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