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 Computer, 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 "DumpRenderTreeDraggingInfo.h"
36 #import "DumpRenderTreePasteboard.h"
37 #import "DumpRenderTreeWindow.h"
38 #import "EditingDelegate.h"
39 #import "EventSendingController.h"
40 #import "FrameLoadDelegate.h"
41 #import "HistoryDelegate.h"
42 #import "JavaScriptThreading.h"
43 #import "LayoutTestController.h"
44 #import "MockGeolocationProvider.h"
45 #import "NavigationController.h"
46 #import "ObjCPlugin.h"
47 #import "ObjCPluginFunction.h"
48 #import "PixelDumpSupport.h"
49 #import "PolicyDelegate.h"
50 #import "ResourceLoadDelegate.h"
51 #import "UIDelegate.h"
53 #import "WorkQueueItem.h"
54 #import <Carbon/Carbon.h>
55 #import <CoreFoundation/CoreFoundation.h>
56 #import <WebKit/DOMElement.h>
57 #import <WebKit/DOMExtensions.h>
58 #import <WebKit/DOMRange.h>
59 #import <WebKit/WebBackForwardList.h>
60 #import <WebKit/WebCache.h>
61 #import <WebKit/WebCoreStatistics.h>
62 #import <WebKit/WebDataSourcePrivate.h>
63 #import <WebKit/WebDatabaseManagerPrivate.h>
64 #import <WebKit/WebDocumentPrivate.h>
65 #import <WebKit/WebEditingDelegate.h>
66 #import <WebKit/WebFrameView.h>
67 #import <WebKit/WebHTMLRepresentationInternal.h>
68 #import <WebKit/WebHistory.h>
69 #import <WebKit/WebHistoryItemPrivate.h>
70 #import <WebKit/WebInspector.h>
71 #import <WebKit/WebKitNSStringExtras.h>
72 #import <WebKit/WebPluginDatabase.h>
73 #import <WebKit/WebPreferences.h>
74 #import <WebKit/WebPreferencesPrivate.h>
75 #import <WebKit/WebPreferenceKeysPrivate.h>
76 #import <WebKit/WebResourceLoadDelegate.h>
77 #import <WebKit/WebTypesInternal.h>
78 #import <WebKit/WebViewPrivate.h>
80 #import <objc/objc-runtime.h>
81 #import <wtf/Assertions.h>
82 #import <wtf/RetainPtr.h>
83 #import <wtf/Threading.h>
84 #import <wtf/OwnPtr.h>
87 #import <mach-o/getsect.h>
92 @interface DumpRenderTreeApplication : NSApplication
95 @interface DumpRenderTreeEvent : NSEvent
98 @interface NSURLRequest (PrivateThingsWeShouldntReallyUse)
99 +(void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString *)host;
102 static void runTest(const string& testPathOrURL);
104 // Deciding when it's OK to dump out the state is a bit tricky. All these must be true:
105 // - There is no load in progress
106 // - There is no work queued up (see workQueue var, below)
107 // - waitToDump==NO. This means either waitUntilDone was never called, or it was called
108 // and notifyDone was called subsequently.
109 // Note that the call to notifyDone and the end of the load can happen in either order.
113 NavigationController* gNavigationController = 0;
114 RefPtr<LayoutTestController> gLayoutTestController;
116 WebFrame *mainFrame = 0;
117 // This is the topmost frame that is loading, during a given load, or nil when no load is
118 // in progress. Usually this is the same as the main frame, but not always. In the case
119 // where a frameset is loaded, and then new content is loaded into one of the child frames,
120 // that child frame is the "topmost frame that is loading".
121 WebFrame *topLoadingFrame = nil; // !nil iff a load is in progress
124 CFMutableSetRef disallowedURLs = 0;
125 CFRunLoopTimerRef waitToDumpWatchdog = 0;
128 static FrameLoadDelegate *frameLoadDelegate;
129 static UIDelegate *uiDelegate;
130 static EditingDelegate *editingDelegate;
131 static ResourceLoadDelegate *resourceLoadDelegate;
132 static HistoryDelegate *historyDelegate;
133 PolicyDelegate *policyDelegate;
135 static int dumpPixels;
137 static int dumpTree = YES;
138 static int forceComplexText;
139 static BOOL printSeparators;
140 static RetainPtr<CFStringRef> persistentUserStyleSheetLocation;
142 static WebHistoryItem *prevTestBFItem = nil; // current b/f item at the end of the previous test
145 static void swizzleAllMethods(Class imposter, Class original)
147 unsigned int imposterMethodCount;
148 Method* imposterMethods = class_copyMethodList(imposter, &imposterMethodCount);
150 unsigned int originalMethodCount;
151 Method* originalMethods = class_copyMethodList(original, &originalMethodCount);
153 for (unsigned int i = 0; i < imposterMethodCount; i++) {
154 SEL imposterMethodName = method_getName(imposterMethods[i]);
156 // Attempt to add the method to the original class. If it fails, the method already exists and we should
157 // instead exchange the implementations.
158 if (class_addMethod(original, imposterMethodName, method_getImplementation(imposterMethods[i]), method_getTypeEncoding(imposterMethods[i])))
162 for (; j < originalMethodCount; j++) {
163 SEL originalMethodName = method_getName(originalMethods[j]);
164 if (sel_isEqual(imposterMethodName, originalMethodName))
168 // If class_addMethod failed above then the method must exist on the original class.
169 ASSERT(j < originalMethodCount);
170 method_exchangeImplementations(imposterMethods[i], originalMethods[j]);
173 free(imposterMethods);
174 free(originalMethods);
178 static void poseAsClass(const char* imposter, const char* original)
180 Class imposterClass = objc_getClass(imposter);
181 Class originalClass = objc_getClass(original);
184 class_poseAs(imposterClass, originalClass);
187 // Swizzle instance methods
188 swizzleAllMethods(imposterClass, originalClass);
189 // and then class methods
190 swizzleAllMethods(object_getClass(imposterClass), object_getClass(originalClass));
194 void setPersistentUserStyleSheetLocation(CFStringRef url)
196 persistentUserStyleSheetLocation = url;
199 static bool shouldIgnoreWebCoreNodeLeaks(const string& URLString)
201 static char* const ignoreSet[] = {
202 // Keeping this infrastructure around in case we ever need it again.
204 static const int ignoreSetCount = sizeof(ignoreSet) / sizeof(char*);
206 for (int i = 0; i < ignoreSetCount; i++) {
207 // FIXME: ignore case
208 string curIgnore(ignoreSet[i]);
209 // Match at the end of the URLString
210 if (!URLString.compare(URLString.length() - curIgnore.length(), curIgnore.length(), curIgnore))
216 static void activateFonts()
218 #if defined(BUILDING_ON_LEOPARD) || defined(BUILDING_ON_TIGER)
219 static const char* fontSectionNames[] = {
233 for (unsigned i = 0; fontSectionNames[i]; ++i) {
234 unsigned long fontDataLength;
235 char* fontData = getsectdata("__DATA", fontSectionNames[i], &fontDataLength);
237 fprintf(stderr, "Failed to locate the %s font.\n", fontSectionNames[i]);
241 ATSFontContainerRef fontContainer;
242 OSStatus status = ATSFontActivateFromMemory(fontData, fontDataLength, kATSFontContextLocal, kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &fontContainer);
244 if (status != noErr) {
245 fprintf(stderr, "Failed to activate the %s font.\n", fontSectionNames[i]);
251 // Work around <rdar://problem/6698023> by activating fonts from disk
252 // FIXME: This code can be removed once <rdar://problem/6698023> is addressed.
254 static const char* fontFileNames[] = {
257 "WebKitWeightWatcher100.ttf",
258 "WebKitWeightWatcher200.ttf",
259 "WebKitWeightWatcher300.ttf",
260 "WebKitWeightWatcher400.ttf",
261 "WebKitWeightWatcher500.ttf",
262 "WebKitWeightWatcher600.ttf",
263 "WebKitWeightWatcher700.ttf",
264 "WebKitWeightWatcher800.ttf",
265 "WebKitWeightWatcher900.ttf",
269 NSMutableArray *fontURLs = [NSMutableArray array];
270 NSURL *resourcesDirectory = [NSURL URLWithString:@"DumpRenderTree.resources" relativeToURL:[[NSBundle mainBundle] executableURL]];
271 for (unsigned i = 0; fontFileNames[i]; ++i) {
272 NSURL *fontURL = [resourcesDirectory URLByAppendingPathComponent:[NSString stringWithUTF8String:fontFileNames[i]]];
273 [fontURLs addObject:[fontURL absoluteURL]];
276 CFArrayRef errors = 0;
277 if (!CTFontManagerRegisterFontsForURLs((CFArrayRef)fontURLs, kCTFontManagerScopeProcess, &errors)) {
278 NSLog(@"Failed to activate fonts: %@", errors);
285 WebView *createWebViewAndOffscreenWindow()
287 NSRect rect = NSMakeRect(0, 0, LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight);
288 WebView *webView = [[WebView alloc] initWithFrame:rect frameName:nil groupName:@"org.webkit.DumpRenderTree"];
290 [webView setUIDelegate:uiDelegate];
291 [webView setFrameLoadDelegate:frameLoadDelegate];
292 [webView setEditingDelegate:editingDelegate];
293 [webView setResourceLoadDelegate:resourceLoadDelegate];
294 [webView _setGeolocationProvider:[MockGeolocationProvider shared]];
296 // Register the same schemes that Safari does
297 [WebView registerURLSchemeAsLocal:@"feed"];
298 [WebView registerURLSchemeAsLocal:@"feeds"];
299 [WebView registerURLSchemeAsLocal:@"feedsearch"];
301 [webView setContinuousSpellCheckingEnabled:YES];
303 // 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.
304 // Put it at -10000, -10000 in "flipped coordinates", since WebCore and the DOM use flipped coordinates.
305 NSRect windowRect = NSOffsetRect(rect, -10000, [[[NSScreen screens] objectAtIndex:0] frame].size.height - rect.size.height + 10000);
306 DumpRenderTreeWindow *window = [[DumpRenderTreeWindow alloc] initWithContentRect:windowRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
308 #if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
309 [window setColorSpace:[[NSScreen mainScreen] colorSpace]];
312 [[window contentView] addSubview:webView];
313 [window orderBack:nil];
314 [window setAutodisplay:NO];
316 [window startListeningForAcceleratedCompositingChanges];
318 // For reasons that are not entirely clear, the following pair of calls makes WebView handle its
319 // dynamic scrollbars properly. Without it, every frame will always have scrollbars.
320 NSBitmapImageRep *imageRep = [webView bitmapImageRepForCachingDisplayInRect:[webView bounds]];
321 [webView cacheDisplayInRect:[webView bounds] toBitmapImageRep:imageRep];
326 void testStringByEvaluatingJavaScriptFromString()
328 // maps expected result <= JavaScript expression
329 NSDictionary *expressions = [NSDictionary dictionaryWithObjectsAndKeys:
334 @"", @"new String()",
335 @"", @"new String('0')",
341 @"", @"(function() { throw 'error'; })()",
349 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
350 WebView *webView = [[WebView alloc] initWithFrame:NSZeroRect frameName:@"" groupName:@""];
352 NSEnumerator *enumerator = [expressions keyEnumerator];
354 while ((expression = [enumerator nextObject])) {
355 NSString *expectedResult = [expressions objectForKey:expression];
356 NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
357 assert([result isEqualToString:expectedResult]);
365 static NSString *libraryPathForDumpRenderTree()
367 //FIXME: This may not be sufficient to prevent interactions/crashes
368 //when running more than one copy of DumpRenderTree.
369 //See https://bugs.webkit.org/show_bug.cgi?id=10906
370 char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
371 if (dumpRenderTreeTemp)
372 return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:dumpRenderTreeTemp length:strlen(dumpRenderTreeTemp)];
374 return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
377 // Called before each test.
378 static void resetDefaultsToConsistentValues()
380 // Give some clear to undocumented defaults values
381 static const int NoFontSmoothing = 0;
382 static const int BlueTintedAppearance = 1;
384 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
385 [defaults setInteger:4 forKey:@"AppleAntiAliasingThreshold"]; // smallest font size to CG should perform antialiasing on
386 [defaults setInteger:NoFontSmoothing forKey:@"AppleFontSmoothing"];
387 [defaults setInteger:BlueTintedAppearance forKey:@"AppleAquaColorVariant"];
388 [defaults setObject:@"0.709800 0.835300 1.000000" forKey:@"AppleHighlightColor"];
389 [defaults setObject:@"0.500000 0.500000 0.500000" forKey:@"AppleOtherHighlightColor"];
390 [defaults setObject:[NSArray arrayWithObject:@"en"] forKey:@"AppleLanguages"];
391 [defaults setBool:YES forKey:WebKitEnableFullDocumentTeardownPreferenceKey];
393 // Scrollbars are drawn either using AppKit (which uses NSUserDefaults) or using HIToolbox (which uses CFPreferences / kCFPreferencesAnyApplication / kCFPreferencesCurrentUser / kCFPreferencesAnyHost)
394 [defaults setObject:@"DoubleMax" forKey:@"AppleScrollBarVariant"];
395 RetainPtr<CFTypeRef> initialValue = CFPreferencesCopyValue(CFSTR("AppleScrollBarVariant"), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
396 CFPreferencesSetValue(CFSTR("AppleScrollBarVariant"), CFSTR("DoubleMax"), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
398 // See <rdar://problem/6347388>.
399 ThemeScrollBarArrowStyle style;
400 GetThemeScrollBarArrowStyle(&style); // Force HIToolbox to read from CFPreferences
403 [defaults setBool:NO forKey:@"AppleScrollAnimationEnabled"];
406 CFPreferencesSetValue(CFSTR("AppleScrollBarVariant"), initialValue.get(), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
408 NSString *path = libraryPathForDumpRenderTree();
409 [defaults setObject:[path stringByAppendingPathComponent:@"Databases"] forKey:WebDatabaseDirectoryDefaultsKey];
410 [defaults setObject:[path stringByAppendingPathComponent:@"LocalCache"] forKey:WebKitLocalCacheDefaultsKey];
412 WebPreferences *preferences = [WebPreferences standardPreferences];
414 [preferences setAllowUniversalAccessFromFileURLs:YES];
415 [preferences setAllowFileAccessFromFileURLs:YES];
416 [preferences setStandardFontFamily:@"Times"];
417 [preferences setFixedFontFamily:@"Courier"];
418 [preferences setSerifFontFamily:@"Times"];
419 [preferences setSansSerifFontFamily:@"Helvetica"];
420 [preferences setCursiveFontFamily:@"Apple Chancery"];
421 [preferences setFantasyFontFamily:@"Papyrus"];
422 [preferences setDefaultFontSize:16];
423 [preferences setDefaultFixedFontSize:13];
424 [preferences setMinimumFontSize:1];
425 [preferences setJavaEnabled:NO];
426 [preferences setJavaScriptEnabled:YES];
427 [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
428 [preferences setTabsToLinks:NO];
429 [preferences setDOMPasteAllowed:YES];
430 [preferences setShouldPrintBackgrounds:YES];
431 [preferences setCacheModel:WebCacheModelDocumentBrowser];
432 [preferences setXSSAuditorEnabled:NO];
433 [preferences setExperimentalNotificationsEnabled:NO];
434 [preferences setPluginAllowedRunTime:1];
435 [preferences setPlugInsEnabled:YES];
437 [preferences setPrivateBrowsingEnabled:NO];
438 [preferences setAuthorAndUserStylesEnabled:YES];
439 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
440 [preferences setJavaScriptCanAccessClipboard:YES];
441 [preferences setOfflineWebApplicationCacheEnabled:YES];
442 [preferences setDeveloperExtrasEnabled:NO];
443 [preferences setLoadsImagesAutomatically:YES];
444 [preferences setFrameFlatteningEnabled:NO];
445 [preferences setEditingBehavior:WebKitEditingMacBehavior];
446 if (persistentUserStyleSheetLocation) {
447 [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
448 [preferences setUserStyleSheetEnabled:YES];
450 [preferences setUserStyleSheetEnabled:NO];
452 // The back/forward cache is causing problems due to layouts during transition from one page to another.
453 // So, turn it off for now, but we might want to turn it back on some day.
454 [preferences setUsesPageCache:NO];
455 [preferences setAcceleratedCompositingEnabled:YES];
456 [preferences setWebGLEnabled:NO];
458 [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
460 setlocale(LC_ALL, "");
463 // Called once on DumpRenderTree startup.
464 static void setDefaultsToConsistentValuesForTesting()
466 resetDefaultsToConsistentValues();
468 NSString *path = libraryPathForDumpRenderTree();
469 NSURLCache *sharedCache =
470 [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
472 diskPath:[path stringByAppendingPathComponent:@"URLCache"]];
473 [NSURLCache setSharedURLCache:sharedCache];
474 [sharedCache release];
478 static void* runThread(void* arg)
480 static ThreadIdentifier previousId = 0;
481 ThreadIdentifier currentId = currentThread();
482 // Verify 2 successive threads do not get the same Id.
483 ASSERT(previousId != currentId);
484 previousId = currentId;
488 static void testThreadIdentifierMap()
490 // Imitate 'foreign' threads that are not created by WTF.
492 pthread_create(&pthread, 0, &runThread, 0);
493 pthread_join(pthread, 0);
495 pthread_create(&pthread, 0, &runThread, 0);
496 pthread_join(pthread, 0);
498 // Now create another thread using WTF. On OSX, it will have the same pthread handle
499 // but should get a different ThreadIdentifier.
500 createThread(runThread, 0, "DumpRenderTree: test");
503 static void crashHandler(int sig)
505 char *signalName = strsignal(sig);
506 write(STDERR_FILENO, signalName, strlen(signalName));
507 write(STDERR_FILENO, "\n", 1);
508 restoreMainDisplayColorProfile(0);
512 static void installSignalHandlers()
514 signal(SIGILL, crashHandler); /* 4: illegal instruction (not reset when caught) */
515 signal(SIGTRAP, crashHandler); /* 5: trace trap (not reset when caught) */
516 signal(SIGEMT, crashHandler); /* 7: EMT instruction */
517 signal(SIGFPE, crashHandler); /* 8: floating point exception */
518 signal(SIGBUS, crashHandler); /* 10: bus error */
519 signal(SIGSEGV, crashHandler); /* 11: segmentation violation */
520 signal(SIGSYS, crashHandler); /* 12: bad argument to system call */
521 signal(SIGPIPE, crashHandler); /* 13: write on a pipe with no reader */
522 signal(SIGXCPU, crashHandler); /* 24: exceeded CPU time limit */
523 signal(SIGXFSZ, crashHandler); /* 25: exceeded file size limit */
526 static void allocateGlobalControllers()
528 // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
529 gNavigationController = [[NavigationController alloc] init];
530 frameLoadDelegate = [[FrameLoadDelegate alloc] init];
531 uiDelegate = [[UIDelegate alloc] init];
532 editingDelegate = [[EditingDelegate alloc] init];
533 resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
534 policyDelegate = [[PolicyDelegate alloc] init];
535 historyDelegate = [[HistoryDelegate alloc] init];
538 // ObjC++ doens't seem to let me pass NSObject*& sadly.
539 static inline void releaseAndZero(NSObject** object)
545 static void releaseGlobalControllers()
547 releaseAndZero(&gNavigationController);
548 releaseAndZero(&frameLoadDelegate);
549 releaseAndZero(&editingDelegate);
550 releaseAndZero(&resourceLoadDelegate);
551 releaseAndZero(&uiDelegate);
552 releaseAndZero(&policyDelegate);
555 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
557 struct option options[] = {
558 {"notree", no_argument, &dumpTree, NO},
559 {"pixel-tests", no_argument, &dumpPixels, YES},
560 {"tree", no_argument, &dumpTree, YES},
561 {"threaded", no_argument, &threaded, YES},
562 {"complex-text", no_argument, &forceComplexText, YES},
567 while ((option = getopt_long(argc, (char * const *)argv, "", options, NULL)) != -1) {
569 case '?': // unknown or ambiguous option
570 case ':': // missing argument
577 static void addTestPluginsToPluginSearchPath(const char* executablePath)
579 NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
580 [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
581 [[WebPluginDatabase sharedDatabase] refresh];
584 static bool useLongRunningServerMode(int argc, const char *argv[])
586 // This assumes you've already called getopt_long
587 return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
590 static void runTestingServerLoop()
592 // When DumpRenderTree run in server mode, we just wait around for file names
593 // to be passed to us and read each in turn, passing the results back to the client
594 char filenameBuffer[2048];
595 while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
596 char *newLineCharacter = strchr(filenameBuffer, '\n');
597 if (newLineCharacter)
598 *newLineCharacter = '\0';
600 if (strlen(filenameBuffer) == 0)
603 runTest(filenameBuffer);
607 static void prepareConsistentTestingEnvironment()
609 poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
610 poseAsClass("DumpRenderTreeEvent", "NSEvent");
612 setDefaultsToConsistentValuesForTesting();
616 setupMainDisplayColorProfile();
617 allocateGlobalControllers();
619 makeLargeMallocFailSilently();
622 void dumpRenderTree(int argc, const char *argv[])
624 initializeGlobalsFromCommandLineOptions(argc, argv);
625 prepareConsistentTestingEnvironment();
626 addTestPluginsToPluginSearchPath(argv[0]);
628 installSignalHandlers();
630 if (forceComplexText)
631 [WebView _setAlwaysUsesComplexTextCodePath:YES];
633 WebView *webView = createWebViewAndOffscreenWindow();
634 mainFrame = [webView mainFrame];
636 [[NSURLCache sharedURLCache] removeAllCachedResponses];
639 // <http://webkit.org/b/31200> In order to prevent extra frame load delegate logging being generated if the first test to use SSL
640 // is set to log frame load delegate calls we ignore SSL certificate errors on localhost and 127.0.0.1.
641 #if BUILDING_ON_TIGER
642 // Initialize internal NSURLRequest data for setAllowsAnyHTTPSCertificate:forHost: to work properly.
643 [[[[NSURLRequest alloc] init] autorelease] HTTPMethod];
645 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
646 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
648 // <rdar://problem/5222911>
649 testStringByEvaluatingJavaScriptFromString();
651 // http://webkit.org/b/32689
652 testThreadIdentifierMap();
655 startJavaScriptThreads();
657 if (useLongRunningServerMode(argc, argv)) {
658 printSeparators = YES;
659 runTestingServerLoop();
661 printSeparators = (optind < argc-1 || (dumpPixels && dumpTree));
662 for (int i = optind; i != argc; ++i)
667 stopJavaScriptThreads();
669 NSWindow *window = [webView window];
673 // Work around problem where registering drag types leaves an outstanding
674 // "perform selector" on the window, which retains the window. It's a bit
675 // inelegant and perhaps dangerous to just blow them all away, but in practice
676 // it probably won't cause any trouble (and this is just a test tool, after all).
677 [NSObject cancelPreviousPerformRequestsWithTarget:window];
679 [window close]; // releases when closed
682 releaseGlobalControllers();
684 [DumpRenderTreePasteboard releaseLocalPasteboards];
686 // FIXME: This should be moved onto LayoutTestController and made into a HashSet
687 if (disallowedURLs) {
688 CFRelease(disallowedURLs);
693 restoreMainDisplayColorProfile(0);
696 int main(int argc, const char *argv[])
698 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
699 [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
700 dumpRenderTree(argc, argv);
701 [WebCoreStatistics garbageCollectJavaScriptObjects];
702 [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
707 static NSInteger compareHistoryItems(id item1, id item2, void *context)
709 return [[item1 target] caseInsensitiveCompare:[item2 target]];
712 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
719 for (int i = start; i < indent; i++)
722 NSString *urlString = [item URLString];
723 if ([[NSURL URLWithString:urlString] isFileURL]) {
724 NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
725 urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
728 printf("%s", [urlString UTF8String]);
729 NSString *target = [item target];
730 if (target && [target length] > 0)
731 printf(" (in frame \"%s\")", [target UTF8String]);
732 if ([item isTargetItem])
733 printf(" **nav target**");
735 NSArray *kids = [item children];
737 // must sort to eliminate arbitrary result ordering which defeats reproducible testing
738 kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
739 for (unsigned i = 0; i < [kids count]; i++)
740 dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
744 static void dumpFrameScrollPosition(WebFrame *f)
746 NSPoint scrollPosition = [[[[f frameView] documentView] superview] bounds].origin;
747 if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
748 if ([f parentFrame] != nil)
749 printf("frame '%s' ", [[f name] UTF8String]);
750 printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
753 if (gLayoutTestController->dumpChildFrameScrollPositions()) {
754 NSArray *kids = [f childFrames];
756 for (unsigned i = 0; i < [kids count]; i++)
757 dumpFrameScrollPosition([kids objectAtIndex:i]);
761 static NSString *dumpFramesAsText(WebFrame *frame)
763 DOMDocument *document = [frame DOMDocument];
764 DOMElement *documentElement = [document documentElement];
766 if (!documentElement)
769 NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
771 // Add header for all but the main frame.
772 if ([frame parentFrame])
773 result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
775 [result appendFormat:@"%@\n", [documentElement innerText]];
777 if (gLayoutTestController->dumpChildFramesAsText()) {
778 NSArray *kids = [frame childFrames];
780 for (unsigned i = 0; i < [kids count]; i++)
781 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
788 static NSData *dumpFrameAsPDF(WebFrame *frame)
793 // Sadly we have to dump to a file and then read from that file again
794 // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
795 // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
796 // The goal of this function is to test "real" printing across multiple pages.
797 // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
798 NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
800 NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
801 [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
802 [printInfoDict setObject:path forKey:NSPrintSavePath];
804 NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
805 [printInfo setHorizontalPagination:NSAutoPagination];
806 [printInfo setVerticalPagination:NSAutoPagination];
807 [printInfo setVerticallyCentered:NO];
809 NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
810 [printOperation setShowPanels:NO];
811 [printOperation runOperation];
815 NSData *pdfData = [NSData dataWithContentsOfFile:path];
816 [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
821 static void convertMIMEType(NSMutableString *mimeType)
823 #ifdef BUILDING_ON_LEOPARD
824 // Workaround for <rdar://problem/5539824> on Leopard
825 if ([mimeType isEqualToString:@"text/xml"])
826 [mimeType setString:@"application/xml"];
828 // Workaround for <rdar://problem/6234318> with Dashcode 2.0
829 if ([mimeType isEqualToString:@"application/x-javascript"])
830 [mimeType setString:@"text/javascript"];
833 static void convertWebResourceDataToString(NSMutableDictionary *resource)
835 NSMutableString *mimeType = [resource objectForKey:@"WebResourceMIMEType"];
836 convertMIMEType(mimeType);
838 if ([mimeType hasPrefix:@"text/"] || [[WebHTMLRepresentation supportedNonImageMIMETypes] containsObject:mimeType]) {
839 NSString *textEncodingName = [resource objectForKey:@"WebResourceTextEncodingName"];
840 NSStringEncoding stringEncoding;
841 if ([textEncodingName length] > 0)
842 stringEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)textEncodingName));
844 stringEncoding = NSUTF8StringEncoding;
846 NSData *data = [resource objectForKey:@"WebResourceData"];
847 NSString *dataAsString = [[NSString alloc] initWithData:data encoding:stringEncoding];
849 [resource setObject:dataAsString forKey:@"WebResourceData"];
850 [dataAsString release];
854 static void normalizeHTTPResponseHeaderFields(NSMutableDictionary *fields)
857 if ([fields objectForKey:@"Date"])
858 [fields setObject:@"Sun, 16 Nov 2008 17:00:00 GMT" forKey:@"Date"];
859 if ([fields objectForKey:@"Last-Modified"])
860 [fields setObject:@"Sun, 16 Nov 2008 16:55:00 GMT" forKey:@"Last-Modified"];
861 if ([fields objectForKey:@"Etag"])
862 [fields setObject:@"\"301925-21-45c7d72d3e780\"" forKey:@"Etag"];
863 if ([fields objectForKey:@"Server"])
864 [fields setObject:@"Apache/2.2.9 (Unix) mod_ssl/2.2.9 OpenSSL/0.9.7l PHP/5.2.6" forKey:@"Server"];
867 if ([fields objectForKey:@"Connection"])
868 [fields removeObjectForKey:@"Connection"];
869 if ([fields objectForKey:@"Keep-Alive"])
870 [fields removeObjectForKey:@"Keep-Alive"];
873 static void normalizeWebResourceURL(NSMutableString *webResourceURL)
875 static int fileUrlLength = [(NSString *)@"file://" length];
876 NSRange layoutTestsWebArchivePathRange = [webResourceURL rangeOfString:@"/LayoutTests/" options:NSBackwardsSearch];
877 if (layoutTestsWebArchivePathRange.location == NSNotFound)
879 NSRange currentWorkingDirectoryRange = NSMakeRange(fileUrlLength, layoutTestsWebArchivePathRange.location - fileUrlLength);
880 [webResourceURL replaceCharactersInRange:currentWorkingDirectoryRange withString:@""];
883 static void convertWebResourceResponseToDictionary(NSMutableDictionary *propertyList)
885 NSURLResponse *response = nil;
886 NSData *responseData = [propertyList objectForKey:@"WebResourceResponse"]; // WebResourceResponseKey in WebResource.m
887 if ([responseData isKindOfClass:[NSData class]]) {
888 // Decode NSURLResponse
889 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:responseData];
890 response = [unarchiver decodeObjectForKey:@"WebResourceResponse"]; // WebResourceResponseKey in WebResource.m
891 [unarchiver finishDecoding];
892 [unarchiver release];
895 NSMutableDictionary *responseDictionary = [[NSMutableDictionary alloc] init];
897 NSMutableString *urlString = [[[response URL] description] mutableCopy];
898 normalizeWebResourceURL(urlString);
899 [responseDictionary setObject:urlString forKey:@"URL"];
902 NSMutableString *mimeTypeString = [[response MIMEType] mutableCopy];
903 convertMIMEType(mimeTypeString);
904 [responseDictionary setObject:mimeTypeString forKey:@"MIMEType"];
905 [mimeTypeString release];
907 NSString *textEncodingName = [response textEncodingName];
908 if (textEncodingName)
909 [responseDictionary setObject:textEncodingName forKey:@"textEncodingName"];
910 [responseDictionary setObject:[NSNumber numberWithLongLong:[response expectedContentLength]] forKey:@"expectedContentLength"];
912 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
913 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
915 NSMutableDictionary *allHeaderFields = [[httpResponse allHeaderFields] mutableCopy];
916 normalizeHTTPResponseHeaderFields(allHeaderFields);
917 [responseDictionary setObject:allHeaderFields forKey:@"allHeaderFields"];
918 [allHeaderFields release];
920 [responseDictionary setObject:[NSNumber numberWithInt:[httpResponse statusCode]] forKey:@"statusCode"];
923 [propertyList setObject:responseDictionary forKey:@"WebResourceResponse"];
924 [responseDictionary release];
927 static NSInteger compareResourceURLs(id resource1, id resource2, void *context)
929 NSString *url1 = [resource1 objectForKey:@"WebResourceURL"];
930 NSString *url2 = [resource2 objectForKey:@"WebResourceURL"];
932 return [url1 compare:url2];
935 static NSString *serializeWebArchiveToXML(WebArchive *webArchive)
937 NSString *errorString;
938 NSMutableDictionary *propertyList = [NSPropertyListSerialization propertyListFromData:[webArchive data]
939 mutabilityOption:NSPropertyListMutableContainersAndLeaves
941 errorDescription:&errorString];
945 NSMutableArray *resources = [NSMutableArray arrayWithCapacity:1];
946 [resources addObject:propertyList];
948 while ([resources count]) {
949 NSMutableDictionary *resourcePropertyList = [resources objectAtIndex:0];
950 [resources removeObjectAtIndex:0];
952 NSMutableDictionary *mainResource = [resourcePropertyList objectForKey:@"WebMainResource"];
953 normalizeWebResourceURL([mainResource objectForKey:@"WebResourceURL"]);
954 convertWebResourceDataToString(mainResource);
956 // Add subframeArchives to list for processing
957 NSMutableArray *subframeArchives = [resourcePropertyList objectForKey:@"WebSubframeArchives"]; // WebSubframeArchivesKey in WebArchive.m
958 if (subframeArchives)
959 [resources addObjectsFromArray:subframeArchives];
961 NSMutableArray *subresources = [resourcePropertyList objectForKey:@"WebSubresources"]; // WebSubresourcesKey in WebArchive.m
962 NSEnumerator *enumerator = [subresources objectEnumerator];
963 NSMutableDictionary *subresourcePropertyList;
964 while ((subresourcePropertyList = [enumerator nextObject])) {
965 normalizeWebResourceURL([subresourcePropertyList objectForKey:@"WebResourceURL"]);
966 convertWebResourceResponseToDictionary(subresourcePropertyList);
967 convertWebResourceDataToString(subresourcePropertyList);
970 // Sort the subresources so they're always in a predictable order for the dump
971 if (NSArray *sortedSubresources = [subresources sortedArrayUsingFunction:compareResourceURLs context:nil])
972 [resourcePropertyList setObject:sortedSubresources forKey:@"WebSubresources"];
975 NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:propertyList
976 format:NSPropertyListXMLFormat_v1_0
977 errorDescription:&errorString];
981 NSMutableString *string = [[[NSMutableString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding] autorelease];
983 // Replace "Apple Computer" with "Apple" in the DTD declaration.
984 NSRange range = [string rangeOfString:@"-//Apple Computer//"];
985 if (range.location != NSNotFound)
986 [string replaceCharactersInRange:range withString:@"-//Apple//"];
991 static void dumpBackForwardListForWebView(WebView *view)
993 printf("\n============== Back Forward List ==============\n");
994 WebBackForwardList *bfList = [view backForwardList];
996 // Print out all items in the list after prevTestBFItem, which was from the previous test
997 // Gather items from the end of the list, the print them out from oldest to newest
998 NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
999 for (int i = [bfList forwardListCount]; i > 0; i--) {
1000 WebHistoryItem *item = [bfList itemAtIndex:i];
1001 // something is wrong if the item from the last test is in the forward part of the b/f list
1002 assert(item != prevTestBFItem);
1003 [itemsToPrint addObject:item];
1006 assert([bfList currentItem] != prevTestBFItem);
1007 [itemsToPrint addObject:[bfList currentItem]];
1008 int currentItemIndex = [itemsToPrint count] - 1;
1010 for (int i = -1; i >= -[bfList backListCount]; i--) {
1011 WebHistoryItem *item = [bfList itemAtIndex:i];
1012 if (item == prevTestBFItem)
1014 [itemsToPrint addObject:item];
1017 for (int i = [itemsToPrint count]-1; i >= 0; i--)
1018 dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1020 [itemsToPrint release];
1021 printf("===============================================\n");
1024 static void sizeWebViewForCurrentTest()
1026 // W3C SVG tests expect to be 480x360
1027 bool isSVGW3CTest = (gLayoutTestController->testPathOrURL().find("svg/W3C-SVG-1.1") != string::npos);
1029 [[mainFrame webView] setFrameSize:NSMakeSize(480, 360)];
1031 [[mainFrame webView] setFrameSize:NSMakeSize(LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight)];
1034 static const char *methodNameStringForFailedTest()
1036 const char *errorMessage;
1037 if (gLayoutTestController->dumpAsText())
1038 errorMessage = "[documentElement innerText]";
1039 else if (gLayoutTestController->dumpDOMAsWebArchive())
1040 errorMessage = "[[mainFrame DOMDocument] webArchive]";
1041 else if (gLayoutTestController->dumpSourceAsWebArchive())
1042 errorMessage = "[[mainFrame dataSource] webArchive]";
1044 errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1046 return errorMessage;
1049 static void dumpBackForwardListForAllWindows()
1051 CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1052 unsigned count = CFArrayGetCount(openWindows);
1053 for (unsigned i = 0; i < count; i++) {
1054 NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1055 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1056 dumpBackForwardListForWebView(webView);
1060 static void invalidateAnyPreviousWaitToDumpWatchdog()
1062 if (waitToDumpWatchdog) {
1063 CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1064 CFRelease(waitToDumpWatchdog);
1065 waitToDumpWatchdog = 0;
1071 invalidateAnyPreviousWaitToDumpWatchdog();
1073 bool dumpAsText = gLayoutTestController->dumpAsText();
1075 NSString *resultString = nil;
1076 NSData *resultData = nil;
1077 NSString *resultMimeType = @"text/plain";
1079 dumpAsText |= [[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"];
1080 gLayoutTestController->setDumpAsText(dumpAsText);
1081 if (gLayoutTestController->dumpAsText()) {
1082 resultString = dumpFramesAsText(mainFrame);
1083 } else if (gLayoutTestController->dumpAsPDF()) {
1084 resultData = dumpFrameAsPDF(mainFrame);
1085 resultMimeType = @"application/pdf";
1086 } else if (gLayoutTestController->dumpDOMAsWebArchive()) {
1087 WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1088 resultString = serializeWebArchiveToXML(webArchive);
1089 resultMimeType = @"application/x-webarchive";
1090 } else if (gLayoutTestController->dumpSourceAsWebArchive()) {
1091 WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1092 resultString = serializeWebArchiveToXML(webArchive);
1093 resultMimeType = @"application/x-webarchive";
1095 sizeWebViewForCurrentTest();
1096 resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gLayoutTestController->isPrinting()];
1099 if (resultString && !resultData)
1100 resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1102 printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1105 fwrite([resultData bytes], 1, [resultData length], stdout);
1107 if (!gLayoutTestController->dumpAsText() && !gLayoutTestController->dumpDOMAsWebArchive() && !gLayoutTestController->dumpSourceAsWebArchive())
1108 dumpFrameScrollPosition(mainFrame);
1110 if (gLayoutTestController->dumpBackForwardList())
1111 dumpBackForwardListForAllWindows();
1113 printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1115 // Stop the watchdog thread before we leave this test to make sure it doesn't
1116 // fire in between tests causing the next test to fail.
1117 // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1118 invalidateAnyPreviousWaitToDumpWatchdog();
1120 if (printSeparators) {
1121 puts("#EOF"); // terminate the content block
1122 fputs("#EOF\n", stderr);
1126 if (dumpPixels && gLayoutTestController->generatePixelResults())
1127 // FIXME: when isPrinting is set, dump the image with page separators.
1128 dumpWebViewAsPixelsAndCompareWithExpected(gLayoutTestController->expectedPixelHash());
1130 puts("#EOF"); // terminate the (possibly empty) pixels block
1138 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1140 return strstr(pathOrURL, "loading/");
1143 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1145 return strstr(pathOrURL, "globalhistory/");
1148 static bool shouldOpenWebInspector(const char* pathOrURL)
1150 return strstr(pathOrURL, "inspector/");
1153 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1155 return shouldOpenWebInspector(pathOrURL) || strstr(pathOrURL, "inspector-enabled/");
1158 static void resetWebViewToConsistentStateBeforeTesting()
1160 WebView *webView = [mainFrame webView];
1161 [webView setEditable:NO];
1162 [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1163 [webView makeTextStandardSize:nil];
1164 [webView resetPageZoom:nil];
1165 [webView setTabKeyCyclesThroughElements:YES];
1166 [webView setPolicyDelegate:nil];
1167 [policyDelegate setPermissive:NO];
1168 [policyDelegate setControllerToNotifyDone:0];
1169 [frameLoadDelegate resetToConsistentState];
1170 [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1171 [webView _clearMainFrameName];
1172 [[webView undoManager] removeAllActions];
1173 [WebView _removeAllUserContentFromGroup:[webView groupName]];
1174 [[webView window] setAutodisplay:NO];
1176 resetDefaultsToConsistentValues();
1178 [[mainFrame webView] setSmartInsertDeleteEnabled:YES];
1179 [[[mainFrame webView] inspector] setJavaScriptProfilingEnabled:NO];
1181 [WebView _setUsesTestModeFocusRingColor:YES];
1182 [WebView _resetOriginAccessWhitelists];
1184 [[MockGeolocationProvider shared] stopTimer];
1186 // Clear the contents of the general pasteboard
1187 [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1190 static void runTest(const string& testPathOrURL)
1192 ASSERT(!testPathOrURL.empty());
1194 // Look for "'" as a separator between the path or URL, and the pixel dump hash that follows.
1195 string pathOrURL(testPathOrURL);
1196 string expectedPixelHash;
1198 size_t separatorPos = pathOrURL.find("'");
1199 if (separatorPos != string::npos) {
1200 pathOrURL = string(testPathOrURL, 0, separatorPos);
1201 expectedPixelHash = string(testPathOrURL, separatorPos + 1);
1204 NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1205 if (!pathOrURLString) {
1206 fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1211 if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"])
1212 url = [NSURL URLWithString:pathOrURLString];
1214 url = [NSURL fileURLWithPath:pathOrURLString];
1216 fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1220 const string testURL([[url absoluteString] UTF8String]);
1222 resetWebViewToConsistentStateBeforeTesting();
1224 gLayoutTestController = LayoutTestController::create(testURL, expectedPixelHash);
1225 topLoadingFrame = nil;
1226 ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1227 releaseAndZero(&draggingInfo);
1230 gLayoutTestController->setIconDatabaseEnabled(false);
1233 CFSetRemoveAllValues(disallowedURLs);
1234 if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1235 gLayoutTestController->setDumpFrameLoadCallbacks(true);
1237 if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1238 [[mainFrame webView] setHistoryDelegate:historyDelegate];
1240 [[mainFrame webView] setHistoryDelegate:nil];
1242 if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1243 gLayoutTestController->setDeveloperExtrasEnabled(true);
1244 if (shouldOpenWebInspector(pathOrURL.c_str()))
1245 gLayoutTestController->showWebInspector();
1248 if ([WebHistory optionalSharedHistory])
1249 [WebHistory setOptionalSharedHistory:nil];
1250 lastMousePosition = NSZeroPoint;
1251 lastClickPosition = NSZeroPoint;
1253 [prevTestBFItem release];
1254 prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
1256 WorkQueue::shared()->clear();
1257 WorkQueue::shared()->setFrozen(false);
1259 bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
1260 if (ignoreWebCoreNodeLeaks)
1261 [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
1263 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1264 [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
1268 pool = [[NSAutoreleasePool alloc] init];
1269 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1273 pool = [[NSAutoreleasePool alloc] init];
1274 [EventSendingController clearSavedEvents];
1275 [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
1277 WorkQueue::shared()->clear();
1279 if (gLayoutTestController->closeRemainingWindowsWhenComplete()) {
1280 NSArray* array = [DumpRenderTreeWindow openWindows];
1282 unsigned count = [array count];
1283 for (unsigned i = 0; i < count; i++) {
1284 NSWindow *window = [array objectAtIndex:i];
1286 // Don't try to close the main window
1287 if (window == [[mainFrame webView] window])
1290 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1297 // If developer extras enabled Web Inspector may have been open by the test.
1298 if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1299 gLayoutTestController->closeWebInspector();
1300 gLayoutTestController->setDeveloperExtrasEnabled(false);
1303 resetWebViewToConsistentStateBeforeTesting();
1305 [mainFrame loadHTMLString:@"<html></html>" baseURL:[NSURL URLWithString:@"about:blank"]];
1306 [mainFrame stopLoading];
1310 // We should only have our main window left open when we're done
1311 ASSERT(CFArrayGetCount(openWindowsRef) == 1);
1312 ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
1314 gLayoutTestController.clear();
1316 if (ignoreWebCoreNodeLeaks)
1317 [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
1320 void displayWebView()
1322 NSView *webView = [mainFrame webView];
1324 [webView lockFocus];
1325 [[[NSColor blackColor] colorWithAlphaComponent:0.66] set];
1326 NSRectFillUsingOperation([webView frame], NSCompositeSourceOver);
1327 [webView unlockFocus];
1330 @implementation DumpRenderTreeEvent
1332 + (NSPoint)mouseLocation
1334 return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
1339 @implementation DumpRenderTreeApplication
1343 // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running