2 * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3 * (C) 2007 Graham Dennis (graham.dennis@gmail.com)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
31 #import "DumpRenderTree.h"
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"
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>
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>
96 #import <Carbon/Carbon.h>
97 #import <WebKit/WebDynamicScrollBarsView.h>
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>
113 #import "DumpRenderTreeBrowserView.h"
117 #import <mach-o/getsect.h>
123 @interface DumpRenderTreeApplication : NSApplication
126 @interface DumpRenderTreeEvent : NSEvent
129 @interface ScrollViewResizerDelegate : NSObject
132 @implementation ScrollViewResizerDelegate
133 - (void)view:(UIWebDocumentView *)view didSetFrame:(CGRect)newFrame oldFrame:(CGRect)oldFrame asResultOfZoom:(BOOL)wasResultOfZoom
135 UIView *scrollView = [view superview];
136 while (![scrollView isKindOfClass:[UIWebScrollView class]])
137 scrollView = [scrollView superview];
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];
148 @interface NSURLRequest (PrivateThingsWeShouldntReallyUse)
149 +(void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString *)host;
153 @interface NSSound (Details)
154 + (void)_setAlertType:(NSUInteger)alertType;
158 static void runTest(const string& testPathOrURL);
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.
169 NavigationController* gNavigationController = 0;
170 RefPtr<TestRunner> gTestRunner;
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
180 CFMutableSetRef disallowedURLs = 0;
181 static CFRunLoopTimerRef waitToDumpWatchdog = 0;
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;
193 static ScrollViewResizerDelegate *scrollViewResizerDelegate;
196 static int dumpPixelsForAllTests = NO;
197 static bool dumpPixelsForCurrentTest = false;
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;
207 static WebHistoryItem *prevTestBFItem = nil; // current b/f item at the end of the previous test
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;
221 static void swizzleAllMethods(Class imposter, Class original)
223 unsigned int imposterMethodCount;
224 Method* imposterMethods = class_copyMethodList(imposter, &imposterMethodCount);
226 unsigned int originalMethodCount;
227 Method* originalMethods = class_copyMethodList(original, &originalMethodCount);
229 for (unsigned int i = 0; i < imposterMethodCount; i++) {
230 SEL imposterMethodName = method_getName(imposterMethods[i]);
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])))
238 for (; j < originalMethodCount; j++) {
239 SEL originalMethodName = method_getName(originalMethods[j]);
240 if (sel_isEqual(imposterMethodName, originalMethodName))
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]);
249 free(imposterMethods);
250 free(originalMethods);
254 static void poseAsClass(const char* imposter, const char* original)
256 Class imposterClass = objc_getClass(imposter);
257 Class originalClass = objc_getClass(original);
260 class_poseAs(imposterClass, originalClass);
263 // Swizzle instance methods
264 swizzleAllMethods(imposterClass, originalClass);
265 // and then class methods
266 swizzleAllMethods(object_getClass(imposterClass), object_getClass(originalClass));
270 void setPersistentUserStyleSheetLocation(CFStringRef url)
272 persistentUserStyleSheetLocation = url;
275 static bool shouldIgnoreWebCoreNodeLeaks(const string& URLString)
277 static char* const ignoreSet[] = {
278 // Keeping this infrastructure around in case we ever need it again.
280 static const int ignoreSetCount = sizeof(ignoreSet) / sizeof(char*);
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))
293 static NSSet *allowedFontFamilySet()
295 static NSSet *fontFamilySet = [[NSSet setWithObjects:
298 @"American Typewriter",
301 @"Apple Color Emoji",
303 @"Apple Garamond BT",
312 @"Arial Rounded MT Bold",
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",
375 @"Microsoft Sans Serif",
385 @"Plantagenet Cherokee",
407 @"WebKit WeightWatcher",
415 return fontFamilySet;
418 static IMP appKitAvailableFontFamiliesIMP;
419 static IMP appKitAvailableFontsIMP;
421 static NSArray *drt_NSFontManager_availableFontFamilies(id self, SEL _cmd)
423 static NSArray *availableFontFamilies;
424 if (availableFontFamilies)
425 return availableFontFamilies;
427 NSArray *availableFamilies = wtfCallIMP<id>(appKitAvailableFontFamiliesIMP, self, _cmd);
429 NSMutableSet *prunedFamiliesSet = [NSMutableSet setWithArray:availableFamilies];
430 [prunedFamiliesSet intersectSet:allowedFontFamilySet()];
432 availableFontFamilies = [[prunedFamiliesSet allObjects] retain];
433 return availableFontFamilies;
436 static NSArray *drt_NSFontManager_availableFonts(id self, SEL _cmd)
438 static NSArray *availableFonts;
440 return availableFonts;
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]];
452 availableFonts = availableFontList;
453 return availableFonts;
456 static void swizzleNSFontManagerMethods()
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");
465 appKitAvailableFontFamiliesIMP = method_setImplementation(availableFontFamiliesMethod, (IMP)drt_NSFontManager_availableFontFamilies);
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");
474 appKitAvailableFontsIMP = method_setImplementation(availableFontsMethod, (IMP)drt_NSFontManager_availableFonts);
477 static void activateTestingFonts()
479 static const char* fontFileNames[] = {
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
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]];
503 CFArrayRef errors = 0;
504 if (!CTFontManagerRegisterFontsForURLs((CFArrayRef)fontURLs, kCTFontManagerScopeProcess, &errors)) {
505 NSLog(@"Failed to activate fonts: %@", errors);
511 static void adjustFonts()
513 swizzleNSFontManagerMethods();
514 activateTestingFonts();
517 static void activateFontsIOS()
519 static const char* fontSectionNames[] = {
533 for (unsigned i = 0; fontSectionNames[i]; ++i) {
534 unsigned long fontDataLength;
535 char* fontData = getsectdata("__DATA", fontSectionNames[i], &fontDataLength);
537 fprintf(stderr, "Failed to locate the %s font.\n", fontSectionNames[i]);
541 CGDataProviderRef data = CGDataProviderCreateWithData(NULL, fontData, fontDataLength, NULL);
543 fprintf(stderr, "Failed to create CGDataProviderRef for the %s font.\n", fontSectionNames[i]);
547 CGFontRef cgFont = CGFontCreateWithDataProvider(data);
548 CGDataProviderRelease(data);
550 fprintf(stderr, "Failed to create CGFontRef for the %s font.\n", fontSectionNames[i]);
554 if (!GSFontAddCGFont(cgFont)) {
555 fprintf(stderr, "Failed to add CGFont to GraphicsServices for the %s font.\n", fontSectionNames[i]);
558 CGFontRelease(cgFont);
561 #endif // !PLATFORM(IOS)
565 void adjustWebDocumentForFlexibleViewport(UIWebBrowserView *webBrowserView, UIWebScrollView *scrollView)
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];
573 // Adjust the viewport view and viewport to have similar behavior
575 [(DumpRenderTreeBrowserView *)webBrowserView setScrollingUsesUIWebScrollView:YES];
576 [webBrowserView setDelegate:scrollViewResizerDelegate];
578 CGRect viewportRect = CGRectMake(0, 0, phoneViewWidth, phoneBrowserScrollViewHeight);
579 [scrollView setBounds:viewportRect];
580 [scrollView setFrame:viewportRect];
582 [webBrowserView setMinimumSize:viewportRect.size];
583 [webBrowserView setAutoresizes:YES];
584 CGRect browserViewFrame = [webBrowserView frame];
585 browserViewFrame.origin = CGPointMake(0, phoneBrowserAddressBarOffset);
586 [webBrowserView setFrame:browserViewFrame];
589 void adjustWebDocumentForStandardViewport(UIWebBrowserView *webBrowserView, UIWebScrollView *scrollView)
591 [webBrowserView setMinimumScale:1.0f forDocumentTypes:UIEveryDocumentMask];
592 [webBrowserView setMaximumScale:5.0f forDocumentTypes:UIEveryDocumentMask];
593 [webBrowserView setInitialScale:1.0f forDocumentTypes:UIEveryDocumentMask];
595 [(DumpRenderTreeBrowserView *)webBrowserView setScrollingUsesUIWebScrollView:NO];
596 [webBrowserView setDelegate: nil];
598 [scrollView setBounds:layoutTestViewportRect];
599 [scrollView setFrame:layoutTestViewportRect];
601 [webBrowserView setMinimumSize:layoutTestViewportRect.size];
602 [webBrowserView setAutoresizes:NO];
603 CGRect browserViewFrame = [webBrowserView frame];
604 browserViewFrame.origin = CGPointZero;
605 [webBrowserView setFrame:browserViewFrame];
610 @interface DRTMockScroller : NSScroller
613 @implementation DRTMockScroller
615 - (NSRect)rectForPart:(NSScrollerPart)partCode
617 if (partCode != NSScrollerKnob)
618 return [super rectForPart:partCode];
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))));
629 return NSMakeRect(bounds.origin.x + knobPosition, bounds.origin.y, knobLength, bounds.size.height);
631 return NSMakeRect(bounds.origin.x, bounds.origin.y + + knobPosition, bounds.size.width, knobLength);
636 if (![self isEnabled])
639 NSRect knobRect = [self rectForPart:NSScrollerKnob];
641 static NSColor *knobColor = [[NSColor colorWithDeviceRed:0x80 / 255.0 green:0x80 / 255.0 blue:0x80 / 255.0 alpha:1] retain];
644 NSRectFill(knobRect);
647 - (void)drawRect:(NSRect)dirtyRect
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];
652 if ([self isEnabled])
655 [disabledTrackColor set];
657 NSRectFill(dirtyRect);
664 static void registerMockScrollbars()
666 [WebDynamicScrollBarsView setCustomScrollerClass:[DRTMockScroller class]];
670 WebView *createWebViewAndOffscreenWindow()
673 NSRect rect = NSMakeRect(0, 0, TestRunner::viewWidth, TestRunner::viewHeight);
674 WebView *webView = [[WebView alloc] initWithFrame:rect frameName:nil groupName:@"org.webkit.DumpRenderTree"];
676 UIWebBrowserView *webBrowserView = [[[DumpRenderTreeBrowserView alloc] initWithFrame:layoutTestViewportRect] autorelease];
678 WebView *webView = [[webBrowserView webView] retain];
679 [webView setGroupName:@"org.webkit.DumpRenderTree"];
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]];
690 // Register the same schemes that Safari does
691 [WebView registerURLSchemeAsLocal:@"feed"];
692 [WebView registerURLSchemeAsLocal:@"feeds"];
693 [WebView registerURLSchemeAsLocal:@"feedsearch"];
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];
704 [webView setDefersCallbacks:NO];
705 [webView setInteractiveFormValidationEnabled:YES];
706 [webView setValidationMessageTimerMagnification:-1];
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];
713 [window setColorSpace:[[NSScreen mainScreen] colorSpace]];
714 [window setCollectionBehavior:NSWindowCollectionBehaviorStationary];
715 [[window contentView] addSubview:webView];
716 [window orderBack:nil];
717 [window setAutodisplay:NO];
719 [window startListeningForAcceleratedCompositingChanges];
721 DumpRenderTreeWindow *drtWindow = [[DumpRenderTreeWindow alloc] initWithLayer:[webBrowserView layer]];
722 [drtWindow setContentView:webView];
723 [webBrowserView setWAKWindow:drtWindow];
725 [[webView window] makeFirstResponder:[[[webView mainFrame] frameView] documentView]];
727 CGRect uiWindowRect = layoutTestViewportRect;
728 uiWindowRect.origin.y += [UIApp statusBarHeight];
729 UIWindow *uiWindow = [[[UIWindow alloc] initWithFrame:uiWindowRect] autorelease];
731 // The UIWindow and UIWebBrowserView are released when the DumpRenderTreeWindow is closed.
732 drtWindow.uiWindow = uiWindow;
733 drtWindow.browserView = webBrowserView;
735 UIWebScrollView *scrollView = [[UIWebScrollView alloc] initWithFrame:layoutTestViewportRect];
736 [scrollView addSubview:webBrowserView];
738 [uiWindow addSubview:scrollView];
739 [scrollView release];
741 adjustWebDocumentForStandardViewport(webBrowserView, scrollView);
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];
750 [[webView mainFrame] _setVisibleSize:CGSizeMake(phoneViewWidth, phoneViewHeight)];
751 [[webView preferences] _setTelephoneNumberParsingEnabled:NO];
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];
766 static void destroyWebViewAndOffscreenWindow()
768 WebView *webView = [mainFrame webView];
770 NSWindow *window = [webView window];
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];
782 [window close]; // releases when closed
784 UIWindow *uiWindow = [gWebBrowserView window];
785 [uiWindow removeFromSuperview];
792 static NSString *libraryPathForDumpRenderTree()
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)];
801 return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
804 // Called before each test.
805 static void resetWebPreferencesToConsistentValues()
807 WebPreferences *preferences = [WebPreferences standardPreferences];
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];
826 [preferences setTabsToLinks:NO];
828 [preferences setDOMPasteAllowed:YES];
830 [preferences setShouldPrintBackgrounds:YES];
832 [preferences setCacheModel:WebCacheModelDocumentBrowser];
833 [preferences setXSSAuditorEnabled:NO];
834 [preferences setExperimentalNotificationsEnabled:NO];
835 [preferences setPlugInsEnabled:YES];
837 [preferences setTextAreasAreResizable:YES];
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];
856 [preferences setUserStyleSheetEnabled:NO];
858 [preferences setMediaPlaybackAllowsInline:YES];
859 [preferences setMediaPlaybackRequiresUserGesture:NO];
861 // Enable the tracker before creating the first WebView will
862 // cause initialization to use the correct database paths.
863 [preferences setStorageTrackerEnabled:YES];
866 #if ENABLE(IOS_TEXT_AUTOSIZING)
867 // Disable text autosizing by default.
868 [preferences _setMinimumZoomFontSize:0];
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];
876 [preferences setCanvasUsesAcceleratedDrawing:YES];
877 [preferences setAcceleratedDrawingEnabled:useAcceleratedDrawing];
879 [preferences setWebGLEnabled:NO];
880 [preferences setCSSRegionsEnabled:YES];
881 [preferences setUsePreHTML5ParserQuirks:NO];
882 [preferences setAsynchronousSpellCheckingEnabled:NO];
884 ASSERT([preferences mockScrollbarsEnabled]);
887 #if ENABLE(WEB_AUDIO)
888 [preferences setWebAudioEnabled:YES];
891 #if ENABLE(IOS_TEXT_AUTOSIZING)
892 // Disable text autosizing by default.
893 [preferences _setMinimumZoomFontSize:0];
896 [preferences setScreenFontSubstitutionEnabled:YES];
898 #if ENABLE(MEDIA_SOURCE)
899 [preferences setMediaSourceEnabled:YES];
902 [WebPreferences _setCurrentNetworkLoaderSessionCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
905 // Called once on DumpRenderTree startup.
906 static void setDefaultsToConsistentValuesForTesting()
912 static const int NoFontSmoothing = 0;
913 static const int BlueTintedAppearance = 1;
915 NSString *libraryPath = libraryPathForDumpRenderTree();
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,
929 @"NSTestCorrectionDictionary": @{
930 @"notationl": @"notational",
931 @"mesage": @"message",
933 @"wellcome": @"welcome",
934 @"hellolfworld": @"hello\nworld"
937 @"WebKitKerningAndLigaturesEnabledByDefault": @NO,
938 @"AppleScrollBarVariant": @"DoubleMax",
940 @"NSScrollAnimationEnabled": @NO,
942 @"NSOverlayScrollersEnabled": @NO,
943 @"AppleShowScrollBars": @"Always",
944 WebDatabaseDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"Databases"],
945 WebStorageDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
946 WebKitLocalCacheDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalCache"]
949 [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:dict];
952 static void runThread(void* arg)
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;
961 static void* runPthread(void* arg)
967 static void testThreadIdentifierMap()
969 // Imitate 'foreign' threads that are not created by WTF.
971 pthread_create(&pthread, 0, &runPthread, 0);
972 pthread_join(pthread, 0);
974 pthread_create(&pthread, 0, &runPthread, 0);
975 pthread_join(pthread, 0);
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");
982 static void allocateGlobalControllers()
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];
995 scrollViewResizerDelegate = [[ScrollViewResizerDelegate alloc] init];
999 // ObjC++ doens't seem to let me pass NSObject*& sadly.
1000 static inline void releaseAndZero(NSObject** object)
1006 static void releaseGlobalControllers()
1008 releaseAndZero(&gNavigationController);
1009 releaseAndZero(&frameLoadDelegate);
1010 releaseAndZero(&editingDelegate);
1011 releaseAndZero(&resourceLoadDelegate);
1012 releaseAndZero(&uiDelegate);
1013 releaseAndZero(&policyDelegate);
1014 releaseAndZero(&storageDelegate);
1016 releaseAndZero(&scrollViewResizerDelegate);
1020 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
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},
1035 while ((option = getopt_long(argc, (char * const *)argv, "", options, NULL)) != -1) {
1037 case '?': // unknown or ambiguous option
1038 case ':': // missing argument
1045 static void addTestPluginsToPluginSearchPath(const char* executablePath)
1048 NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
1049 [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
1050 [[WebPluginDatabase sharedDatabase] refresh];
1054 static bool useLongRunningServerMode(int argc, const char *argv[])
1056 // This assumes you've already called getopt_long
1057 return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
1060 static void runTestingServerLoop()
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';
1070 if (strlen(filenameBuffer) == 0)
1073 runTest(filenameBuffer);
1077 static void prepareConsistentTestingEnvironment()
1080 poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
1081 poseAsClass("DumpRenderTreeEvent", "NSEvent");
1083 poseAsClass("DumpRenderTreeEvent", "GSEvent");
1086 [[WebPreferences standardPreferences] setAutosaves:NO];
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];
1092 NSURLCache *sharedCache =
1093 [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
1095 diskPath:[libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"URLCache"]];
1096 [NSURLCache setSharedURLCache:sharedCache];
1097 [sharedCache release];
1100 registerMockScrollbars();
1102 // The mock scrollbars setting cannot be modified after creating a view, so we have to do it now.
1103 [[WebPreferences standardPreferences] setMockScrollbarsEnabled:YES];
1108 allocateGlobalControllers();
1110 makeLargeMallocFailSilently();
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);
1119 void dumpRenderTree(int argc, const char *argv[])
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);
1130 initializeGlobalsFromCommandLineOptions(argc, argv);
1131 prepareConsistentTestingEnvironment();
1132 addTestPluginsToPluginSearchPath(argv[0]);
1134 if (forceComplexText)
1135 [WebView _setAlwaysUsesComplexTextCodePath:YES];
1138 [NSSound _setAlertType:0];
1141 WebView *webView = createWebViewAndOffscreenWindow();
1142 mainFrame = [webView mainFrame];
1144 [[NSURLCache sharedURLCache] removeAllCachedResponses];
1147 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
1148 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
1150 // http://webkit.org/b/32689
1151 testThreadIdentifierMap();
1154 startJavaScriptThreads();
1156 if (useLongRunningServerMode(argc, argv)) {
1157 printSeparators = YES;
1158 runTestingServerLoop();
1160 printSeparators = optind < argc - 1;
1161 for (int i = optind; i != argc; ++i)
1166 stopJavaScriptThreads();
1168 destroyWebViewAndOffscreenWindow();
1170 releaseGlobalControllers();
1173 [DumpRenderTreePasteboard releaseLocalPasteboards];
1176 // FIXME: This should be moved onto TestRunner and made into a HashSet
1177 if (disallowedURLs) {
1178 CFRelease(disallowedURLs);
1191 static const char **_argv;
1193 @implementation DumpRenderTree
1195 - (void)_runDumpRenderTree
1197 dumpRenderTree(_argc, _argv);
1200 - (void)applicationDidFinishLaunching:(NSNotification *)notification
1202 [self performSelectorOnMainThread:@selector(_runDumpRenderTree) withObject:nil waitUntilDone:NO];
1205 - (void)_deferDumpToMainThread
1207 ASSERT(WebThreadIsCurrent());
1209 dispatch_async(dispatch_get_main_queue(), ^{
1214 - (void)_webThreadEventLoopHasRun
1216 ASSERT(!WebThreadIsCurrent());
1217 _hasFlushedWebThreadRunQueue = YES;
1220 - (void)_webThreadInvoked
1222 ASSERT(WebThreadIsCurrent());
1223 dispatch_async(dispatch_get_main_queue(), ^{
1224 [self _webThreadEventLoopHasRun];
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
1234 ASSERT(!WebThreadIsCurrent());
1235 _hasFlushedWebThreadRunQueue = NO;
1237 [self _webThreadInvoked];
1239 while (!_hasFlushedWebThreadRunQueue) {
1240 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1241 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1249 int DumpRenderTreeMain(int argc, const char *argv[])
1252 _UIApplicationLoadWebKit();
1254 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1256 setDefaultsToConsistentValuesForTesting(); // Must be called before NSApplication initialization.
1259 [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
1261 dumpRenderTree(argc, argv);
1265 UIApplicationMain(argc, (char**)argv, @"DumpRenderTree", nil);
1267 [WebCoreStatistics garbageCollectJavaScriptObjects];
1268 [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
1269 if (JSC::Options::logHeapStatisticsAtExit())
1270 JSC::HeapStatistics::reportSuccess();
1275 static NSInteger compareHistoryItems(id item1, id item2, void *context)
1277 return [[item1 target] caseInsensitiveCompare:[item2 target]];
1280 static NSData *dumpAudio()
1282 const vector<char>& dataVector = gTestRunner->audioResult();
1284 NSData *data = [NSData dataWithBytes:dataVector.data() length:dataVector.size()];
1288 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
1295 for (int i = start; i < indent; i++)
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)]];
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**");
1311 NSArray *kids = [item children];
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);
1320 static void dumpFrameScrollPosition(WebFrame *f)
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);
1332 if (gTestRunner->dumpChildFrameScrollPositions()) {
1333 NSArray *kids = [f childFrames];
1335 for (unsigned i = 0; i < [kids count]; i++)
1336 dumpFrameScrollPosition([kids objectAtIndex:i]);
1340 static NSString *dumpFramesAsText(WebFrame *frame)
1342 DOMDocument *document = [frame DOMDocument];
1343 DOMElement *documentElement = [document documentElement];
1345 if (!documentElement)
1348 NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
1350 // Add header for all but the main frame.
1351 if ([frame parentFrame])
1352 result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
1354 [result appendFormat:@"%@\n", [documentElement innerText]];
1356 if (gTestRunner->dumpChildFramesAsText()) {
1357 NSArray *kids = [frame childFrames];
1359 for (unsigned i = 0; i < [kids count]; i++)
1360 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
1367 static NSData *dumpFrameAsPDF(WebFrame *frame)
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"];
1380 NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
1381 [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
1382 [printInfoDict setObject:path forKey:NSPrintSavePath];
1384 NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
1385 [printInfo setHorizontalPagination:NSAutoPagination];
1386 [printInfo setVerticalPagination:NSAutoPagination];
1387 [printInfo setVerticallyCentered:NO];
1389 NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
1390 [printOperation setShowPanels:NO];
1391 [printOperation runOperation];
1393 [printInfo release];
1395 NSData *pdfData = [NSData dataWithContentsOfFile:path];
1396 [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
1404 static void dumpBackForwardListForWebView(WebView *view)
1406 printf("\n============== Back Forward List ==============\n");
1407 WebBackForwardList *bfList = [view backForwardList];
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];
1419 assert([bfList currentItem] != prevTestBFItem);
1420 [itemsToPrint addObject:[bfList currentItem]];
1421 int currentItemIndex = [itemsToPrint count] - 1;
1423 for (int i = -1; i >= -[bfList backListCount]; i--) {
1424 WebHistoryItem *item = [bfList itemAtIndex:i];
1425 if (item == prevTestBFItem)
1427 [itemsToPrint addObject:item];
1430 for (int i = [itemsToPrint count]-1; i >= 0; i--)
1431 dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1433 [itemsToPrint release];
1434 printf("===============================================\n");
1438 static void changeWindowScaleIfNeeded(const char* testPathOrUR)
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)
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];
1453 static void sizeWebViewForCurrentTest()
1455 // W3C SVG tests expect to be 480x360
1456 bool isSVGW3CTest = (gTestRunner->testPathOrURL().find("svg/W3C-SVG-1.1") != string::npos);
1458 [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::w3cSVGViewWidth, TestRunner::w3cSVGViewHeight)];
1460 [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::viewWidth, TestRunner::viewHeight)];
1463 static const char *methodNameStringForFailedTest()
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]";
1473 errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1475 return errorMessage;
1478 static void dumpBackForwardListForAllWindows()
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);
1485 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1487 ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1488 WebView *webView = (WebView *)[window contentView];
1490 dumpBackForwardListForWebView(webView);
1494 static void invalidateAnyPreviousWaitToDumpWatchdog()
1496 if (waitToDumpWatchdog) {
1497 CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1498 CFRelease(waitToDumpWatchdog);
1499 waitToDumpWatchdog = 0;
1503 void setWaitToDumpWatchdog(CFRunLoopTimerRef timer)
1506 ASSERT(shouldSetWaitToDumpWatchdog());
1507 waitToDumpWatchdog = timer;
1508 CFRunLoopAddTimer(CFRunLoopGetCurrent(), waitToDumpWatchdog, kCFRunLoopCommonModes);
1511 bool shouldSetWaitToDumpWatchdog()
1513 return !waitToDumpWatchdog && useTimeoutWatchdog;
1516 static void updateDisplay()
1518 WebView *webView = [mainFrame webView];
1520 if ([webView _isUsingAcceleratedCompositing])
1523 [webView displayIfNeeded];
1529 // This can get called on the web thread if from a JavaScript notifyDone().
1530 if (WebThreadIsCurrent()) {
1531 [(DumpRenderTree *)UIApp _deferDumpToMainThread];
1539 invalidateAnyPreviousWaitToDumpWatchdog();
1540 ASSERT(!gTestRunner->hasPendingWebNotificationClick());
1543 NSString *resultString = nil;
1544 NSData *resultData = nil;
1545 NSString *resultMimeType = @"text/plain";
1547 if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
1548 gTestRunner->setDumpAsText(true);
1549 gTestRunner->setGeneratePixelResults(false);
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";
1568 resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gTestRunner->isPrinting()];
1570 if (resultString && !resultData)
1571 resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1573 printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1575 WTF::FastMallocStatistics mallocStats = WTF::fastMallocStatistics();
1576 printf("DumpMalloc: %li\n", mallocStats.committedVMBytes);
1578 if (gTestRunner->dumpAsAudio())
1579 printf("Content-Length: %lu\n", static_cast<unsigned long>([resultData length]));
1582 fwrite([resultData bytes], 1, [resultData length], stdout);
1584 if (!gTestRunner->dumpAsText() && !gTestRunner->dumpDOMAsWebArchive() && !gTestRunner->dumpSourceAsWebArchive() && !gTestRunner->dumpAsAudio())
1585 dumpFrameScrollPosition(mainFrame);
1587 if (gTestRunner->dumpBackForwardList())
1588 dumpBackForwardListForAllWindows();
1590 printf("ERROR: nil result from %s", methodNameStringForFailedTest());
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();
1597 if (printSeparators) {
1598 puts("#EOF"); // terminate the content block
1599 fputs("#EOF\n", stderr);
1603 if (dumpPixelsForCurrentTest && gTestRunner->generatePixelResults())
1604 // FIXME: when isPrinting is set, dump the image with page separators.
1605 dumpWebViewAsPixelsAndCompareWithExpected(gTestRunner->expectedPixelHash());
1607 puts("#EOF"); // terminate the (possibly empty) pixels block
1613 CFRunLoopStop(CFRunLoopGetMain());
1616 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1618 return strstr(pathOrURL, "loading/");
1621 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1623 return strstr(pathOrURL, "globalhistory/");
1626 static bool shouldDumpAsText(const char* pathOrURL)
1628 return strstr(pathOrURL, "dumpAsText/");
1631 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1637 static bool shouldMakeViewportFlexible(const char* pathOrURL)
1639 return strstr(pathOrURL, "viewport/");
1643 static void resetWebViewToConsistentStateBeforeTesting()
1645 WebView *webView = [mainFrame webView];
1647 adjustWebDocumentForStandardViewport(gWebBrowserView, gWebScrollView);
1648 [webView _setAllowsMessaging:YES];
1649 [mainFrame setMediaDataLoadsAutomatically:YES];
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];
1657 [webView _setCustomBackingScaleFactor:0];
1659 [webView setTabKeyCyclesThroughElements:YES];
1660 [webView setPolicyDelegate:defaultPolicyDelegate];
1661 [policyDelegate setPermissive:NO];
1662 [policyDelegate setControllerToNotifyDone:0];
1663 [frameLoadDelegate resetToConsistentState];
1665 [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1667 [webView _clearMainFrameName];
1668 [[webView undoManager] removeAllActions];
1669 [WebView _removeAllUserContentFromGroup:[webView groupName]];
1671 [[webView window] setAutodisplay:NO];
1673 [webView setTracksRepaints:NO];
1675 resetWebPreferencesToConsistentValues();
1677 TestRunner::setSerializeHTTPLoads(false);
1679 setlocale(LC_ALL, "");
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();
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];
1696 [WebView _setUsesTestModeFocusRingColor:YES];
1698 [WebView _resetOriginAccessWhitelists];
1699 [WebView _setAllowsRoundingHacks:NO];
1701 [[MockGeolocationProvider shared] stopTimer];
1702 [[MockWebNotificationProvider shared] reset];
1705 // Clear the contents of the general pasteboard
1706 [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1709 [mainFrame _clearOpener];
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()
1720 dispatch_semaphore_t delegateSemaphore = dispatch_semaphore_create(0);
1722 dispatch_semaphore_signal(delegateSemaphore);
1725 while (dispatch_semaphore_wait(delegateSemaphore, DISPATCH_TIME_NOW)) {
1726 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1727 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1733 dispatch_release(delegateSemaphore);
1737 static void runTest(const string& inputLine)
1739 ASSERT(!inputLine.empty());
1741 TestCommand command = parseInputLine(inputLine);
1742 const string& pathOrURL = command.pathOrURL;
1743 dumpPixelsForCurrentTest = command.shouldDumpPixels || dumpPixelsForAllTests;
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());
1752 if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"] || [pathOrURLString hasPrefix:@"file://"])
1753 url = [NSURL URLWithString:pathOrURLString];
1755 url = [NSURL fileURLWithPath:pathOrURLString];
1757 fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1761 const char* testURL([[url absoluteString] UTF8String]);
1763 resetWebViewToConsistentStateBeforeTesting();
1765 changeWindowScaleIfNeeded(testURL);
1768 gTestRunner = TestRunner::create(testURL, command.expectedPixelHash);
1769 topLoadingFrame = nil;
1771 ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1772 releaseAndZero(&draggingInfo);
1776 sizeWebViewForCurrentTest();
1777 gTestRunner->setIconDatabaseEnabled(false);
1780 CFSetRemoveAllValues(disallowedURLs);
1781 if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1782 gTestRunner->setDumpFrameLoadCallbacks(true);
1784 if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1785 [[mainFrame webView] setHistoryDelegate:historyDelegate];
1787 [[mainFrame webView] setHistoryDelegate:nil];
1789 if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1790 gTestRunner->setDeveloperExtrasEnabled(true);
1791 if (shouldDumpAsText(pathOrURL.c_str())) {
1792 gTestRunner->setDumpAsText(true);
1793 gTestRunner->setGeneratePixelResults(false);
1798 if (shouldMakeViewportFlexible(pathOrURL.c_str()))
1799 adjustWebDocumentForFlexibleViewport(gWebBrowserView, gWebScrollView);
1802 if ([WebHistory optionalSharedHistory])
1803 [WebHistory setOptionalSharedHistory:nil];
1804 lastMousePosition = NSZeroPoint;
1805 lastClickPosition = NSZeroPoint;
1807 [prevTestBFItem release];
1808 prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
1810 WorkQueue::shared()->clear();
1811 WorkQueue::shared()->setFrozen(false);
1813 bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
1814 if (ignoreWebCoreNodeLeaks)
1815 [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
1817 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1818 [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
1822 pool = [[NSAutoreleasePool alloc] init];
1823 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
1828 [(DumpRenderTree *)UIApp _waitForWebThread];
1829 WebThreadLockAfterDelegateCallbacksHaveCompleted();
1831 pool = [[NSAutoreleasePool alloc] init];
1832 [EventSendingController clearSavedEvents];
1833 [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
1835 WorkQueue::shared()->clear();
1837 if (gTestRunner->closeRemainingWindowsWhenComplete()) {
1838 NSArray* array = [DumpRenderTreeWindow openWindows];
1840 unsigned count = [array count];
1841 for (unsigned i = 0; i < count; i++) {
1842 NSWindow *window = [array objectAtIndex:i];
1844 // Don't try to close the main window
1845 if (window == [[mainFrame webView] window])
1849 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1851 ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1852 WebView *webView = (WebView *)[window contentView];
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);
1866 resetWebViewToConsistentStateBeforeTesting();
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:@""]]];
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]);
1878 gTestRunner.clear();
1880 if (ignoreWebCoreNodeLeaks)
1881 [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
1884 [WebCoreStatistics garbageCollectJavaScriptObjects];
1887 void displayWebView()
1890 WebView *webView = [mainFrame webView];
1893 [webView setTracksRepaints:YES];
1894 [webView resetTrackedRepaints];
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];
1904 @implementation DumpRenderTreeEvent
1906 + (NSPoint)mouseLocation
1908 return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
1913 @implementation DumpRenderTreeApplication
1917 // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running