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