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