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