[WTF] Introduce Thread class and use RefPtr<Thread> and align Windows Threading imple...
[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     // FIXME: SpringTimingFunction
842     [preferences setGamepadsEnabled:YES];
843     [preferences setLinkPreloadEnabled:YES];
844     [preferences setModernMediaControlsEnabled:YES];
845     // FIXME: InputEvents
846     [preferences setResourceTimingEnabled:YES];
847     [preferences setSubtleCryptoEnabled:YES];
848     [preferences setUserTimingEnabled:YES];
849     [preferences setWebAnimationsEnabled:YES];
850     [preferences setWebGL2Enabled:YES];
851     [preferences setWebGPUEnabled:YES];
852     [preferences setPeerConnectionEnabled:YES];
853     [preferences setWebRTCLegacyAPIEnabled:YES];
854     [preferences setCredentialManagementEnabled:YES];
855 }
856
857 // Called before each test.
858 static void resetWebPreferencesToConsistentValues()
859 {
860     WebPreferences *preferences = [WebPreferences standardPreferences];
861     enableExperimentalFeatures(preferences);
862
863     [preferences setNeedsStorageAccessFromFileURLsQuirk: NO];
864     [preferences setAllowUniversalAccessFromFileURLs:YES];
865     [preferences setAllowFileAccessFromFileURLs:YES];
866     [preferences setStandardFontFamily:@"Times"];
867     [preferences setFixedFontFamily:@"Courier"];
868     [preferences setSerifFontFamily:@"Times"];
869     [preferences setSansSerifFontFamily:@"Helvetica"];
870     [preferences setCursiveFontFamily:@"Apple Chancery"];
871     [preferences setFantasyFontFamily:@"Papyrus"];
872     [preferences setPictographFontFamily:@"Apple Color Emoji"];
873     [preferences setDefaultFontSize:16];
874     [preferences setDefaultFixedFontSize:13];
875     [preferences setMinimumFontSize:0];
876     [preferences setDefaultTextEncodingName:@"ISO-8859-1"];
877     [preferences setJavaEnabled:NO];
878     [preferences setJavaScriptEnabled:YES];
879     [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
880 #if !PLATFORM(IOS)
881     [preferences setTabsToLinks:NO];
882 #endif
883     [preferences setDOMPasteAllowed:YES];
884 #if !PLATFORM(IOS)
885     [preferences setShouldPrintBackgrounds:YES];
886 #endif
887     [preferences setCacheModel:WebCacheModelDocumentBrowser];
888     [preferences setXSSAuditorEnabled:NO];
889     [preferences setExperimentalNotificationsEnabled:NO];
890     [preferences setPlugInsEnabled:YES];
891 #if !PLATFORM(IOS)
892     [preferences setTextAreasAreResizable:YES];
893 #endif
894
895     [preferences setPrivateBrowsingEnabled:NO];
896     [preferences setAuthorAndUserStylesEnabled:YES];
897     [preferences setShrinksStandaloneImagesToFit:YES];
898     [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
899     [preferences setJavaScriptCanAccessClipboard:YES];
900     [preferences setOfflineWebApplicationCacheEnabled:YES];
901     [preferences setDeveloperExtrasEnabled:NO];
902     [preferences setJavaScriptRuntimeFlags:WebKitJavaScriptRuntimeFlagsAllEnabled];
903     [preferences setLoadsImagesAutomatically:YES];
904     [preferences setLoadsSiteIconsIgnoringImageLoadingPreference:NO];
905     [preferences setFrameFlatteningEnabled:NO];
906     [preferences setSpatialNavigationEnabled:NO];
907     [preferences setMetaRefreshEnabled:YES];
908
909     if (persistentUserStyleSheetLocation) {
910         [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
911         [preferences setUserStyleSheetEnabled:YES];
912     } else
913         [preferences setUserStyleSheetEnabled:NO];
914
915     [preferences setMediaPlaybackAllowsInline:YES];
916     [preferences setVideoPlaybackRequiresUserGesture:NO];
917     [preferences setAudioPlaybackRequiresUserGesture:NO];
918     [preferences setMediaDataLoadsAutomatically:YES];
919     [preferences setInvisibleAutoplayNotPermitted:NO];
920     [preferences setSubpixelAntialiasedLayerTextEnabled:NO];
921
922 #if PLATFORM(IOS)
923     // Enable the tracker before creating the first WebView will
924     // cause initialization to use the correct database paths.
925     [preferences setStorageTrackerEnabled:YES];
926 #endif
927
928     [preferences _setTextAutosizingEnabled:NO];
929
930     // The back/forward cache is causing problems due to layouts during transition from one page to another.
931     // So, turn it off for now, but we might want to turn it back on some day.
932     [preferences setUsesPageCache:NO];
933     [preferences setAcceleratedCompositingEnabled:YES];
934 #if USE(CA)
935     [preferences setCanvasUsesAcceleratedDrawing:YES];
936     [preferences setAcceleratedDrawingEnabled:useAcceleratedDrawing];
937 #endif
938     [preferences setUsePreHTML5ParserQuirks:NO];
939     [preferences setAsynchronousSpellCheckingEnabled:NO];
940 #if !PLATFORM(IOS)
941     ASSERT([preferences mockScrollbarsEnabled]);
942 #endif
943
944     [preferences setWebAudioEnabled:YES];
945     [preferences setMediaSourceEnabled:YES];
946
947     [preferences setShadowDOMEnabled:YES];
948     [preferences setCustomElementsEnabled:YES];
949
950     [preferences setWebGL2Enabled:YES];
951     [preferences setWebGPUEnabled:YES];
952
953     [preferences setFetchAPIEnabled:YES];
954
955     [preferences setDownloadAttributeEnabled:YES];
956
957     [preferences setHiddenPageDOMTimerThrottlingEnabled:NO];
958     [preferences setHiddenPageCSSAnimationSuspensionEnabled:NO];
959     
960     [preferences setMediaStreamEnabled: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 #endif
1242
1243     signal(SIGILL, &writeCrashedMessageOnFatalError);
1244     signal(SIGFPE, &writeCrashedMessageOnFatalError);
1245     signal(SIGBUS, &writeCrashedMessageOnFatalError);
1246     signal(SIGSEGV, &writeCrashedMessageOnFatalError);
1247
1248     initializeGlobalsFromCommandLineOptions(argc, argv);
1249     prepareConsistentTestingEnvironment();
1250     addTestPluginsToPluginSearchPath(argv[0]);
1251
1252     if (forceComplexText)
1253         [WebView _setAlwaysUsesComplexTextCodePath:YES];
1254
1255 #if USE(APPKIT)
1256     [NSSound _setAlertType:0];
1257 #endif
1258
1259     WebView *webView = createWebViewAndOffscreenWindow();
1260     mainFrame = [webView mainFrame];
1261
1262     [[NSURLCache sharedURLCache] removeAllCachedResponses];
1263     [WebCache empty];
1264
1265     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
1266     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
1267
1268     // http://webkit.org/b/32689
1269     testThreadIdentifierMap();
1270
1271     if (threaded)
1272         startJavaScriptThreads();
1273
1274     if (useLongRunningServerMode(argc, argv)) {
1275         printSeparators = YES;
1276         runTestingServerLoop();
1277     } else {
1278         printSeparators = optind < argc - 1;
1279         for (int i = optind; i != argc; ++i)
1280             runTest(argv[i]);
1281     }
1282
1283     if (threaded)
1284         stopJavaScriptThreads();
1285
1286     destroyWebViewAndOffscreenWindow(webView);
1287     
1288     releaseGlobalControllers();
1289     
1290 #if !PLATFORM(IOS)
1291     [DumpRenderTreePasteboard releaseLocalPasteboards];
1292 #endif
1293
1294     // FIXME: This should be moved onto TestRunner and made into a HashSet
1295     if (disallowedURLs) {
1296         CFRelease(disallowedURLs);
1297         disallowedURLs = 0;
1298     }
1299
1300 #if PLATFORM(IOS)
1301     tearDownIOSLayoutTestCommunication();
1302 #endif
1303 }
1304
1305 #if PLATFORM(IOS)
1306 static int _argc;
1307 static const char **_argv;
1308
1309 @implementation DumpRenderTree
1310
1311 - (void)_runDumpRenderTree
1312 {
1313     dumpRenderTree(_argc, _argv);
1314 }
1315
1316 - (void)applicationDidFinishLaunching:(NSNotification *)notification
1317 {
1318     [self performSelectorOnMainThread:@selector(_runDumpRenderTree) withObject:nil waitUntilDone:NO];
1319 }
1320
1321 - (void)applicationDidEnterBackground:(UIApplication *)application
1322 {
1323     RELEASE_ASSERT_NOT_REACHED();
1324 }
1325
1326 - (void)_webThreadEventLoopHasRun
1327 {
1328     ASSERT(!WebThreadIsCurrent());
1329     _hasFlushedWebThreadRunQueue = YES;
1330 }
1331
1332 - (void)_webThreadInvoked
1333 {
1334     ASSERT(WebThreadIsCurrent());
1335     dispatch_async(dispatch_get_main_queue(), ^{
1336         [self _webThreadEventLoopHasRun];
1337     });
1338 }
1339
1340 // The test can end in response to a delegate callback while there are still methods queued on the Web Thread.
1341 // If we do not ensure the Web Thread has been run, the callback can be done on a WebView that no longer exists.
1342 // To avoid this, _waitForWebThread dispatches a call to the WebThread event loop, actively processing the delegate
1343 // callbacks in the main thread while waiting for the call to be invoked on the Web Thread.
1344 - (void)_waitForWebThread
1345 {
1346     ASSERT(!WebThreadIsCurrent());
1347     _hasFlushedWebThreadRunQueue = NO;
1348     WebThreadRun(^{
1349         [self _webThreadInvoked];
1350     });
1351     while (!_hasFlushedWebThreadRunQueue) {
1352         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1353         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1354         [pool release];
1355     }
1356 }
1357
1358 @end
1359 #endif
1360
1361 static bool returningFromMain = false;
1362
1363 void atexitFunction()
1364 {
1365     if (returningFromMain)
1366         return;
1367
1368     NSLog(@"DumpRenderTree is exiting unexpectedly. Generating a crash log.");
1369     __builtin_trap();
1370 }
1371
1372 int DumpRenderTreeMain(int argc, const char *argv[])
1373 {
1374     atexit(atexitFunction);
1375
1376 #if PLATFORM(IOS)
1377     _UIApplicationLoadWebKit();
1378 #endif
1379     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1380
1381     setDefaultsToConsistentValuesForTesting(); // Must be called before NSApplication initialization.
1382
1383 #if !PLATFORM(IOS)
1384     [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
1385
1386     dumpRenderTree(argc, argv);
1387 #else
1388     _argc = argc;
1389     _argv = argv;
1390     UIApplicationMain(argc, (char**)argv, @"DumpRenderTree", @"DumpRenderTree");
1391 #endif
1392     [WebCoreStatistics garbageCollectJavaScriptObjects];
1393     [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
1394     JSC::finalizeStatsAtEndOfTesting();
1395     [pool release];
1396     returningFromMain = true;
1397     return 0;
1398 }
1399
1400 static NSInteger compareHistoryItems(id item1, id item2, void *context)
1401 {
1402     return [[item1 target] caseInsensitiveCompare:[item2 target]];
1403 }
1404
1405 static NSData *dumpAudio()
1406 {
1407     const vector<char>& dataVector = gTestRunner->audioResult();
1408     
1409     NSData *data = [NSData dataWithBytes:dataVector.data() length:dataVector.size()];
1410     return data;
1411 }
1412
1413 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
1414 {
1415     int start = 0;
1416     if (current) {
1417         printf("curr->");
1418         start = 6;
1419     }
1420     for (int i = start; i < indent; i++)
1421         putchar(' ');
1422     
1423     NSString *urlString = [item URLString];
1424     if ([[NSURL URLWithString:urlString] isFileURL]) {
1425         NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
1426         urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
1427     }
1428     
1429     printf("%s", [urlString UTF8String]);
1430     NSString *target = [item target];
1431     if (target && [target length] > 0)
1432         printf(" (in frame \"%s\")", [target UTF8String]);
1433     if ([item isTargetItem])
1434         printf("  **nav target**");
1435     putchar('\n');
1436     NSArray *kids = [item children];
1437     if (kids) {
1438         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
1439         kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
1440         for (unsigned i = 0; i < [kids count]; i++)
1441             dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
1442     }
1443 }
1444
1445 static void dumpFrameScrollPosition(WebFrame *f)
1446 {
1447     WebScriptObject* scriptObject = [f windowObject];
1448     NSPoint scrollPosition = NSMakePoint(
1449         [[scriptObject valueForKey:@"pageXOffset"] floatValue],
1450         [[scriptObject valueForKey:@"pageYOffset"] floatValue]);
1451     if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
1452         if ([f parentFrame] != nil)
1453             printf("frame '%s' ", [[f name] UTF8String]);
1454         printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
1455     }
1456
1457     if (gTestRunner->dumpChildFrameScrollPositions()) {
1458         NSArray *kids = [f childFrames];
1459         if (kids)
1460             for (unsigned i = 0; i < [kids count]; i++)
1461                 dumpFrameScrollPosition([kids objectAtIndex:i]);
1462     }
1463 }
1464
1465 static NSString *dumpFramesAsText(WebFrame *frame)
1466 {
1467     DOMDocument *document = [frame DOMDocument];
1468     DOMElement *documentElement = [document documentElement];
1469
1470     if (!documentElement)
1471         return @"";
1472
1473     NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
1474
1475     // Add header for all but the main frame.
1476     if ([frame parentFrame])
1477         result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
1478
1479     NSString *innerText = [documentElement innerText];
1480     // We use WKStringGetUTF8CStringNonStrict() to convert innerText to a WK String since
1481     // WKStringGetUTF8CStringNonStrict() can handle dangling surrogates and the NSString
1482     // conversion methods cannot. After the conversion to a buffer, we turn that buffer into
1483     // a CFString via fromUTF8WithLatin1Fallback().createCFString() which can be appended to
1484     // the result without any conversion.
1485     WKRetainPtr<WKStringRef> stringRef(AdoptWK, WKStringCreateWithCFString((CFStringRef)innerText));
1486     size_t bufferSize = WKStringGetMaximumUTF8CStringSize(stringRef.get());
1487     auto buffer = std::make_unique<char[]>(bufferSize);
1488     size_t stringLength = WKStringGetUTF8CStringNonStrict(stringRef.get(), buffer.get(), bufferSize);
1489     [result appendFormat:@"%@\n", String::fromUTF8WithLatin1Fallback(buffer.get(), stringLength - 1).createCFString().get()];
1490
1491     if (gTestRunner->dumpChildFramesAsText()) {
1492         NSArray *kids = [frame childFrames];
1493         if (kids) {
1494             for (unsigned i = 0; i < [kids count]; i++)
1495                 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
1496         }
1497     }
1498
1499     return result;
1500 }
1501
1502 static NSData *dumpFrameAsPDF(WebFrame *frame)
1503 {
1504 #if !PLATFORM(IOS)
1505     if (!frame)
1506         return nil;
1507
1508     // Sadly we have to dump to a file and then read from that file again
1509     // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
1510     // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
1511     // The goal of this function is to test "real" printing across multiple pages.
1512     // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
1513     NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
1514
1515     NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
1516     [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
1517     [printInfoDict setObject:path forKey:NSPrintSavePath];
1518
1519     NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
1520     [printInfo setHorizontalPagination:NSAutoPagination];
1521     [printInfo setVerticalPagination:NSAutoPagination];
1522     [printInfo setVerticallyCentered:NO];
1523
1524     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
1525     [printOperation setShowPanels:NO];
1526     [printOperation runOperation];
1527
1528     [printInfo release];
1529
1530     NSData *pdfData = [NSData dataWithContentsOfFile:path];
1531     [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
1532
1533     return pdfData;
1534 #else
1535     return nil;
1536 #endif
1537 }
1538
1539 static void dumpBackForwardListForWebView(WebView *view)
1540 {
1541     printf("\n============== Back Forward List ==============\n");
1542     WebBackForwardList *bfList = [view backForwardList];
1543
1544     // Print out all items in the list after prevTestBFItem, which was from the previous test
1545     // Gather items from the end of the list, the print them out from oldest to newest
1546     NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
1547     for (int i = [bfList forwardListCount]; i > 0; i--) {
1548         WebHistoryItem *item = [bfList itemAtIndex:i];
1549         // something is wrong if the item from the last test is in the forward part of the b/f list
1550         assert(item != prevTestBFItem);
1551         [itemsToPrint addObject:item];
1552     }
1553             
1554     assert([bfList currentItem] != prevTestBFItem);
1555     [itemsToPrint addObject:[bfList currentItem]];
1556     int currentItemIndex = [itemsToPrint count] - 1;
1557
1558     for (int i = -1; i >= -[bfList backListCount]; i--) {
1559         WebHistoryItem *item = [bfList itemAtIndex:i];
1560         if (item == prevTestBFItem)
1561             break;
1562         [itemsToPrint addObject:item];
1563     }
1564
1565     for (int i = [itemsToPrint count]-1; i >= 0; i--)
1566         dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1567
1568     [itemsToPrint release];
1569     printf("===============================================\n");
1570 }
1571
1572 #if !PLATFORM(IOS)
1573 static void changeWindowScaleIfNeeded(const char* testPathOrUR)
1574 {
1575     WTF::String localPathOrUrl = String(testPathOrUR);
1576     float currentScaleFactor = [[[mainFrame webView] window] backingScaleFactor];
1577     float requiredScaleFactor = 1;
1578     if (localPathOrUrl.findIgnoringCase("/hidpi-3x-") != notFound)
1579         requiredScaleFactor = 3;
1580     else if (localPathOrUrl.findIgnoringCase("/hidpi-") != notFound)
1581         requiredScaleFactor = 2;
1582     if (currentScaleFactor == requiredScaleFactor)
1583         return;
1584     // 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.
1585     gTestRunner->setBackingScaleFactor(requiredScaleFactor);
1586     [[[mainFrame webView] window] _setWindowResolution:requiredScaleFactor displayIfChanged:YES];
1587 }
1588 #endif
1589
1590 static void sizeWebViewForCurrentTest()
1591 {
1592     [uiDelegate resetWindowOrigin];
1593
1594     // W3C SVG tests expect to be 480x360
1595     bool isSVGW3CTest = (gTestRunner->testURL().find("svg/W3C-SVG-1.1") != string::npos);
1596     if (isSVGW3CTest)
1597         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::w3cSVGViewWidth, TestRunner::w3cSVGViewHeight)];
1598     else
1599         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::viewWidth, TestRunner::viewHeight)];
1600 }
1601
1602 static const char *methodNameStringForFailedTest()
1603 {
1604     const char *errorMessage;
1605     if (gTestRunner->dumpAsText())
1606         errorMessage = "[documentElement innerText]";
1607     else if (gTestRunner->dumpDOMAsWebArchive())
1608         errorMessage = "[[mainFrame DOMDocument] webArchive]";
1609     else if (gTestRunner->dumpSourceAsWebArchive())
1610         errorMessage = "[[mainFrame dataSource] webArchive]";
1611     else
1612         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1613
1614     return errorMessage;
1615 }
1616
1617 static void dumpBackForwardListForAllWindows()
1618 {
1619     CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1620     unsigned count = CFArrayGetCount(openWindows);
1621     for (unsigned i = 0; i < count; i++) {
1622         NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1623 #if !PLATFORM(IOS)
1624         WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1625 #else
1626         ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1627         WebView *webView = (WebView *)[window contentView];
1628 #endif
1629         dumpBackForwardListForWebView(webView);
1630     }
1631 }
1632
1633 static void invalidateAnyPreviousWaitToDumpWatchdog()
1634 {
1635     if (waitToDumpWatchdog) {
1636         CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1637         CFRelease(waitToDumpWatchdog);
1638         waitToDumpWatchdog = 0;
1639     }
1640 }
1641
1642 void setWaitToDumpWatchdog(CFRunLoopTimerRef timer)
1643 {
1644     ASSERT(timer);
1645     ASSERT(shouldSetWaitToDumpWatchdog());
1646     waitToDumpWatchdog = timer;
1647     CFRunLoopAddTimer(CFRunLoopGetCurrent(), waitToDumpWatchdog, kCFRunLoopCommonModes);
1648 }
1649
1650 bool shouldSetWaitToDumpWatchdog()
1651 {
1652     return !waitToDumpWatchdog && useTimeoutWatchdog;
1653 }
1654
1655 static void updateDisplay()
1656 {
1657     WebView *webView = [mainFrame webView];
1658 #if PLATFORM(IOS)
1659     [gWebBrowserView layoutIfNeeded]; // Re-enables tile painting, which was disabled when committing the frame load.
1660     [gDrtWindow layoutTilesNow];
1661     [webView _flushCompositingChanges];
1662 #else
1663     if ([webView _isUsingAcceleratedCompositing])
1664         [webView display];
1665     else
1666         [webView displayIfNeeded];
1667 #endif
1668 }
1669
1670 void dump()
1671 {
1672 #if PLATFORM(IOS)
1673     WebThreadLock();
1674 #endif
1675
1676     updateDisplay();
1677
1678     invalidateAnyPreviousWaitToDumpWatchdog();
1679     ASSERT(!gTestRunner->hasPendingWebNotificationClick());
1680
1681     if (dumpTree) {
1682         NSString *resultString = nil;
1683         NSData *resultData = nil;
1684         NSString *resultMimeType = @"text/plain";
1685
1686         if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
1687             gTestRunner->setDumpAsText(true);
1688             gTestRunner->setGeneratePixelResults(false);
1689         }
1690         if (gTestRunner->dumpAsAudio()) {
1691             resultData = dumpAudio();
1692             resultMimeType = @"audio/wav";
1693         } else if (gTestRunner->dumpAsText()) {
1694             resultString = dumpFramesAsText(mainFrame);
1695         } else if (gTestRunner->dumpAsPDF()) {
1696             resultData = dumpFrameAsPDF(mainFrame);
1697             resultMimeType = @"application/pdf";
1698         } else if (gTestRunner->dumpDOMAsWebArchive()) {
1699             WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1700             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1701             resultMimeType = @"application/x-webarchive";
1702         } else if (gTestRunner->dumpSourceAsWebArchive()) {
1703             WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1704             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1705             resultMimeType = @"application/x-webarchive";
1706         } else
1707             resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gTestRunner->isPrinting()];
1708
1709         if (resultString && !resultData)
1710             resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1711
1712         printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1713
1714         WTF::FastMallocStatistics mallocStats = WTF::fastMallocStatistics();
1715         printf("DumpMalloc: %li\n", mallocStats.committedVMBytes);
1716
1717         if (gTestRunner->dumpAsAudio())
1718             printf("Content-Length: %lu\n", static_cast<unsigned long>([resultData length]));
1719
1720         if (resultData) {
1721             fwrite([resultData bytes], 1, [resultData length], stdout);
1722
1723             if (!gTestRunner->dumpAsText() && !gTestRunner->dumpDOMAsWebArchive() && !gTestRunner->dumpSourceAsWebArchive() && !gTestRunner->dumpAsAudio())
1724                 dumpFrameScrollPosition(mainFrame);
1725
1726             if (gTestRunner->dumpBackForwardList())
1727                 dumpBackForwardListForAllWindows();
1728         } else
1729             printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1730
1731         // Stop the watchdog thread before we leave this test to make sure it doesn't
1732         // fire in between tests causing the next test to fail.
1733         // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1734         invalidateAnyPreviousWaitToDumpWatchdog();
1735
1736         if (printSeparators)
1737             puts("#EOF");       // terminate the content block
1738     }
1739
1740     if (dumpPixelsForCurrentTest && gTestRunner->generatePixelResults())
1741         // FIXME: when isPrinting is set, dump the image with page separators.
1742         dumpWebViewAsPixelsAndCompareWithExpected(gTestRunner->expectedPixelHash());
1743
1744     puts("#EOF");   // terminate the (possibly empty) pixels block
1745     fflush(stdout);
1746
1747     done = YES;
1748     CFRunLoopStop(CFRunLoopGetMain());
1749 }
1750
1751 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1752 {
1753     return strstr(pathOrURL, "loading/");
1754 }
1755
1756 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1757 {
1758     return strstr(pathOrURL, "globalhistory/");
1759 }
1760
1761 static bool shouldDumpAsText(const char* pathOrURL)
1762 {
1763     return strstr(pathOrURL, "dumpAsText/");
1764 }
1765
1766 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1767 {
1768     return true;
1769 }
1770
1771 #if PLATFORM(IOS)
1772 static bool shouldMakeViewportFlexible(const char* pathOrURL)
1773 {
1774     return strstr(pathOrURL, "viewport/") && !strstr(pathOrURL, "visual-viewport/");
1775 }
1776 #endif
1777
1778 static void resetWebViewToConsistentStateBeforeTesting(const TestOptions& options)
1779 {
1780     WebView *webView = [mainFrame webView];
1781
1782 #if PLATFORM(IOS)
1783     adjustWebDocumentForStandardViewport(gWebBrowserView, gWebScrollView);
1784     [webView _setAllowsMessaging:YES];
1785 #endif
1786     [webView setEditable:NO];
1787     [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1788     [webView makeTextStandardSize:nil];
1789     [webView resetPageZoom:nil];
1790     [webView _scaleWebView:1.0 atOrigin:NSZeroPoint];
1791 #if !PLATFORM(IOS)
1792     [webView _setCustomBackingScaleFactor:0];
1793 #endif
1794     [webView setTabKeyCyclesThroughElements:YES];
1795     [webView setPolicyDelegate:defaultPolicyDelegate];
1796     [policyDelegate setPermissive:NO];
1797     [policyDelegate setControllerToNotifyDone:0];
1798     [uiDelegate resetToConsistentStateBeforeTesting:options];
1799     [frameLoadDelegate resetToConsistentState];
1800 #if !PLATFORM(IOS)
1801     [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1802 #endif
1803     [webView _clearMainFrameName];
1804     [[webView undoManager] removeAllActions];
1805     [WebView _removeAllUserContentFromGroup:[webView groupName]];
1806 #if !PLATFORM(IOS)
1807     [[webView window] setAutodisplay:NO];
1808 #endif
1809     [webView setTracksRepaints:NO];
1810
1811     [WebCache clearCachedCredentials];
1812     
1813     resetWebPreferencesToConsistentValues();
1814     setWebPreferencesForTestOptions(options);
1815
1816     TestRunner::setSerializeHTTPLoads(false);
1817     TestRunner::setAllowsAnySSLCertificate(false);
1818
1819     setlocale(LC_ALL, "");
1820
1821     if (gTestRunner) {
1822         WebCoreTestSupport::resetInternalsObject([mainFrame globalContext]);
1823         // in the case that a test using the chrome input field failed, be sure to clean up for the next test
1824         gTestRunner->removeChromeInputField();
1825     }
1826
1827 #if !PLATFORM(IOS)
1828     if (WebCore::Frame* frame = [webView _mainCoreFrame])
1829         WebCoreTestSupport::clearWheelEventTestTrigger(*frame);
1830 #endif
1831
1832 #if !PLATFORM(IOS)
1833     [webView setContinuousSpellCheckingEnabled:YES];
1834     [webView setAutomaticQuoteSubstitutionEnabled:NO];
1835     [webView setAutomaticLinkDetectionEnabled:NO];
1836     [webView setAutomaticDashSubstitutionEnabled:NO];
1837     [webView setAutomaticTextReplacementEnabled:NO];
1838     [webView setAutomaticSpellingCorrectionEnabled:YES];
1839     [webView setGrammarCheckingEnabled:YES];
1840
1841     [WebView _setUsesTestModeFocusRingColor:YES];
1842 #endif
1843     [WebView _resetOriginAccessWhitelists];
1844
1845     [[MockGeolocationProvider shared] stopTimer];
1846     [[MockWebNotificationProvider shared] reset];
1847     
1848 #if !PLATFORM(IOS)
1849     // Clear the contents of the general pasteboard
1850     [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1851 #endif
1852
1853     [mainFrame _clearOpener];
1854
1855     setSpellCheckerLoggingEnabled(false);
1856
1857     resetAccumulatedLogs();
1858     WebCoreTestSupport::initializeLogChannelsIfNecessary();
1859 }
1860
1861 #if PLATFORM(IOS)
1862 // Work around <rdar://problem/9909073> WebKit's method of calling delegates on
1863 // the main thread is not thread safe. If the web thread is attempting to call
1864 // out to a delegate method on the main thread, we want to spin the main thread
1865 // run loop until the delegate method completes before taking the web thread
1866 // lock to prevent potentially re-entering WebCore.
1867 static void WebThreadLockAfterDelegateCallbacksHaveCompleted()
1868 {
1869     dispatch_semaphore_t delegateSemaphore = dispatch_semaphore_create(0);
1870     WebThreadRun(^{
1871         dispatch_semaphore_signal(delegateSemaphore);
1872     });
1873
1874     while (dispatch_semaphore_wait(delegateSemaphore, DISPATCH_TIME_NOW)) {
1875         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1876         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1877         [pool release];
1878     }
1879
1880     WebThreadLock();
1881     
1882     dispatch_release(delegateSemaphore);
1883 }
1884 #endif
1885
1886 static NSURL *computeTestURL(NSString *pathOrURLString, NSString **relativeTestPath)
1887 {
1888     *relativeTestPath = nil;
1889
1890     if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"] || [pathOrURLString hasPrefix:@"file://"])
1891         return [NSURL URLWithString:pathOrURLString];
1892
1893     NSString *absolutePath = [[[NSURL fileURLWithPath:pathOrURLString] absoluteURL] path];
1894
1895     NSRange layoutTestsRange = [absolutePath rangeOfString:@"/LayoutTests/"];
1896     if (layoutTestsRange.location == NSNotFound)
1897         return [NSURL fileURLWithPath:absolutePath];
1898
1899     *relativeTestPath = [absolutePath substringFromIndex:NSMaxRange(layoutTestsRange)];
1900
1901     // Convert file URLs in LayoutTests/http/tests to HTTP URLs, except for file URLs in LayoutTests/http/tests/local.
1902
1903     NSRange httpTestsRange = [absolutePath rangeOfString:@"/LayoutTests/http/tests/"];
1904     if (httpTestsRange.location == NSNotFound || [absolutePath rangeOfString:@"/LayoutTests/http/tests/local/"].location != NSNotFound)
1905         return [NSURL fileURLWithPath:absolutePath];
1906
1907     auto components = adoptNS([[NSURLComponents alloc] init]);
1908     [components setPath:[absolutePath substringFromIndex:NSMaxRange(httpTestsRange) - 1]];
1909     [components setHost:@"127.0.0.1"];
1910
1911     // Paths under /ssl/ should be loaded using HTTPS.
1912     BOOL isSecure = [[components path] hasPrefix:@"/ssl/"];
1913     if (isSecure) {
1914         [components setScheme:@"https"];
1915         [components setPort:@(8443)];
1916     } else {
1917         [components setScheme:@"http"];
1918         [components setPort:@(8000)];
1919     }
1920
1921     return [components URL];
1922 }
1923
1924 static void runTest(const string& inputLine)
1925 {
1926     ASSERT(!inputLine.empty());
1927
1928     TestCommand command = parseInputLine(inputLine);
1929     const string& pathOrURL = command.pathOrURL;
1930     dumpPixelsForCurrentTest = command.shouldDumpPixels || dumpPixelsForAllTests;
1931
1932     NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1933     if (!pathOrURLString) {
1934         fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1935         return;
1936     }
1937
1938     NSString *testPath;
1939     NSURL *url = computeTestURL(pathOrURLString, &testPath);
1940     if (!url) {
1941         fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1942         return;
1943     }
1944     if (!testPath)
1945         testPath = [url absoluteString];
1946
1947     NSString *informationString = [@"CRASHING TEST: " stringByAppendingString:testPath];
1948     WKSetCrashReportApplicationSpecificInformation((CFStringRef)informationString);
1949
1950     TestOptions options(url, command);
1951     resetWebViewToConsistentStateBeforeTesting(options);
1952
1953     const char* testURL([[url absoluteString] UTF8String]);
1954
1955 #if !PLATFORM(IOS)
1956     changeWindowScaleIfNeeded(testURL);
1957 #endif
1958
1959     gTestRunner = TestRunner::create(testURL, command.expectedPixelHash);
1960     gTestRunner->setAllowedHosts(allowedHosts);
1961     gTestRunner->setCustomTimeout(command.timeout);
1962     gTestRunner->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr);
1963     topLoadingFrame = nil;
1964 #if !PLATFORM(IOS)
1965     ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1966     releaseAndZero(&draggingInfo);
1967 #endif
1968     done = NO;
1969
1970     sizeWebViewForCurrentTest();
1971     gTestRunner->setIconDatabaseEnabled(false);
1972     gTestRunner->clearAllApplicationCaches();
1973
1974     if (disallowedURLs)
1975         CFSetRemoveAllValues(disallowedURLs);
1976     if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1977         gTestRunner->setDumpFrameLoadCallbacks(true);
1978
1979     if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1980         [[mainFrame webView] setHistoryDelegate:historyDelegate];
1981     else
1982         [[mainFrame webView] setHistoryDelegate:nil];
1983
1984     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1985         gTestRunner->setDeveloperExtrasEnabled(true);
1986         if (shouldDumpAsText(pathOrURL.c_str())) {
1987             gTestRunner->setDumpAsText(true);
1988             gTestRunner->setGeneratePixelResults(false);
1989         }
1990     }
1991
1992 #if PLATFORM(IOS)
1993     if (shouldMakeViewportFlexible(pathOrURL.c_str()))
1994         adjustWebDocumentForFlexibleViewport(gWebBrowserView, gWebScrollView);
1995 #endif
1996
1997     if ([WebHistory optionalSharedHistory])
1998         [WebHistory setOptionalSharedHistory:nil];
1999
2000     lastMousePosition = NSZeroPoint;
2001     lastClickPosition = NSZeroPoint;
2002
2003     [prevTestBFItem release];
2004     prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
2005
2006     auto& workQueue = WorkQueue::singleton();
2007     workQueue.clear();
2008     workQueue.setFrozen(false);
2009
2010     bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
2011     if (ignoreWebCoreNodeLeaks)
2012         [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
2013
2014     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2015     [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
2016     [pool release];
2017
2018     while (!done) {
2019         pool = [[NSAutoreleasePool alloc] init];
2020         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
2021         [pool release];
2022     }
2023
2024 #if PLATFORM(IOS)
2025     [(DumpRenderTree *)UIApp _waitForWebThread];
2026     WebThreadLockAfterDelegateCallbacksHaveCompleted();
2027 #endif
2028     pool = [[NSAutoreleasePool alloc] init];
2029     [EventSendingController clearSavedEvents];
2030     [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
2031
2032     workQueue.clear();
2033
2034     // If the test page could have possibly opened the Web Inspector frontend,
2035     // then try to close it in case it was accidentally left open.
2036     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2037         gTestRunner->closeWebInspector();
2038         gTestRunner->setDeveloperExtrasEnabled(false);
2039     }
2040
2041 #if PLATFORM(MAC)
2042     // Make sure the WebView is parented, since the test may have unparented it.
2043     WebView *webView = [mainFrame webView];
2044     if (![webView superview])
2045         [[mainWindow contentView] addSubview:webView];
2046 #endif
2047
2048     if (gTestRunner->closeRemainingWindowsWhenComplete()) {
2049         NSArray* array = [DumpRenderTreeWindow openWindows];
2050
2051         unsigned count = [array count];
2052         for (unsigned i = 0; i < count; i++) {
2053             NSWindow *window = [array objectAtIndex:i];
2054
2055             // Don't try to close the main window
2056             if (window == [[mainFrame webView] window])
2057                 continue;
2058             
2059 #if !PLATFORM(IOS)
2060             WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
2061 #else
2062             ASSERT([[window contentView] isKindOfClass:[WebView class]]);
2063             WebView *webView = (WebView *)[window contentView];
2064 #endif
2065
2066             [webView close];
2067             [window close];
2068         }
2069     }
2070
2071     resetWebViewToConsistentStateBeforeTesting(options);
2072
2073     // Loading an empty request synchronously replaces the document with a blank one, which is necessary
2074     // to stop timers, WebSockets and other activity that could otherwise spill output into next test's results.
2075     [mainFrame loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
2076
2077     [pool release];
2078
2079     // We should only have our main window left open when we're done
2080     ASSERT(CFArrayGetCount(openWindowsRef) == 1);
2081     ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
2082
2083     gTestRunner->cleanup();
2084     gTestRunner = nullptr;
2085
2086     if (ignoreWebCoreNodeLeaks)
2087         [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
2088
2089     if (gcBetweenTests)
2090         [WebCoreStatistics garbageCollectJavaScriptObjects];
2091
2092     fputs("#EOF\n", stderr);
2093     fflush(stderr);
2094 }
2095
2096 void displayWebView()
2097 {
2098 #if !PLATFORM(IOS)
2099     WebView *webView = [mainFrame webView];
2100     [webView display];
2101
2102     // FIXME: Tracking repaints is not specific to Mac. We should enable such support on iOS.
2103     [webView setTracksRepaints:YES];
2104     [webView resetTrackedRepaints];
2105 #else
2106     [gDrtWindow layoutTilesNow];
2107     [gDrtWindow setNeedsDisplayInRect:[gDrtWindow frame]];
2108     [CATransaction flush];
2109 #endif
2110 }
2111
2112 #if !PLATFORM(IOS)
2113 @implementation DumpRenderTreeEvent
2114
2115 + (NSPoint)mouseLocation
2116 {
2117     return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
2118 }
2119
2120 @end
2121
2122 @implementation DumpRenderTreeApplication
2123
2124 - (BOOL)isRunning
2125 {
2126     // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running
2127     return YES;
2128 }
2129
2130 @end
2131 #endif