Remove runtime toggle for pointer-lock
[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 setHiddenPageDOMTimerThrottlingEnabled:NO];
999     [preferences setHiddenPageCSSAnimationSuspensionEnabled:NO];
1000
1001     preferences.intersectionObserverEnabled = options.enableIntersectionObserver;
1002     preferences.modernMediaControlsEnabled = options.enableModernMediaControls;
1003
1004     [preferences setSubtleCryptoEnabled:YES];
1005
1006     [WebPreferences _clearNetworkLoaderSession];
1007     [WebPreferences _setCurrentNetworkLoaderSessionCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
1008 }
1009
1010 // Called once on DumpRenderTree startup.
1011 static void setDefaultsToConsistentValuesForTesting()
1012 {
1013 #if PLATFORM(IOS)
1014     WebThreadLock();
1015 #endif
1016
1017     static const int NoFontSmoothing = 0;
1018     static const int BlueTintedAppearance = 1;
1019
1020     NSString *libraryPath = libraryPathForDumpRenderTree();
1021
1022     NSDictionary *dict = @{
1023         @"AppleKeyboardUIMode": @1,
1024         @"AppleAntiAliasingThreshold": @4,
1025         @"AppleFontSmoothing": @(NoFontSmoothing),
1026         @"AppleAquaColorVariant": @(BlueTintedAppearance),
1027         @"AppleHighlightColor": @"0.709800 0.835300 1.000000",
1028         @"AppleOtherHighlightColor":@"0.500000 0.500000 0.500000",
1029         @"AppleLanguages": @[ @"en" ],
1030         WebKitEnableFullDocumentTeardownPreferenceKey: @YES,
1031         WebKitFullScreenEnabledPreferenceKey: @YES,
1032         WebKitAllowsInlineMediaPlaybackPreferenceKey: @YES,
1033         WebKitInlineMediaPlaybackRequiresPlaysInlineAttributeKey: @NO,
1034         @"UseWebKitWebInspector": @YES,
1035 #if !PLATFORM(IOS)
1036         @"NSPreferredSpellServerLanguage": @"en_US",
1037         @"NSUserDictionaryReplacementItems": @[],
1038         @"NSTestCorrectionDictionary": @{
1039             @"notationl": @"notational",
1040             @"mesage": @"message",
1041             @"wouldn": @"would",
1042             @"wellcome": @"welcome",
1043             @"hellolfworld": @"hello\nworld"
1044         },
1045 #endif
1046         @"AppleScrollBarVariant": @"DoubleMax",
1047 #if !PLATFORM(IOS)
1048         @"NSScrollAnimationEnabled": @NO,
1049 #endif
1050         @"NSOverlayScrollersEnabled": @NO,
1051         @"AppleShowScrollBars": @"Always",
1052         @"NSButtonAnimationsEnabled": @NO, // Ideally, we should find a way to test animations, but for now, make sure that the dumped snapshot matches actual state.
1053 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100 && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1054         @"AppleSystemFontOSSubversion": @(10),
1055 #endif
1056         @"NSWindowDisplayWithRunLoopObserver": @YES, // Temporary workaround, see <rdar://problem/20351297>.
1057         @"AppleEnableSwipeNavigateWithScrolls": @YES,
1058         @"com.apple.swipescrolldirection": @1,
1059     };
1060
1061     [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:dict];
1062
1063 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1064     // Make NSFont use the new defaults.
1065     [NSFont initialize];
1066 #endif
1067
1068     NSDictionary *processInstanceDefaults = @{
1069         WebDatabaseDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"Databases"],
1070         WebStorageDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
1071         WebKitLocalCacheDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalCache"],
1072         WebKitResourceLoadStatisticsDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
1073 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100 && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1074         // This needs to also be added to argument domain because of <rdar://problem/20210002>.
1075         @"AppleSystemFontOSSubversion": @(10),
1076 #endif
1077     };
1078
1079     [[NSUserDefaults standardUserDefaults] setVolatileDomain:processInstanceDefaults forName:NSArgumentDomain];
1080 }
1081
1082 static void runThread(void* arg)
1083 {
1084     static ThreadIdentifier previousId = 0;
1085     ThreadIdentifier currentId = currentThread();
1086     // Verify 2 successive threads do not get the same Id.
1087     ASSERT(previousId != currentId);
1088     previousId = currentId;
1089 }
1090
1091 static void* runPthread(void* arg)
1092 {
1093     runThread(arg);
1094     return 0;
1095 }
1096
1097 static void testThreadIdentifierMap()
1098 {
1099     // Imitate 'foreign' threads that are not created by WTF.
1100     pthread_t pthread;
1101     pthread_create(&pthread, 0, &runPthread, 0);
1102     pthread_join(pthread, 0);
1103
1104     pthread_create(&pthread, 0, &runPthread, 0);
1105     pthread_join(pthread, 0);
1106
1107     // Now create another thread using WTF. On OSX, it will have the same pthread handle
1108     // but should get a different ThreadIdentifier.
1109     createThread(runThread, 0, "DumpRenderTree: test");
1110 }
1111
1112 static void allocateGlobalControllers()
1113 {
1114     // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
1115     gNavigationController = [[NavigationController alloc] init];
1116     frameLoadDelegate = [[FrameLoadDelegate alloc] init];
1117     uiDelegate = [[UIDelegate alloc] init];
1118     editingDelegate = [[EditingDelegate alloc] init];
1119     resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
1120     policyDelegate = [[PolicyDelegate alloc] init];
1121     historyDelegate = [[HistoryDelegate alloc] init];
1122     defaultPolicyDelegate = [[DefaultPolicyDelegate alloc] init];
1123 #if PLATFORM(IOS)
1124     scrollViewResizerDelegate = [[ScrollViewResizerDelegate alloc] init];
1125 #endif
1126 }
1127
1128 // ObjC++ doens't seem to let me pass NSObject*& sadly.
1129 static inline void releaseAndZero(NSObject** object)
1130 {
1131     [*object release];
1132     *object = nil;
1133 }
1134
1135 static void releaseGlobalControllers()
1136 {
1137     releaseAndZero(&gNavigationController);
1138     releaseAndZero(&frameLoadDelegate);
1139     releaseAndZero(&editingDelegate);
1140     releaseAndZero(&resourceLoadDelegate);
1141     releaseAndZero(&uiDelegate);
1142     releaseAndZero(&policyDelegate);
1143 #if PLATFORM(IOS)
1144     releaseAndZero(&scrollViewResizerDelegate);
1145 #endif
1146 }
1147
1148 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
1149 {
1150     struct option options[] = {
1151         {"notree", no_argument, &dumpTree, NO},
1152         {"pixel-tests", no_argument, &dumpPixelsForAllTests, YES},
1153         {"tree", no_argument, &dumpTree, YES},
1154         {"threaded", no_argument, &threaded, YES},
1155         {"complex-text", no_argument, &forceComplexText, YES},
1156         {"accelerated-drawing", no_argument, &useAcceleratedDrawing, YES},
1157         {"gc-between-tests", no_argument, &gcBetweenTests, YES},
1158         {"no-timeout", no_argument, &useTimeoutWatchdog, NO},
1159         {"allowed-host", required_argument, nullptr, 'a'},
1160         {"show-webview", no_argument, &showWebView, YES},
1161         {"print-test-count", no_argument, &printTestCount, YES},
1162         {nullptr, 0, nullptr, 0}
1163     };
1164     
1165     int option;
1166     while ((option = getopt_long(argc, (char * const *)argv, "", options, nullptr)) != -1) {
1167         switch (option) {
1168             case '?':   // unknown or ambiguous option
1169             case ':':   // missing argument
1170                 exit(1);
1171                 break;
1172             case 'a': // "allowed-host"
1173                 allowedHosts.insert(optarg);
1174                 break;
1175         }
1176     }
1177 }
1178
1179 static void addTestPluginsToPluginSearchPath(const char* executablePath)
1180 {
1181 #if !PLATFORM(IOS)
1182     NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
1183     [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
1184     [[WebPluginDatabase sharedDatabase] refresh];
1185 #endif
1186 }
1187
1188 static bool useLongRunningServerMode(int argc, const char *argv[])
1189 {
1190     // This assumes you've already called getopt_long
1191     return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
1192 }
1193
1194 static void runTestingServerLoop()
1195 {
1196     // When DumpRenderTree run in server mode, we just wait around for file names
1197     // to be passed to us and read each in turn, passing the results back to the client
1198     char filenameBuffer[2048];
1199     unsigned testCount = 0;
1200     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1201         char *newLineCharacter = strchr(filenameBuffer, '\n');
1202         if (newLineCharacter)
1203             *newLineCharacter = '\0';
1204
1205         if (strlen(filenameBuffer) == 0)
1206             continue;
1207
1208         runTest(filenameBuffer);
1209
1210         if (printTestCount) {
1211             ++testCount;
1212             printf("\nServer mode has completed %u tests.\n\n", testCount);
1213         }
1214     }
1215 }
1216
1217 static void prepareConsistentTestingEnvironment()
1218 {
1219 #if !PLATFORM(IOS)
1220     poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
1221     poseAsClass("DumpRenderTreeEvent", "NSEvent");
1222 #else
1223     poseAsClass("DumpRenderTreeEvent", "GSEvent");
1224 #endif
1225
1226     [[WebPreferences standardPreferences] setAutosaves:NO];
1227
1228     // +[WebPreferences _switchNetworkLoaderToNewTestingSession] calls +[NSURLCache sharedURLCache], which initializes a default cache on disk.
1229     // Making the shared cache memory-only avoids touching the file system.
1230     RetainPtr<NSURLCache> sharedCache =
1231         adoptNS([[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
1232                                       diskCapacity:0
1233                                           diskPath:nil]);
1234     [NSURLCache setSharedURLCache:sharedCache.get()];
1235
1236     [WebPreferences _switchNetworkLoaderToNewTestingSession];
1237
1238 #if !PLATFORM(IOS)
1239     adjustFonts();
1240     registerMockScrollbars();
1241
1242     // The mock scrollbars setting cannot be modified after creating a view, so we have to do it now.
1243     [[WebPreferences standardPreferences] setMockScrollbarsEnabled:YES];
1244 #else
1245     activateFontsIOS();
1246 #endif
1247     
1248     allocateGlobalControllers();
1249     
1250     makeLargeMallocFailSilently();
1251
1252 #if PLATFORM(MAC)
1253     NSActivityOptions options = (NSActivityUserInitiatedAllowingIdleSystemSleep | NSActivityLatencyCritical) & ~(NSActivitySuddenTerminationDisabled | NSActivityAutomaticTerminationDisabled);
1254     static id assertion = [[[NSProcessInfo processInfo] beginActivityWithOptions:options reason:@"DumpRenderTree should not be subject to process suppression"] retain];
1255     ASSERT_UNUSED(assertion, assertion);
1256 #endif
1257 }
1258
1259 const char crashedMessage[] = "#CRASHED\n";
1260
1261 void writeCrashedMessageOnFatalError(int signalCode)
1262 {
1263     // Reset the default action for the signal so that we run ReportCrash(8) on pending and
1264     // subsequent instances of the signal.
1265     signal(signalCode, SIG_DFL);
1266
1267     // WRITE(2) and FSYNC(2) are considered safe to call from a signal handler by SIGACTION(2).
1268     write(STDERR_FILENO, &crashedMessage[0], sizeof(crashedMessage) - 1);
1269     fsync(STDERR_FILENO);
1270 }
1271
1272 void dumpRenderTree(int argc, const char *argv[])
1273 {
1274 #if PLATFORM(IOS)
1275     const char* identifier = getenv("IPC_IDENTIFIER");
1276     const char *stdinPath = [[NSString stringWithFormat:@"/tmp/%s_IN", identifier] UTF8String];
1277     const char *stdoutPath = [[NSString stringWithFormat:@"/tmp/%s_OUT", identifier] UTF8String];
1278     const char *stderrPath = [[NSString stringWithFormat:@"/tmp/%s_ERROR", identifier] UTF8String];
1279
1280     int infd = open(stdinPath, O_RDWR);
1281     dup2(infd, STDIN_FILENO);
1282     int outfd = open(stdoutPath, O_RDWR);
1283     dup2(outfd, STDOUT_FILENO);
1284     int errfd = open(stderrPath, O_RDWR | O_NONBLOCK);
1285     dup2(errfd, STDERR_FILENO);
1286 #endif
1287
1288     signal(SIGILL, &writeCrashedMessageOnFatalError);
1289     signal(SIGFPE, &writeCrashedMessageOnFatalError);
1290     signal(SIGBUS, &writeCrashedMessageOnFatalError);
1291     signal(SIGSEGV, &writeCrashedMessageOnFatalError);
1292
1293     initializeGlobalsFromCommandLineOptions(argc, argv);
1294     prepareConsistentTestingEnvironment();
1295     addTestPluginsToPluginSearchPath(argv[0]);
1296
1297     if (forceComplexText)
1298         [WebView _setAlwaysUsesComplexTextCodePath:YES];
1299
1300 #if USE(APPKIT)
1301     [NSSound _setAlertType:0];
1302 #endif
1303
1304     WebView *webView = createWebViewAndOffscreenWindow();
1305     mainFrame = [webView mainFrame];
1306
1307     [[NSURLCache sharedURLCache] removeAllCachedResponses];
1308     [WebCache empty];
1309
1310     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
1311     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
1312
1313     // http://webkit.org/b/32689
1314     testThreadIdentifierMap();
1315
1316     if (threaded)
1317         startJavaScriptThreads();
1318
1319     if (useLongRunningServerMode(argc, argv)) {
1320         printSeparators = YES;
1321         runTestingServerLoop();
1322     } else {
1323         printSeparators = optind < argc - 1;
1324         for (int i = optind; i != argc; ++i)
1325             runTest(argv[i]);
1326     }
1327
1328     if (threaded)
1329         stopJavaScriptThreads();
1330
1331     destroyWebViewAndOffscreenWindow(webView);
1332     
1333     releaseGlobalControllers();
1334     
1335 #if !PLATFORM(IOS)
1336     [DumpRenderTreePasteboard releaseLocalPasteboards];
1337 #endif
1338
1339     // FIXME: This should be moved onto TestRunner and made into a HashSet
1340     if (disallowedURLs) {
1341         CFRelease(disallowedURLs);
1342         disallowedURLs = 0;
1343     }
1344
1345 #if PLATFORM(IOS)
1346     close(infd);
1347     close(outfd);
1348     close(errfd);
1349 #endif
1350 }
1351
1352 #if PLATFORM(IOS)
1353 static int _argc;
1354 static const char **_argv;
1355
1356 @implementation DumpRenderTree
1357
1358 - (void)_runDumpRenderTree
1359 {
1360     dumpRenderTree(_argc, _argv);
1361 }
1362
1363 - (void)applicationDidFinishLaunching:(NSNotification *)notification
1364 {
1365     [self performSelectorOnMainThread:@selector(_runDumpRenderTree) withObject:nil waitUntilDone:NO];
1366 }
1367
1368 - (void)applicationDidEnterBackground:(UIApplication *)application
1369 {
1370     RELEASE_ASSERT_NOT_REACHED();
1371 }
1372
1373 - (void)_webThreadEventLoopHasRun
1374 {
1375     ASSERT(!WebThreadIsCurrent());
1376     _hasFlushedWebThreadRunQueue = YES;
1377 }
1378
1379 - (void)_webThreadInvoked
1380 {
1381     ASSERT(WebThreadIsCurrent());
1382     dispatch_async(dispatch_get_main_queue(), ^{
1383         [self _webThreadEventLoopHasRun];
1384     });
1385 }
1386
1387 // The test can end in response to a delegate callback while there are still methods queued on the Web Thread.
1388 // If we do not ensure the Web Thread has been run, the callback can be done on a WebView that no longer exists.
1389 // To avoid this, _waitForWebThread dispatches a call to the WebThread event loop, actively processing the delegate
1390 // callbacks in the main thread while waiting for the call to be invoked on the Web Thread.
1391 - (void)_waitForWebThread
1392 {
1393     ASSERT(!WebThreadIsCurrent());
1394     _hasFlushedWebThreadRunQueue = NO;
1395     WebThreadRun(^{
1396         [self _webThreadInvoked];
1397     });
1398     while (!_hasFlushedWebThreadRunQueue) {
1399         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1400         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1401         [pool release];
1402     }
1403 }
1404
1405 @end
1406 #endif
1407
1408 static bool returningFromMain = false;
1409
1410 void atexitFunction()
1411 {
1412     if (returningFromMain)
1413         return;
1414
1415     NSLog(@"DumpRenderTree is exiting unexpectedly. Generating a crash log.");
1416     __builtin_trap();
1417 }
1418
1419 int DumpRenderTreeMain(int argc, const char *argv[])
1420 {
1421     atexit(atexitFunction);
1422
1423 #if PLATFORM(IOS)
1424     _UIApplicationLoadWebKit();
1425 #endif
1426     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1427
1428     setDefaultsToConsistentValuesForTesting(); // Must be called before NSApplication initialization.
1429
1430 #if !PLATFORM(IOS)
1431     [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
1432
1433     dumpRenderTree(argc, argv);
1434 #else
1435     _argc = argc;
1436     _argv = argv;
1437     UIApplicationMain(argc, (char**)argv, @"DumpRenderTree", @"DumpRenderTree");
1438 #endif
1439     [WebCoreStatistics garbageCollectJavaScriptObjects];
1440     [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
1441     JSC::finalizeStatsAtEndOfTesting();
1442     [pool release];
1443     returningFromMain = true;
1444     return 0;
1445 }
1446
1447 static NSInteger compareHistoryItems(id item1, id item2, void *context)
1448 {
1449     return [[item1 target] caseInsensitiveCompare:[item2 target]];
1450 }
1451
1452 static NSData *dumpAudio()
1453 {
1454     const vector<char>& dataVector = gTestRunner->audioResult();
1455     
1456     NSData *data = [NSData dataWithBytes:dataVector.data() length:dataVector.size()];
1457     return data;
1458 }
1459
1460 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
1461 {
1462     int start = 0;
1463     if (current) {
1464         printf("curr->");
1465         start = 6;
1466     }
1467     for (int i = start; i < indent; i++)
1468         putchar(' ');
1469     
1470     NSString *urlString = [item URLString];
1471     if ([[NSURL URLWithString:urlString] isFileURL]) {
1472         NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
1473         urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
1474     }
1475     
1476     printf("%s", [urlString UTF8String]);
1477     NSString *target = [item target];
1478     if (target && [target length] > 0)
1479         printf(" (in frame \"%s\")", [target UTF8String]);
1480     if ([item isTargetItem])
1481         printf("  **nav target**");
1482     putchar('\n');
1483     NSArray *kids = [item children];
1484     if (kids) {
1485         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
1486         kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
1487         for (unsigned i = 0; i < [kids count]; i++)
1488             dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
1489     }
1490 }
1491
1492 static void dumpFrameScrollPosition(WebFrame *f)
1493 {
1494     WebScriptObject* scriptObject = [f windowObject];
1495     NSPoint scrollPosition = NSMakePoint(
1496         [[scriptObject valueForKey:@"pageXOffset"] floatValue],
1497         [[scriptObject valueForKey:@"pageYOffset"] floatValue]);
1498     if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
1499         if ([f parentFrame] != nil)
1500             printf("frame '%s' ", [[f name] UTF8String]);
1501         printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
1502     }
1503
1504     if (gTestRunner->dumpChildFrameScrollPositions()) {
1505         NSArray *kids = [f childFrames];
1506         if (kids)
1507             for (unsigned i = 0; i < [kids count]; i++)
1508                 dumpFrameScrollPosition([kids objectAtIndex:i]);
1509     }
1510 }
1511
1512 static NSString *dumpFramesAsText(WebFrame *frame)
1513 {
1514     DOMDocument *document = [frame DOMDocument];
1515     DOMElement *documentElement = [document documentElement];
1516
1517     if (!documentElement)
1518         return @"";
1519
1520     NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
1521
1522     // Add header for all but the main frame.
1523     if ([frame parentFrame])
1524         result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
1525
1526     NSString *innerText = [documentElement innerText];
1527     // We use WKStringGetUTF8CStringNonStrict() to convert innerText to a WK String since
1528     // WKStringGetUTF8CStringNonStrict() can handle dangling surrogates and the NSString
1529     // conversion methods cannot. After the conversion to a buffer, we turn that buffer into
1530     // a CFString via fromUTF8WithLatin1Fallback().createCFString() which can be appended to
1531     // the result without any conversion.
1532     WKRetainPtr<WKStringRef> stringRef(AdoptWK, WKStringCreateWithCFString((CFStringRef)innerText));
1533     size_t bufferSize = WKStringGetMaximumUTF8CStringSize(stringRef.get());
1534     auto buffer = std::make_unique<char[]>(bufferSize);
1535     size_t stringLength = WKStringGetUTF8CStringNonStrict(stringRef.get(), buffer.get(), bufferSize);
1536     [result appendFormat:@"%@\n", String::fromUTF8WithLatin1Fallback(buffer.get(), stringLength - 1).createCFString().get()];
1537
1538     if (gTestRunner->dumpChildFramesAsText()) {
1539         NSArray *kids = [frame childFrames];
1540         if (kids) {
1541             for (unsigned i = 0; i < [kids count]; i++)
1542                 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
1543         }
1544     }
1545
1546     return result;
1547 }
1548
1549 static NSData *dumpFrameAsPDF(WebFrame *frame)
1550 {
1551 #if !PLATFORM(IOS)
1552     if (!frame)
1553         return nil;
1554
1555     // Sadly we have to dump to a file and then read from that file again
1556     // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
1557     // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
1558     // The goal of this function is to test "real" printing across multiple pages.
1559     // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
1560     NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
1561
1562     NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
1563     [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
1564     [printInfoDict setObject:path forKey:NSPrintSavePath];
1565
1566     NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
1567     [printInfo setHorizontalPagination:NSAutoPagination];
1568     [printInfo setVerticalPagination:NSAutoPagination];
1569     [printInfo setVerticallyCentered:NO];
1570
1571     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
1572     [printOperation setShowPanels:NO];
1573     [printOperation runOperation];
1574
1575     [printInfo release];
1576
1577     NSData *pdfData = [NSData dataWithContentsOfFile:path];
1578     [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
1579
1580     return pdfData;
1581 #else
1582     return nil;
1583 #endif
1584 }
1585
1586 static void dumpBackForwardListForWebView(WebView *view)
1587 {
1588     printf("\n============== Back Forward List ==============\n");
1589     WebBackForwardList *bfList = [view backForwardList];
1590
1591     // Print out all items in the list after prevTestBFItem, which was from the previous test
1592     // Gather items from the end of the list, the print them out from oldest to newest
1593     NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
1594     for (int i = [bfList forwardListCount]; i > 0; i--) {
1595         WebHistoryItem *item = [bfList itemAtIndex:i];
1596         // something is wrong if the item from the last test is in the forward part of the b/f list
1597         assert(item != prevTestBFItem);
1598         [itemsToPrint addObject:item];
1599     }
1600             
1601     assert([bfList currentItem] != prevTestBFItem);
1602     [itemsToPrint addObject:[bfList currentItem]];
1603     int currentItemIndex = [itemsToPrint count] - 1;
1604
1605     for (int i = -1; i >= -[bfList backListCount]; i--) {
1606         WebHistoryItem *item = [bfList itemAtIndex:i];
1607         if (item == prevTestBFItem)
1608             break;
1609         [itemsToPrint addObject:item];
1610     }
1611
1612     for (int i = [itemsToPrint count]-1; i >= 0; i--)
1613         dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1614
1615     [itemsToPrint release];
1616     printf("===============================================\n");
1617 }
1618
1619 #if !PLATFORM(IOS)
1620 static void changeWindowScaleIfNeeded(const char* testPathOrUR)
1621 {
1622     WTF::String localPathOrUrl = String(testPathOrUR);
1623     float currentScaleFactor = [[[mainFrame webView] window] backingScaleFactor];
1624     float requiredScaleFactor = 1;
1625     if (localPathOrUrl.findIgnoringCase("/hidpi-3x-") != notFound)
1626         requiredScaleFactor = 3;
1627     else if (localPathOrUrl.findIgnoringCase("/hidpi-") != notFound)
1628         requiredScaleFactor = 2;
1629     if (currentScaleFactor == requiredScaleFactor)
1630         return;
1631     // 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.
1632     gTestRunner->setBackingScaleFactor(requiredScaleFactor);
1633     [[[mainFrame webView] window] _setWindowResolution:requiredScaleFactor displayIfChanged:YES];
1634 }
1635 #endif
1636
1637 static void sizeWebViewForCurrentTest()
1638 {
1639     [uiDelegate resetWindowOrigin];
1640
1641     // W3C SVG tests expect to be 480x360
1642     bool isSVGW3CTest = (gTestRunner->testURL().find("svg/W3C-SVG-1.1") != string::npos);
1643     if (isSVGW3CTest)
1644         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::w3cSVGViewWidth, TestRunner::w3cSVGViewHeight)];
1645     else
1646         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::viewWidth, TestRunner::viewHeight)];
1647 }
1648
1649 static const char *methodNameStringForFailedTest()
1650 {
1651     const char *errorMessage;
1652     if (gTestRunner->dumpAsText())
1653         errorMessage = "[documentElement innerText]";
1654     else if (gTestRunner->dumpDOMAsWebArchive())
1655         errorMessage = "[[mainFrame DOMDocument] webArchive]";
1656     else if (gTestRunner->dumpSourceAsWebArchive())
1657         errorMessage = "[[mainFrame dataSource] webArchive]";
1658     else
1659         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1660
1661     return errorMessage;
1662 }
1663
1664 static void dumpBackForwardListForAllWindows()
1665 {
1666     CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1667     unsigned count = CFArrayGetCount(openWindows);
1668     for (unsigned i = 0; i < count; i++) {
1669         NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1670 #if !PLATFORM(IOS)
1671         WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1672 #else
1673         ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1674         WebView *webView = (WebView *)[window contentView];
1675 #endif
1676         dumpBackForwardListForWebView(webView);
1677     }
1678 }
1679
1680 static void invalidateAnyPreviousWaitToDumpWatchdog()
1681 {
1682     if (waitToDumpWatchdog) {
1683         CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1684         CFRelease(waitToDumpWatchdog);
1685         waitToDumpWatchdog = 0;
1686     }
1687 }
1688
1689 void setWaitToDumpWatchdog(CFRunLoopTimerRef timer)
1690 {
1691     ASSERT(timer);
1692     ASSERT(shouldSetWaitToDumpWatchdog());
1693     waitToDumpWatchdog = timer;
1694     CFRunLoopAddTimer(CFRunLoopGetCurrent(), waitToDumpWatchdog, kCFRunLoopCommonModes);
1695 }
1696
1697 bool shouldSetWaitToDumpWatchdog()
1698 {
1699     return !waitToDumpWatchdog && useTimeoutWatchdog;
1700 }
1701
1702 static void updateDisplay()
1703 {
1704     WebView *webView = [mainFrame webView];
1705 #if PLATFORM(IOS)
1706     [gWebBrowserView layoutIfNeeded]; // Re-enables tile painting, which was disabled when committing the frame load.
1707     [gDrtWindow layoutTilesNow];
1708     [webView _flushCompositingChanges];
1709 #else
1710     if ([webView _isUsingAcceleratedCompositing])
1711         [webView display];
1712     else
1713         [webView displayIfNeeded];
1714 #endif
1715 }
1716
1717 void dump()
1718 {
1719 #if PLATFORM(IOS)
1720     WebThreadLock();
1721 #endif
1722
1723     updateDisplay();
1724
1725     invalidateAnyPreviousWaitToDumpWatchdog();
1726     ASSERT(!gTestRunner->hasPendingWebNotificationClick());
1727
1728     if (dumpTree) {
1729         NSString *resultString = nil;
1730         NSData *resultData = nil;
1731         NSString *resultMimeType = @"text/plain";
1732
1733         if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
1734             gTestRunner->setDumpAsText(true);
1735             gTestRunner->setGeneratePixelResults(false);
1736         }
1737         if (gTestRunner->dumpAsAudio()) {
1738             resultData = dumpAudio();
1739             resultMimeType = @"audio/wav";
1740         } else if (gTestRunner->dumpAsText()) {
1741             resultString = dumpFramesAsText(mainFrame);
1742         } else if (gTestRunner->dumpAsPDF()) {
1743             resultData = dumpFrameAsPDF(mainFrame);
1744             resultMimeType = @"application/pdf";
1745         } else if (gTestRunner->dumpDOMAsWebArchive()) {
1746             WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1747             resultString = CFBridgingRelease(createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1748             resultMimeType = @"application/x-webarchive";
1749         } else if (gTestRunner->dumpSourceAsWebArchive()) {
1750             WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1751             resultString = CFBridgingRelease(createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1752             resultMimeType = @"application/x-webarchive";
1753         } else
1754             resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gTestRunner->isPrinting()];
1755
1756         if (resultString && !resultData)
1757             resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1758
1759         printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1760
1761         WTF::FastMallocStatistics mallocStats = WTF::fastMallocStatistics();
1762         printf("DumpMalloc: %li\n", mallocStats.committedVMBytes);
1763
1764         if (gTestRunner->dumpAsAudio())
1765             printf("Content-Length: %lu\n", static_cast<unsigned long>([resultData length]));
1766
1767         if (resultData) {
1768             fwrite([resultData bytes], 1, [resultData length], stdout);
1769
1770             if (!gTestRunner->dumpAsText() && !gTestRunner->dumpDOMAsWebArchive() && !gTestRunner->dumpSourceAsWebArchive() && !gTestRunner->dumpAsAudio())
1771                 dumpFrameScrollPosition(mainFrame);
1772
1773             if (gTestRunner->dumpBackForwardList())
1774                 dumpBackForwardListForAllWindows();
1775         } else
1776             printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1777
1778         // Stop the watchdog thread before we leave this test to make sure it doesn't
1779         // fire in between tests causing the next test to fail.
1780         // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1781         invalidateAnyPreviousWaitToDumpWatchdog();
1782
1783         if (printSeparators)
1784             puts("#EOF");       // terminate the content block
1785     }
1786
1787     if (dumpPixelsForCurrentTest && gTestRunner->generatePixelResults())
1788         // FIXME: when isPrinting is set, dump the image with page separators.
1789         dumpWebViewAsPixelsAndCompareWithExpected(gTestRunner->expectedPixelHash());
1790
1791     puts("#EOF");   // terminate the (possibly empty) pixels block
1792     fflush(stdout);
1793
1794     done = YES;
1795     CFRunLoopStop(CFRunLoopGetMain());
1796 }
1797
1798 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1799 {
1800     return strstr(pathOrURL, "loading/");
1801 }
1802
1803 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1804 {
1805     return strstr(pathOrURL, "globalhistory/");
1806 }
1807
1808 static bool shouldDumpAsText(const char* pathOrURL)
1809 {
1810     return strstr(pathOrURL, "dumpAsText/");
1811 }
1812
1813 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1814 {
1815     return true;
1816 }
1817
1818 #if PLATFORM(IOS)
1819 static bool shouldMakeViewportFlexible(const char* pathOrURL)
1820 {
1821     return strstr(pathOrURL, "viewport/") && !strstr(pathOrURL, "visual-viewport/");
1822 }
1823 #endif
1824
1825 static void resetWebViewToConsistentStateBeforeTesting(const TestOptions& options)
1826 {
1827     WebView *webView = [mainFrame webView];
1828 #if PLATFORM(IOS)
1829     adjustWebDocumentForStandardViewport(gWebBrowserView, gWebScrollView);
1830     [webView _setAllowsMessaging:YES];
1831 #endif
1832     [webView setEditable:NO];
1833     [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1834     [webView makeTextStandardSize:nil];
1835     [webView resetPageZoom:nil];
1836     [webView _scaleWebView:1.0 atOrigin:NSZeroPoint];
1837 #if !PLATFORM(IOS)
1838     [webView _setCustomBackingScaleFactor:0];
1839 #endif
1840     [webView setTabKeyCyclesThroughElements:YES];
1841     [webView setPolicyDelegate:defaultPolicyDelegate];
1842     [policyDelegate setPermissive:NO];
1843     [policyDelegate setControllerToNotifyDone:0];
1844     [frameLoadDelegate resetToConsistentState];
1845 #if !PLATFORM(IOS)
1846     [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1847 #endif
1848     [webView _clearMainFrameName];
1849     [[webView undoManager] removeAllActions];
1850     [WebView _removeAllUserContentFromGroup:[webView groupName]];
1851 #if !PLATFORM(IOS)
1852     [[webView window] setAutodisplay:NO];
1853 #endif
1854     [webView setTracksRepaints:NO];
1855
1856     [WebCache clearCachedCredentials];
1857     
1858     resetWebPreferencesToConsistentValues(options);
1859
1860     TestRunner::setSerializeHTTPLoads(false);
1861     TestRunner::setAllowsAnySSLCertificate(false);
1862
1863     setlocale(LC_ALL, "");
1864
1865     if (gTestRunner) {
1866         WebCoreTestSupport::resetInternalsObject([mainFrame globalContext]);
1867         // in the case that a test using the chrome input field failed, be sure to clean up for the next test
1868         gTestRunner->removeChromeInputField();
1869     }
1870
1871 #if !PLATFORM(IOS)
1872     if (WebCore::Frame* frame = [webView _mainCoreFrame])
1873         WebCoreTestSupport::clearWheelEventTestTrigger(*frame);
1874 #endif
1875
1876 #if !PLATFORM(IOS)
1877     [webView setContinuousSpellCheckingEnabled:YES];
1878     [webView setAutomaticQuoteSubstitutionEnabled:NO];
1879     [webView setAutomaticLinkDetectionEnabled:NO];
1880     [webView setAutomaticDashSubstitutionEnabled:NO];
1881     [webView setAutomaticTextReplacementEnabled:NO];
1882     [webView setAutomaticSpellingCorrectionEnabled:YES];
1883     [webView setGrammarCheckingEnabled:YES];
1884
1885     [WebView _setUsesTestModeFocusRingColor:YES];
1886 #endif
1887     [WebView _resetOriginAccessWhitelists];
1888
1889     [[MockGeolocationProvider shared] stopTimer];
1890     [[MockWebNotificationProvider shared] reset];
1891     
1892 #if !PLATFORM(IOS)
1893     // Clear the contents of the general pasteboard
1894     [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1895 #endif
1896
1897     [mainFrame _clearOpener];
1898
1899     resetAccumulatedLogs();
1900     WebCoreTestSupport::initializeLogChannelsIfNecessary();
1901 }
1902
1903 #if PLATFORM(IOS)
1904 // Work around <rdar://problem/9909073> WebKit's method of calling delegates on
1905 // the main thread is not thread safe. If the web thread is attempting to call
1906 // out to a delegate method on the main thread, we want to spin the main thread
1907 // run loop until the delegate method completes before taking the web thread
1908 // lock to prevent potentially re-entering WebCore.
1909 static void WebThreadLockAfterDelegateCallbacksHaveCompleted()
1910 {
1911     dispatch_semaphore_t delegateSemaphore = dispatch_semaphore_create(0);
1912     WebThreadRun(^{
1913         dispatch_semaphore_signal(delegateSemaphore);
1914     });
1915
1916     while (dispatch_semaphore_wait(delegateSemaphore, DISPATCH_TIME_NOW)) {
1917         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1918         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1919         [pool release];
1920     }
1921
1922     WebThreadLock();
1923     
1924     dispatch_release(delegateSemaphore);
1925 }
1926 #endif
1927
1928 static NSURL *computeTestURL(NSString *pathOrURLString, NSString **relativeTestPath)
1929 {
1930     *relativeTestPath = nil;
1931
1932     if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"] || [pathOrURLString hasPrefix:@"file://"])
1933         return [NSURL URLWithString:pathOrURLString];
1934
1935     NSString *absolutePath = [[[NSURL fileURLWithPath:pathOrURLString] absoluteURL] path];
1936
1937     NSRange layoutTestsRange = [absolutePath rangeOfString:@"/LayoutTests/"];
1938     if (layoutTestsRange.location == NSNotFound)
1939         return [NSURL fileURLWithPath:absolutePath];
1940
1941     *relativeTestPath = [absolutePath substringFromIndex:NSMaxRange(layoutTestsRange)];
1942
1943     // Convert file URLs in LayoutTests/http/tests to HTTP URLs, except for file URLs in LayoutTests/http/tests/local.
1944
1945     NSRange httpTestsRange = [absolutePath rangeOfString:@"/LayoutTests/http/tests/"];
1946     if (httpTestsRange.location == NSNotFound || [absolutePath rangeOfString:@"/LayoutTests/http/tests/local/"].location != NSNotFound)
1947         return [NSURL fileURLWithPath:absolutePath];
1948
1949     auto components = adoptNS([[NSURLComponents alloc] init]);
1950     [components setPath:[absolutePath substringFromIndex:NSMaxRange(httpTestsRange) - 1]];
1951     [components setHost:@"127.0.0.1"];
1952
1953     // Paths under /ssl/ should be loaded using HTTPS.
1954     BOOL isSecure = [[components path] hasPrefix:@"/ssl/"];
1955     if (isSecure) {
1956         [components setScheme:@"https"];
1957         [components setPort:@(8443)];
1958     } else {
1959         [components setScheme:@"http"];
1960         [components setPort:@(8000)];
1961     }
1962
1963     return [components URL];
1964 }
1965
1966 static void runTest(const string& inputLine)
1967 {
1968     ASSERT(!inputLine.empty());
1969
1970     TestCommand command = parseInputLine(inputLine);
1971     const string& pathOrURL = command.pathOrURL;
1972     dumpPixelsForCurrentTest = command.shouldDumpPixels || dumpPixelsForAllTests;
1973
1974     NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1975     if (!pathOrURLString) {
1976         fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1977         return;
1978     }
1979
1980     NSString *testPath;
1981     NSURL *url = computeTestURL(pathOrURLString, &testPath);
1982     if (!url) {
1983         fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1984         return;
1985     }
1986     if (!testPath)
1987         testPath = [url absoluteString];
1988
1989     NSString *informationString = [@"CRASHING TEST: " stringByAppendingString:testPath];
1990     WKSetCrashReportApplicationSpecificInformation((CFStringRef)informationString);
1991
1992     TestOptions options(url);
1993     resetWebViewToConsistentStateBeforeTesting(options);
1994
1995     const char* testURL([[url absoluteString] UTF8String]);
1996
1997 #if !PLATFORM(IOS)
1998     changeWindowScaleIfNeeded(testURL);
1999 #endif
2000
2001     gTestRunner = TestRunner::create(testURL, command.expectedPixelHash);
2002     gTestRunner->setAllowedHosts(allowedHosts);
2003     gTestRunner->setCustomTimeout(command.timeout);
2004     topLoadingFrame = nil;
2005 #if !PLATFORM(IOS)
2006     ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
2007     releaseAndZero(&draggingInfo);
2008 #endif
2009     done = NO;
2010
2011     sizeWebViewForCurrentTest();
2012     gTestRunner->setIconDatabaseEnabled(false);
2013     gTestRunner->clearAllApplicationCaches();
2014
2015     if (disallowedURLs)
2016         CFSetRemoveAllValues(disallowedURLs);
2017     if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
2018         gTestRunner->setDumpFrameLoadCallbacks(true);
2019
2020     if (shouldLogHistoryDelegates(pathOrURL.c_str()))
2021         [[mainFrame webView] setHistoryDelegate:historyDelegate];
2022     else
2023         [[mainFrame webView] setHistoryDelegate:nil];
2024
2025     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2026         gTestRunner->setDeveloperExtrasEnabled(true);
2027         if (shouldDumpAsText(pathOrURL.c_str())) {
2028             gTestRunner->setDumpAsText(true);
2029             gTestRunner->setGeneratePixelResults(false);
2030         }
2031     }
2032
2033 #if PLATFORM(IOS)
2034     if (shouldMakeViewportFlexible(pathOrURL.c_str()))
2035         adjustWebDocumentForFlexibleViewport(gWebBrowserView, gWebScrollView);
2036 #endif
2037
2038     if ([WebHistory optionalSharedHistory])
2039         [WebHistory setOptionalSharedHistory:nil];
2040
2041     lastMousePosition = NSZeroPoint;
2042     lastClickPosition = NSZeroPoint;
2043
2044     [prevTestBFItem release];
2045     prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
2046
2047     auto& workQueue = WorkQueue::singleton();
2048     workQueue.clear();
2049     workQueue.setFrozen(false);
2050
2051     bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
2052     if (ignoreWebCoreNodeLeaks)
2053         [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
2054
2055     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2056     [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
2057     [pool release];
2058
2059     while (!done) {
2060         pool = [[NSAutoreleasePool alloc] init];
2061         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
2062         [pool release];
2063     }
2064
2065 #if PLATFORM(IOS)
2066     [(DumpRenderTree *)UIApp _waitForWebThread];
2067     WebThreadLockAfterDelegateCallbacksHaveCompleted();
2068 #endif
2069     pool = [[NSAutoreleasePool alloc] init];
2070     [EventSendingController clearSavedEvents];
2071     [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
2072
2073     workQueue.clear();
2074
2075     // If the test page could have possibly opened the Web Inspector frontend,
2076     // then try to close it in case it was accidentally left open.
2077     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2078         gTestRunner->closeWebInspector();
2079         gTestRunner->setDeveloperExtrasEnabled(false);
2080     }
2081
2082     if (gTestRunner->closeRemainingWindowsWhenComplete()) {
2083         NSArray* array = [DumpRenderTreeWindow openWindows];
2084
2085         unsigned count = [array count];
2086         for (unsigned i = 0; i < count; i++) {
2087             NSWindow *window = [array objectAtIndex:i];
2088
2089             // Don't try to close the main window
2090             if (window == [[mainFrame webView] window])
2091                 continue;
2092             
2093 #if !PLATFORM(IOS)
2094             WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
2095 #else
2096             ASSERT([[window contentView] isKindOfClass:[WebView class]]);
2097             WebView *webView = (WebView *)[window contentView];
2098 #endif
2099
2100             [webView close];
2101             [window close];
2102         }
2103     }
2104
2105     resetWebViewToConsistentStateBeforeTesting(options);
2106
2107     // Loading an empty request synchronously replaces the document with a blank one, which is necessary
2108     // to stop timers, WebSockets and other activity that could otherwise spill output into next test's results.
2109     [mainFrame loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
2110
2111     [pool release];
2112
2113     // We should only have our main window left open when we're done
2114     ASSERT(CFArrayGetCount(openWindowsRef) == 1);
2115     ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
2116
2117     gTestRunner->cleanup();
2118     gTestRunner = nullptr;
2119
2120     if (ignoreWebCoreNodeLeaks)
2121         [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
2122
2123     if (gcBetweenTests)
2124         [WebCoreStatistics garbageCollectJavaScriptObjects];
2125
2126     fputs("#EOF\n", stderr);
2127     fflush(stderr);
2128 }
2129
2130 void displayWebView()
2131 {
2132 #if !PLATFORM(IOS)
2133     WebView *webView = [mainFrame webView];
2134     [webView display];
2135
2136     // FIXME: Tracking repaints is not specific to Mac. We should enable such support on iOS.
2137     [webView setTracksRepaints:YES];
2138     [webView resetTrackedRepaints];
2139 #else
2140     [gDrtWindow layoutTilesNow];
2141     [gDrtWindow setNeedsDisplayInRect:[gDrtWindow frame]];
2142     [CATransaction flush];
2143 #endif
2144 }
2145
2146 #if !PLATFORM(IOS)
2147 @implementation DumpRenderTreeEvent
2148
2149 + (NSPoint)mouseLocation
2150 {
2151     return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
2152 }
2153
2154 @end
2155
2156 @implementation DumpRenderTreeApplication
2157
2158 - (BOOL)isRunning
2159 {
2160     // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running
2161     return YES;
2162 }
2163
2164 @end
2165 #endif