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