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 int useHTML5Parser = YES;
140 static int useHTML5TreeBuilder = NO; // Temporary, will be removed.
141 static BOOL printSeparators;
142 static RetainPtr<CFStringRef> persistentUserStyleSheetLocation;
144 static WebHistoryItem *prevTestBFItem = nil; // current b/f item at the end of the previous test
147 static void swizzleAllMethods(Class imposter, Class original)
149 unsigned int imposterMethodCount;
150 Method* imposterMethods = class_copyMethodList(imposter, &imposterMethodCount);
152 unsigned int originalMethodCount;
153 Method* originalMethods = class_copyMethodList(original, &originalMethodCount);
155 for (unsigned int i = 0; i < imposterMethodCount; i++) {
156 SEL imposterMethodName = method_getName(imposterMethods[i]);
158 // Attempt to add the method to the original class. If it fails, the method already exists and we should
159 // instead exchange the implementations.
160 if (class_addMethod(original, imposterMethodName, method_getImplementation(imposterMethods[i]), method_getTypeEncoding(imposterMethods[i])))
164 for (; j < originalMethodCount; j++) {
165 SEL originalMethodName = method_getName(originalMethods[j]);
166 if (sel_isEqual(imposterMethodName, originalMethodName))
170 // If class_addMethod failed above then the method must exist on the original class.
171 ASSERT(j < originalMethodCount);
172 method_exchangeImplementations(imposterMethods[i], originalMethods[j]);
175 free(imposterMethods);
176 free(originalMethods);
180 static void poseAsClass(const char* imposter, const char* original)
182 Class imposterClass = objc_getClass(imposter);
183 Class originalClass = objc_getClass(original);
186 class_poseAs(imposterClass, originalClass);
189 // Swizzle instance methods
190 swizzleAllMethods(imposterClass, originalClass);
191 // and then class methods
192 swizzleAllMethods(object_getClass(imposterClass), object_getClass(originalClass));
196 void setPersistentUserStyleSheetLocation(CFStringRef url)
198 persistentUserStyleSheetLocation = url;
201 static bool shouldIgnoreWebCoreNodeLeaks(const string& URLString)
203 static char* const ignoreSet[] = {
204 // Keeping this infrastructure around in case we ever need it again.
206 static const int ignoreSetCount = sizeof(ignoreSet) / sizeof(char*);
208 for (int i = 0; i < ignoreSetCount; i++) {
209 // FIXME: ignore case
210 string curIgnore(ignoreSet[i]);
211 // Match at the end of the URLString
212 if (!URLString.compare(URLString.length() - curIgnore.length(), curIgnore.length(), curIgnore))
218 static void activateFonts()
220 #if defined(BUILDING_ON_LEOPARD) || defined(BUILDING_ON_TIGER)
221 static const char* fontSectionNames[] = {
235 for (unsigned i = 0; fontSectionNames[i]; ++i) {
236 unsigned long fontDataLength;
237 char* fontData = getsectdata("__DATA", fontSectionNames[i], &fontDataLength);
239 fprintf(stderr, "Failed to locate the %s font.\n", fontSectionNames[i]);
243 ATSFontContainerRef fontContainer;
244 OSStatus status = ATSFontActivateFromMemory(fontData, fontDataLength, kATSFontContextLocal, kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &fontContainer);
246 if (status != noErr) {
247 fprintf(stderr, "Failed to activate the %s font.\n", fontSectionNames[i]);
253 // Work around <rdar://problem/6698023> by activating fonts from disk
254 // FIXME: This code can be removed once <rdar://problem/6698023> is addressed.
256 static const char* fontFileNames[] = {
259 "WebKitWeightWatcher100.ttf",
260 "WebKitWeightWatcher200.ttf",
261 "WebKitWeightWatcher300.ttf",
262 "WebKitWeightWatcher400.ttf",
263 "WebKitWeightWatcher500.ttf",
264 "WebKitWeightWatcher600.ttf",
265 "WebKitWeightWatcher700.ttf",
266 "WebKitWeightWatcher800.ttf",
267 "WebKitWeightWatcher900.ttf",
271 NSMutableArray *fontURLs = [NSMutableArray array];
272 NSURL *resourcesDirectory = [NSURL URLWithString:@"DumpRenderTree.resources" relativeToURL:[[NSBundle mainBundle] executableURL]];
273 for (unsigned i = 0; fontFileNames[i]; ++i) {
274 NSURL *fontURL = [resourcesDirectory URLByAppendingPathComponent:[NSString stringWithUTF8String:fontFileNames[i]]];
275 [fontURLs addObject:[fontURL absoluteURL]];
278 CFArrayRef errors = 0;
279 if (!CTFontManagerRegisterFontsForURLs((CFArrayRef)fontURLs, kCTFontManagerScopeProcess, &errors)) {
280 NSLog(@"Failed to activate fonts: %@", errors);
287 WebView *createWebViewAndOffscreenWindow()
289 NSRect rect = NSMakeRect(0, 0, LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight);
290 WebView *webView = [[WebView alloc] initWithFrame:rect frameName:nil groupName:@"org.webkit.DumpRenderTree"];
292 [webView setUIDelegate:uiDelegate];
293 [webView setFrameLoadDelegate:frameLoadDelegate];
294 [webView setEditingDelegate:editingDelegate];
295 [webView setResourceLoadDelegate:resourceLoadDelegate];
296 [webView _setGeolocationProvider:[MockGeolocationProvider shared]];
298 // Register the same schemes that Safari does
299 [WebView registerURLSchemeAsLocal:@"feed"];
300 [WebView registerURLSchemeAsLocal:@"feeds"];
301 [WebView registerURLSchemeAsLocal:@"feedsearch"];
303 [webView setContinuousSpellCheckingEnabled:YES];
305 // 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.
306 // Put it at -10000, -10000 in "flipped coordinates", since WebCore and the DOM use flipped coordinates.
307 NSRect windowRect = NSOffsetRect(rect, -10000, [[[NSScreen screens] objectAtIndex:0] frame].size.height - rect.size.height + 10000);
308 DumpRenderTreeWindow *window = [[DumpRenderTreeWindow alloc] initWithContentRect:windowRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
310 #if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
311 [window setColorSpace:[[NSScreen mainScreen] colorSpace]];
314 [[window contentView] addSubview:webView];
315 [window orderBack:nil];
316 [window setAutodisplay:NO];
318 [window startListeningForAcceleratedCompositingChanges];
320 // For reasons that are not entirely clear, the following pair of calls makes WebView handle its
321 // dynamic scrollbars properly. Without it, every frame will always have scrollbars.
322 NSBitmapImageRep *imageRep = [webView bitmapImageRepForCachingDisplayInRect:[webView bounds]];
323 [webView cacheDisplayInRect:[webView bounds] toBitmapImageRep:imageRep];
328 void testStringByEvaluatingJavaScriptFromString()
330 // maps expected result <= JavaScript expression
331 NSDictionary *expressions = [NSDictionary dictionaryWithObjectsAndKeys:
336 @"", @"new String()",
337 @"", @"new String('0')",
343 @"", @"(function() { throw 'error'; })()",
351 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
352 WebView *webView = [[WebView alloc] initWithFrame:NSZeroRect frameName:@"" groupName:@""];
354 NSEnumerator *enumerator = [expressions keyEnumerator];
356 while ((expression = [enumerator nextObject])) {
357 NSString *expectedResult = [expressions objectForKey:expression];
358 NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
359 assert([result isEqualToString:expectedResult]);
367 static NSString *libraryPathForDumpRenderTree()
369 //FIXME: This may not be sufficient to prevent interactions/crashes
370 //when running more than one copy of DumpRenderTree.
371 //See https://bugs.webkit.org/show_bug.cgi?id=10906
372 char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
373 if (dumpRenderTreeTemp)
374 return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:dumpRenderTreeTemp length:strlen(dumpRenderTreeTemp)];
376 return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
379 // Called before each test.
380 static void resetDefaultsToConsistentValues()
382 // Give some clear to undocumented defaults values
383 static const int NoFontSmoothing = 0;
384 static const int BlueTintedAppearance = 1;
386 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
387 [defaults setInteger:4 forKey:@"AppleAntiAliasingThreshold"]; // smallest font size to CG should perform antialiasing on
388 [defaults setInteger:NoFontSmoothing forKey:@"AppleFontSmoothing"];
389 [defaults setInteger:BlueTintedAppearance forKey:@"AppleAquaColorVariant"];
390 [defaults setObject:@"0.709800 0.835300 1.000000" forKey:@"AppleHighlightColor"];
391 [defaults setObject:@"0.500000 0.500000 0.500000" forKey:@"AppleOtherHighlightColor"];
392 [defaults setObject:[NSArray arrayWithObject:@"en"] forKey:@"AppleLanguages"];
393 [defaults setBool:YES forKey:WebKitEnableFullDocumentTeardownPreferenceKey];
395 // Scrollbars are drawn either using AppKit (which uses NSUserDefaults) or using HIToolbox (which uses CFPreferences / kCFPreferencesAnyApplication / kCFPreferencesCurrentUser / kCFPreferencesAnyHost)
396 [defaults setObject:@"DoubleMax" forKey:@"AppleScrollBarVariant"];
397 RetainPtr<CFTypeRef> initialValue = CFPreferencesCopyValue(CFSTR("AppleScrollBarVariant"), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
398 CFPreferencesSetValue(CFSTR("AppleScrollBarVariant"), CFSTR("DoubleMax"), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
400 // See <rdar://problem/6347388>.
401 ThemeScrollBarArrowStyle style;
402 GetThemeScrollBarArrowStyle(&style); // Force HIToolbox to read from CFPreferences
405 [defaults setBool:NO forKey:@"AppleScrollAnimationEnabled"];
408 CFPreferencesSetValue(CFSTR("AppleScrollBarVariant"), initialValue.get(), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
410 NSString *path = libraryPathForDumpRenderTree();
411 [defaults setObject:[path stringByAppendingPathComponent:@"Databases"] forKey:WebDatabaseDirectoryDefaultsKey];
412 [defaults setObject:[path stringByAppendingPathComponent:@"LocalCache"] forKey:WebKitLocalCacheDefaultsKey];
414 WebPreferences *preferences = [WebPreferences standardPreferences];
416 [preferences setAllowUniversalAccessFromFileURLs:YES];
417 [preferences setAllowFileAccessFromFileURLs:YES];
418 [preferences setStandardFontFamily:@"Times"];
419 [preferences setFixedFontFamily:@"Courier"];
420 [preferences setSerifFontFamily:@"Times"];
421 [preferences setSansSerifFontFamily:@"Helvetica"];
422 [preferences setCursiveFontFamily:@"Apple Chancery"];
423 [preferences setFantasyFontFamily:@"Papyrus"];
424 [preferences setDefaultFontSize:16];
425 [preferences setDefaultFixedFontSize:13];
426 [preferences setMinimumFontSize:1];
427 [preferences setJavaEnabled:NO];
428 [preferences setJavaScriptEnabled:YES];
429 [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
430 [preferences setTabsToLinks:NO];
431 [preferences setDOMPasteAllowed:YES];
432 [preferences setShouldPrintBackgrounds:YES];
433 [preferences setCacheModel:WebCacheModelDocumentBrowser];
434 [preferences setXSSAuditorEnabled:NO];
435 [preferences setExperimentalNotificationsEnabled:NO];
436 [preferences setPluginAllowedRunTime:1];
437 [preferences setPlugInsEnabled:YES];
439 [preferences setPrivateBrowsingEnabled:NO];
440 [preferences setAuthorAndUserStylesEnabled:YES];
441 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
442 [preferences setJavaScriptCanAccessClipboard:YES];
443 [preferences setOfflineWebApplicationCacheEnabled:YES];
444 [preferences setDeveloperExtrasEnabled:NO];
445 [preferences setLoadsImagesAutomatically:YES];
446 [preferences setFrameFlatteningEnabled:NO];
447 [preferences setEditingBehavior:WebKitEditingMacBehavior];
448 if (persistentUserStyleSheetLocation) {
449 [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
450 [preferences setUserStyleSheetEnabled:YES];
452 [preferences setUserStyleSheetEnabled:NO];
454 // The back/forward cache is causing problems due to layouts during transition from one page to another.
455 // So, turn it off for now, but we might want to turn it back on some day.
456 [preferences setUsesPageCache:NO];
457 [preferences setAcceleratedCompositingEnabled:YES];
458 [preferences setWebGLEnabled:NO];
459 [preferences setHTML5ParserEnabled:useHTML5Parser];
460 [preferences setHTML5TreeBuilderEnabled:useHTML5TreeBuilder]; // Temporary, will be removed.
462 [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
464 setlocale(LC_ALL, "");
467 // Called once on DumpRenderTree startup.
468 static void setDefaultsToConsistentValuesForTesting()
470 resetDefaultsToConsistentValues();
472 NSString *path = libraryPathForDumpRenderTree();
473 NSURLCache *sharedCache =
474 [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
476 diskPath:[path stringByAppendingPathComponent:@"URLCache"]];
477 [NSURLCache setSharedURLCache:sharedCache];
478 [sharedCache release];
482 static void* runThread(void* arg)
484 static ThreadIdentifier previousId = 0;
485 ThreadIdentifier currentId = currentThread();
486 // Verify 2 successive threads do not get the same Id.
487 ASSERT(previousId != currentId);
488 previousId = currentId;
492 static void testThreadIdentifierMap()
494 // Imitate 'foreign' threads that are not created by WTF.
496 pthread_create(&pthread, 0, &runThread, 0);
497 pthread_join(pthread, 0);
499 pthread_create(&pthread, 0, &runThread, 0);
500 pthread_join(pthread, 0);
502 // Now create another thread using WTF. On OSX, it will have the same pthread handle
503 // but should get a different ThreadIdentifier.
504 createThread(runThread, 0, "DumpRenderTree: test");
507 static void crashHandler(int sig)
509 char *signalName = strsignal(sig);
510 write(STDERR_FILENO, signalName, strlen(signalName));
511 write(STDERR_FILENO, "\n", 1);
512 restoreMainDisplayColorProfile(0);
516 static void installSignalHandlers()
518 signal(SIGILL, crashHandler); /* 4: illegal instruction (not reset when caught) */
519 signal(SIGTRAP, crashHandler); /* 5: trace trap (not reset when caught) */
520 signal(SIGEMT, crashHandler); /* 7: EMT instruction */
521 signal(SIGFPE, crashHandler); /* 8: floating point exception */
522 signal(SIGBUS, crashHandler); /* 10: bus error */
523 signal(SIGSEGV, crashHandler); /* 11: segmentation violation */
524 signal(SIGSYS, crashHandler); /* 12: bad argument to system call */
525 signal(SIGPIPE, crashHandler); /* 13: write on a pipe with no reader */
526 signal(SIGXCPU, crashHandler); /* 24: exceeded CPU time limit */
527 signal(SIGXFSZ, crashHandler); /* 25: exceeded file size limit */
530 static void allocateGlobalControllers()
532 // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
533 gNavigationController = [[NavigationController alloc] init];
534 frameLoadDelegate = [[FrameLoadDelegate alloc] init];
535 uiDelegate = [[UIDelegate alloc] init];
536 editingDelegate = [[EditingDelegate alloc] init];
537 resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
538 policyDelegate = [[PolicyDelegate alloc] init];
539 historyDelegate = [[HistoryDelegate alloc] init];
542 // ObjC++ doens't seem to let me pass NSObject*& sadly.
543 static inline void releaseAndZero(NSObject** object)
549 static void releaseGlobalControllers()
551 releaseAndZero(&gNavigationController);
552 releaseAndZero(&frameLoadDelegate);
553 releaseAndZero(&editingDelegate);
554 releaseAndZero(&resourceLoadDelegate);
555 releaseAndZero(&uiDelegate);
556 releaseAndZero(&policyDelegate);
559 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
561 struct option options[] = {
562 {"notree", no_argument, &dumpTree, NO},
563 {"pixel-tests", no_argument, &dumpPixels, YES},
564 {"tree", no_argument, &dumpTree, YES},
565 {"threaded", no_argument, &threaded, YES},
566 {"complex-text", no_argument, &forceComplexText, YES},
567 {"legacy-parser", no_argument, &useHTML5Parser, NO},
568 {"html5-treebuilder", no_argument, &useHTML5TreeBuilder, YES},
573 while ((option = getopt_long(argc, (char * const *)argv, "", options, NULL)) != -1) {
575 case '?': // unknown or ambiguous option
576 case ':': // missing argument
583 static void addTestPluginsToPluginSearchPath(const char* executablePath)
585 NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
586 [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
587 [[WebPluginDatabase sharedDatabase] refresh];
590 static bool useLongRunningServerMode(int argc, const char *argv[])
592 // This assumes you've already called getopt_long
593 return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
596 static void runTestingServerLoop()
598 // When DumpRenderTree run in server mode, we just wait around for file names
599 // to be passed to us and read each in turn, passing the results back to the client
600 char filenameBuffer[2048];
601 while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
602 char *newLineCharacter = strchr(filenameBuffer, '\n');
603 if (newLineCharacter)
604 *newLineCharacter = '\0';
606 if (strlen(filenameBuffer) == 0)
609 runTest(filenameBuffer);
613 static void prepareConsistentTestingEnvironment()
615 poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
616 poseAsClass("DumpRenderTreeEvent", "NSEvent");
618 setDefaultsToConsistentValuesForTesting();
622 setupMainDisplayColorProfile();
623 allocateGlobalControllers();
625 makeLargeMallocFailSilently();
628 void dumpRenderTree(int argc, const char *argv[])
630 initializeGlobalsFromCommandLineOptions(argc, argv);
631 prepareConsistentTestingEnvironment();
632 addTestPluginsToPluginSearchPath(argv[0]);
634 installSignalHandlers();
636 if (forceComplexText)
637 [WebView _setAlwaysUsesComplexTextCodePath:YES];
639 WebView *webView = createWebViewAndOffscreenWindow();
640 mainFrame = [webView mainFrame];
642 [[NSURLCache sharedURLCache] removeAllCachedResponses];
645 // <http://webkit.org/b/31200> In order to prevent extra frame load delegate logging being generated if the first test to use SSL
646 // is set to log frame load delegate calls we ignore SSL certificate errors on localhost and 127.0.0.1.
647 #if BUILDING_ON_TIGER
648 // Initialize internal NSURLRequest data for setAllowsAnyHTTPSCertificate:forHost: to work properly.
649 [[[[NSURLRequest alloc] init] autorelease] HTTPMethod];
651 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
652 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
654 // <rdar://problem/5222911>
655 testStringByEvaluatingJavaScriptFromString();
657 // http://webkit.org/b/32689
658 testThreadIdentifierMap();
661 startJavaScriptThreads();
663 if (useLongRunningServerMode(argc, argv)) {
664 printSeparators = YES;
665 runTestingServerLoop();
667 printSeparators = (optind < argc-1 || (dumpPixels && dumpTree));
668 for (int i = optind; i != argc; ++i)
673 stopJavaScriptThreads();
675 NSWindow *window = [webView window];
679 // Work around problem where registering drag types leaves an outstanding
680 // "perform selector" on the window, which retains the window. It's a bit
681 // inelegant and perhaps dangerous to just blow them all away, but in practice
682 // it probably won't cause any trouble (and this is just a test tool, after all).
683 [NSObject cancelPreviousPerformRequestsWithTarget:window];
685 [window close]; // releases when closed
688 releaseGlobalControllers();
690 [DumpRenderTreePasteboard releaseLocalPasteboards];
692 // FIXME: This should be moved onto LayoutTestController and made into a HashSet
693 if (disallowedURLs) {
694 CFRelease(disallowedURLs);
699 restoreMainDisplayColorProfile(0);
702 int main(int argc, const char *argv[])
704 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
705 [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
706 dumpRenderTree(argc, argv);
707 [WebCoreStatistics garbageCollectJavaScriptObjects];
708 [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
713 static NSInteger compareHistoryItems(id item1, id item2, void *context)
715 return [[item1 target] caseInsensitiveCompare:[item2 target]];
718 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
725 for (int i = start; i < indent; i++)
728 NSString *urlString = [item URLString];
729 if ([[NSURL URLWithString:urlString] isFileURL]) {
730 NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
731 urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
734 printf("%s", [urlString UTF8String]);
735 NSString *target = [item target];
736 if (target && [target length] > 0)
737 printf(" (in frame \"%s\")", [target UTF8String]);
738 if ([item isTargetItem])
739 printf(" **nav target**");
741 NSArray *kids = [item children];
743 // must sort to eliminate arbitrary result ordering which defeats reproducible testing
744 kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
745 for (unsigned i = 0; i < [kids count]; i++)
746 dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
750 static void dumpFrameScrollPosition(WebFrame *f)
752 NSPoint scrollPosition = [[[[f frameView] documentView] superview] bounds].origin;
753 if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
754 if ([f parentFrame] != nil)
755 printf("frame '%s' ", [[f name] UTF8String]);
756 printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
759 if (gLayoutTestController->dumpChildFrameScrollPositions()) {
760 NSArray *kids = [f childFrames];
762 for (unsigned i = 0; i < [kids count]; i++)
763 dumpFrameScrollPosition([kids objectAtIndex:i]);
767 static NSString *dumpFramesAsText(WebFrame *frame)
769 DOMDocument *document = [frame DOMDocument];
770 DOMElement *documentElement = [document documentElement];
772 if (!documentElement)
775 NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
777 // Add header for all but the main frame.
778 if ([frame parentFrame])
779 result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
781 [result appendFormat:@"%@\n", [documentElement innerText]];
783 if (gLayoutTestController->dumpChildFramesAsText()) {
784 NSArray *kids = [frame childFrames];
786 for (unsigned i = 0; i < [kids count]; i++)
787 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
794 static NSData *dumpFrameAsPDF(WebFrame *frame)
799 // Sadly we have to dump to a file and then read from that file again
800 // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
801 // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
802 // The goal of this function is to test "real" printing across multiple pages.
803 // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
804 NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
806 NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
807 [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
808 [printInfoDict setObject:path forKey:NSPrintSavePath];
810 NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
811 [printInfo setHorizontalPagination:NSAutoPagination];
812 [printInfo setVerticalPagination:NSAutoPagination];
813 [printInfo setVerticallyCentered:NO];
815 NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
816 [printOperation setShowPanels:NO];
817 [printOperation runOperation];
821 NSData *pdfData = [NSData dataWithContentsOfFile:path];
822 [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
827 static void convertMIMEType(NSMutableString *mimeType)
829 #ifdef BUILDING_ON_LEOPARD
830 // Workaround for <rdar://problem/5539824> on Leopard
831 if ([mimeType isEqualToString:@"text/xml"])
832 [mimeType setString:@"application/xml"];
834 // Workaround for <rdar://problem/6234318> with Dashcode 2.0
835 if ([mimeType isEqualToString:@"application/x-javascript"])
836 [mimeType setString:@"text/javascript"];
839 static void convertWebResourceDataToString(NSMutableDictionary *resource)
841 NSMutableString *mimeType = [resource objectForKey:@"WebResourceMIMEType"];
842 convertMIMEType(mimeType);
844 if ([mimeType hasPrefix:@"text/"] || [[WebHTMLRepresentation supportedNonImageMIMETypes] containsObject:mimeType]) {
845 NSString *textEncodingName = [resource objectForKey:@"WebResourceTextEncodingName"];
846 NSStringEncoding stringEncoding;
847 if ([textEncodingName length] > 0)
848 stringEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)textEncodingName));
850 stringEncoding = NSUTF8StringEncoding;
852 NSData *data = [resource objectForKey:@"WebResourceData"];
853 NSString *dataAsString = [[NSString alloc] initWithData:data encoding:stringEncoding];
855 [resource setObject:dataAsString forKey:@"WebResourceData"];
856 [dataAsString release];
860 static void normalizeHTTPResponseHeaderFields(NSMutableDictionary *fields)
863 if ([fields objectForKey:@"Date"])
864 [fields setObject:@"Sun, 16 Nov 2008 17:00:00 GMT" forKey:@"Date"];
865 if ([fields objectForKey:@"Last-Modified"])
866 [fields setObject:@"Sun, 16 Nov 2008 16:55:00 GMT" forKey:@"Last-Modified"];
867 if ([fields objectForKey:@"Etag"])
868 [fields setObject:@"\"301925-21-45c7d72d3e780\"" forKey:@"Etag"];
869 if ([fields objectForKey:@"Server"])
870 [fields setObject:@"Apache/2.2.9 (Unix) mod_ssl/2.2.9 OpenSSL/0.9.7l PHP/5.2.6" forKey:@"Server"];
873 if ([fields objectForKey:@"Connection"])
874 [fields removeObjectForKey:@"Connection"];
875 if ([fields objectForKey:@"Keep-Alive"])
876 [fields removeObjectForKey:@"Keep-Alive"];
879 static void normalizeWebResourceURL(NSMutableString *webResourceURL)
881 static int fileUrlLength = [(NSString *)@"file://" length];
882 NSRange layoutTestsWebArchivePathRange = [webResourceURL rangeOfString:@"/LayoutTests/" options:NSBackwardsSearch];
883 if (layoutTestsWebArchivePathRange.location == NSNotFound)
885 NSRange currentWorkingDirectoryRange = NSMakeRange(fileUrlLength, layoutTestsWebArchivePathRange.location - fileUrlLength);
886 [webResourceURL replaceCharactersInRange:currentWorkingDirectoryRange withString:@""];
889 static void convertWebResourceResponseToDictionary(NSMutableDictionary *propertyList)
891 NSURLResponse *response = nil;
892 NSData *responseData = [propertyList objectForKey:@"WebResourceResponse"]; // WebResourceResponseKey in WebResource.m
893 if ([responseData isKindOfClass:[NSData class]]) {
894 // Decode NSURLResponse
895 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:responseData];
896 response = [unarchiver decodeObjectForKey:@"WebResourceResponse"]; // WebResourceResponseKey in WebResource.m
897 [unarchiver finishDecoding];
898 [unarchiver release];
901 NSMutableDictionary *responseDictionary = [[NSMutableDictionary alloc] init];
903 NSMutableString *urlString = [[[response URL] description] mutableCopy];
904 normalizeWebResourceURL(urlString);
905 [responseDictionary setObject:urlString forKey:@"URL"];
908 NSMutableString *mimeTypeString = [[response MIMEType] mutableCopy];
909 convertMIMEType(mimeTypeString);
910 [responseDictionary setObject:mimeTypeString forKey:@"MIMEType"];
911 [mimeTypeString release];
913 NSString *textEncodingName = [response textEncodingName];
914 if (textEncodingName)
915 [responseDictionary setObject:textEncodingName forKey:@"textEncodingName"];
916 [responseDictionary setObject:[NSNumber numberWithLongLong:[response expectedContentLength]] forKey:@"expectedContentLength"];
918 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
919 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
921 NSMutableDictionary *allHeaderFields = [[httpResponse allHeaderFields] mutableCopy];
922 normalizeHTTPResponseHeaderFields(allHeaderFields);
923 [responseDictionary setObject:allHeaderFields forKey:@"allHeaderFields"];
924 [allHeaderFields release];
926 [responseDictionary setObject:[NSNumber numberWithInt:[httpResponse statusCode]] forKey:@"statusCode"];
929 [propertyList setObject:responseDictionary forKey:@"WebResourceResponse"];
930 [responseDictionary release];
933 static NSInteger compareResourceURLs(id resource1, id resource2, void *context)
935 NSString *url1 = [resource1 objectForKey:@"WebResourceURL"];
936 NSString *url2 = [resource2 objectForKey:@"WebResourceURL"];
938 return [url1 compare:url2];
941 static NSString *serializeWebArchiveToXML(WebArchive *webArchive)
943 NSString *errorString;
944 NSMutableDictionary *propertyList = [NSPropertyListSerialization propertyListFromData:[webArchive data]
945 mutabilityOption:NSPropertyListMutableContainersAndLeaves
947 errorDescription:&errorString];
951 NSMutableArray *resources = [NSMutableArray arrayWithCapacity:1];
952 [resources addObject:propertyList];
954 while ([resources count]) {
955 NSMutableDictionary *resourcePropertyList = [resources objectAtIndex:0];
956 [resources removeObjectAtIndex:0];
958 NSMutableDictionary *mainResource = [resourcePropertyList objectForKey:@"WebMainResource"];
959 normalizeWebResourceURL([mainResource objectForKey:@"WebResourceURL"]);
960 convertWebResourceDataToString(mainResource);
962 // Add subframeArchives to list for processing
963 NSMutableArray *subframeArchives = [resourcePropertyList objectForKey:@"WebSubframeArchives"]; // WebSubframeArchivesKey in WebArchive.m
964 if (subframeArchives)
965 [resources addObjectsFromArray:subframeArchives];
967 NSMutableArray *subresources = [resourcePropertyList objectForKey:@"WebSubresources"]; // WebSubresourcesKey in WebArchive.m
968 NSEnumerator *enumerator = [subresources objectEnumerator];
969 NSMutableDictionary *subresourcePropertyList;
970 while ((subresourcePropertyList = [enumerator nextObject])) {
971 normalizeWebResourceURL([subresourcePropertyList objectForKey:@"WebResourceURL"]);
972 convertWebResourceResponseToDictionary(subresourcePropertyList);
973 convertWebResourceDataToString(subresourcePropertyList);
976 // Sort the subresources so they're always in a predictable order for the dump
977 if (NSArray *sortedSubresources = [subresources sortedArrayUsingFunction:compareResourceURLs context:nil])
978 [resourcePropertyList setObject:sortedSubresources forKey:@"WebSubresources"];
981 NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:propertyList
982 format:NSPropertyListXMLFormat_v1_0
983 errorDescription:&errorString];
987 NSMutableString *string = [[[NSMutableString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding] autorelease];
989 // Replace "Apple Computer" with "Apple" in the DTD declaration.
990 NSRange range = [string rangeOfString:@"-//Apple Computer//"];
991 if (range.location != NSNotFound)
992 [string replaceCharactersInRange:range withString:@"-//Apple//"];
997 static void dumpBackForwardListForWebView(WebView *view)
999 printf("\n============== Back Forward List ==============\n");
1000 WebBackForwardList *bfList = [view backForwardList];
1002 // Print out all items in the list after prevTestBFItem, which was from the previous test
1003 // Gather items from the end of the list, the print them out from oldest to newest
1004 NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
1005 for (int i = [bfList forwardListCount]; i > 0; i--) {
1006 WebHistoryItem *item = [bfList itemAtIndex:i];
1007 // something is wrong if the item from the last test is in the forward part of the b/f list
1008 assert(item != prevTestBFItem);
1009 [itemsToPrint addObject:item];
1012 assert([bfList currentItem] != prevTestBFItem);
1013 [itemsToPrint addObject:[bfList currentItem]];
1014 int currentItemIndex = [itemsToPrint count] - 1;
1016 for (int i = -1; i >= -[bfList backListCount]; i--) {
1017 WebHistoryItem *item = [bfList itemAtIndex:i];
1018 if (item == prevTestBFItem)
1020 [itemsToPrint addObject:item];
1023 for (int i = [itemsToPrint count]-1; i >= 0; i--)
1024 dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1026 [itemsToPrint release];
1027 printf("===============================================\n");
1030 static void sizeWebViewForCurrentTest()
1032 // W3C SVG tests expect to be 480x360
1033 bool isSVGW3CTest = (gLayoutTestController->testPathOrURL().find("svg/W3C-SVG-1.1") != string::npos);
1035 [[mainFrame webView] setFrameSize:NSMakeSize(480, 360)];
1037 [[mainFrame webView] setFrameSize:NSMakeSize(LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight)];
1040 static const char *methodNameStringForFailedTest()
1042 const char *errorMessage;
1043 if (gLayoutTestController->dumpAsText())
1044 errorMessage = "[documentElement innerText]";
1045 else if (gLayoutTestController->dumpDOMAsWebArchive())
1046 errorMessage = "[[mainFrame DOMDocument] webArchive]";
1047 else if (gLayoutTestController->dumpSourceAsWebArchive())
1048 errorMessage = "[[mainFrame dataSource] webArchive]";
1050 errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1052 return errorMessage;
1055 static void dumpBackForwardListForAllWindows()
1057 CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1058 unsigned count = CFArrayGetCount(openWindows);
1059 for (unsigned i = 0; i < count; i++) {
1060 NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1061 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1062 dumpBackForwardListForWebView(webView);
1066 static void invalidateAnyPreviousWaitToDumpWatchdog()
1068 if (waitToDumpWatchdog) {
1069 CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1070 CFRelease(waitToDumpWatchdog);
1071 waitToDumpWatchdog = 0;
1077 invalidateAnyPreviousWaitToDumpWatchdog();
1079 bool dumpAsText = gLayoutTestController->dumpAsText();
1081 NSString *resultString = nil;
1082 NSData *resultData = nil;
1083 NSString *resultMimeType = @"text/plain";
1085 dumpAsText |= [[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"];
1086 gLayoutTestController->setDumpAsText(dumpAsText);
1087 if (gLayoutTestController->dumpAsText()) {
1088 resultString = dumpFramesAsText(mainFrame);
1089 } else if (gLayoutTestController->dumpAsPDF()) {
1090 resultData = dumpFrameAsPDF(mainFrame);
1091 resultMimeType = @"application/pdf";
1092 } else if (gLayoutTestController->dumpDOMAsWebArchive()) {
1093 WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1094 resultString = serializeWebArchiveToXML(webArchive);
1095 resultMimeType = @"application/x-webarchive";
1096 } else if (gLayoutTestController->dumpSourceAsWebArchive()) {
1097 WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1098 resultString = serializeWebArchiveToXML(webArchive);
1099 resultMimeType = @"application/x-webarchive";
1101 sizeWebViewForCurrentTest();
1102 resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gLayoutTestController->isPrinting()];
1105 if (resultString && !resultData)
1106 resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1108 printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1111 fwrite([resultData bytes], 1, [resultData length], stdout);
1113 if (!gLayoutTestController->dumpAsText() && !gLayoutTestController->dumpDOMAsWebArchive() && !gLayoutTestController->dumpSourceAsWebArchive())
1114 dumpFrameScrollPosition(mainFrame);
1116 if (gLayoutTestController->dumpBackForwardList())
1117 dumpBackForwardListForAllWindows();
1119 printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1121 // Stop the watchdog thread before we leave this test to make sure it doesn't
1122 // fire in between tests causing the next test to fail.
1123 // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1124 invalidateAnyPreviousWaitToDumpWatchdog();
1126 if (printSeparators) {
1127 puts("#EOF"); // terminate the content block
1128 fputs("#EOF\n", stderr);
1132 if (dumpPixels && gLayoutTestController->generatePixelResults())
1133 // FIXME: when isPrinting is set, dump the image with page separators.
1134 dumpWebViewAsPixelsAndCompareWithExpected(gLayoutTestController->expectedPixelHash());
1136 puts("#EOF"); // terminate the (possibly empty) pixels block
1144 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1146 return strstr(pathOrURL, "loading/");
1149 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1151 return strstr(pathOrURL, "globalhistory/");
1154 static bool shouldOpenWebInspector(const char* pathOrURL)
1156 return strstr(pathOrURL, "inspector/");
1159 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1161 return shouldOpenWebInspector(pathOrURL) || strstr(pathOrURL, "inspector-enabled/");
1164 static void resetWebViewToConsistentStateBeforeTesting()
1166 WebView *webView = [mainFrame webView];
1167 [webView setEditable:NO];
1168 [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1169 [webView makeTextStandardSize:nil];
1170 [webView resetPageZoom:nil];
1171 [webView setTabKeyCyclesThroughElements:YES];
1172 [webView setPolicyDelegate:nil];
1173 [policyDelegate setPermissive:NO];
1174 [policyDelegate setControllerToNotifyDone:0];
1175 [frameLoadDelegate resetToConsistentState];
1176 [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1177 [webView _clearMainFrameName];
1178 [[webView undoManager] removeAllActions];
1179 [WebView _removeAllUserContentFromGroup:[webView groupName]];
1180 [[webView window] setAutodisplay:NO];
1182 resetDefaultsToConsistentValues();
1184 [[mainFrame webView] setSmartInsertDeleteEnabled:YES];
1185 [[[mainFrame webView] inspector] setJavaScriptProfilingEnabled:NO];
1187 [WebView _setUsesTestModeFocusRingColor:YES];
1188 [WebView _resetOriginAccessWhitelists];
1190 [[MockGeolocationProvider shared] stopTimer];
1192 // Clear the contents of the general pasteboard
1193 [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1196 static void runTest(const string& testPathOrURL)
1198 ASSERT(!testPathOrURL.empty());
1200 // Look for "'" as a separator between the path or URL, and the pixel dump hash that follows.
1201 string pathOrURL(testPathOrURL);
1202 string expectedPixelHash;
1204 size_t separatorPos = pathOrURL.find("'");
1205 if (separatorPos != string::npos) {
1206 pathOrURL = string(testPathOrURL, 0, separatorPos);
1207 expectedPixelHash = string(testPathOrURL, separatorPos + 1);
1210 NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1211 if (!pathOrURLString) {
1212 fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1217 if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"])
1218 url = [NSURL URLWithString:pathOrURLString];
1220 url = [NSURL fileURLWithPath:pathOrURLString];
1222 fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1226 const string testURL([[url absoluteString] UTF8String]);
1228 resetWebViewToConsistentStateBeforeTesting();
1230 gLayoutTestController = LayoutTestController::create(testURL, expectedPixelHash);
1231 topLoadingFrame = nil;
1232 ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1233 releaseAndZero(&draggingInfo);
1236 gLayoutTestController->setIconDatabaseEnabled(false);
1239 CFSetRemoveAllValues(disallowedURLs);
1240 if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1241 gLayoutTestController->setDumpFrameLoadCallbacks(true);
1243 if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1244 [[mainFrame webView] setHistoryDelegate:historyDelegate];
1246 [[mainFrame webView] setHistoryDelegate:nil];
1248 if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1249 gLayoutTestController->setDeveloperExtrasEnabled(true);
1250 if (shouldOpenWebInspector(pathOrURL.c_str()))
1251 gLayoutTestController->showWebInspector();
1254 if ([WebHistory optionalSharedHistory])
1255 [WebHistory setOptionalSharedHistory:nil];
1256 lastMousePosition = NSZeroPoint;
1257 lastClickPosition = NSZeroPoint;
1259 [prevTestBFItem release];
1260 prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
1262 WorkQueue::shared()->clear();
1263 WorkQueue::shared()->setFrozen(false);
1265 bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
1266 if (ignoreWebCoreNodeLeaks)
1267 [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
1269 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1270 [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
1274 pool = [[NSAutoreleasePool alloc] init];
1275 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1279 pool = [[NSAutoreleasePool alloc] init];
1280 [EventSendingController clearSavedEvents];
1281 [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
1283 WorkQueue::shared()->clear();
1285 if (gLayoutTestController->closeRemainingWindowsWhenComplete()) {
1286 NSArray* array = [DumpRenderTreeWindow openWindows];
1288 unsigned count = [array count];
1289 for (unsigned i = 0; i < count; i++) {
1290 NSWindow *window = [array objectAtIndex:i];
1292 // Don't try to close the main window
1293 if (window == [[mainFrame webView] window])
1296 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1303 // If developer extras enabled Web Inspector may have been open by the test.
1304 if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1305 gLayoutTestController->closeWebInspector();
1306 gLayoutTestController->setDeveloperExtrasEnabled(false);
1309 resetWebViewToConsistentStateBeforeTesting();
1311 [mainFrame loadHTMLString:@"<html></html>" baseURL:[NSURL URLWithString:@"about:blank"]];
1312 [mainFrame stopLoading];
1316 // We should only have our main window left open when we're done
1317 ASSERT(CFArrayGetCount(openWindowsRef) == 1);
1318 ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
1320 gLayoutTestController.clear();
1322 if (ignoreWebCoreNodeLeaks)
1323 [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
1326 void displayWebView()
1328 NSView *webView = [mainFrame webView];
1330 [webView lockFocus];
1331 [[[NSColor blackColor] colorWithAlphaComponent:0.66] set];
1332 NSRectFillUsingOperation([webView frame], NSCompositeSourceOver);
1333 [webView unlockFocus];
1336 @implementation DumpRenderTreeEvent
1338 + (NSPoint)mouseLocation
1340 return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
1345 @implementation DumpRenderTreeApplication
1349 // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running