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