Add +[WebView _allowsRoundingHacks]
[WebKit-https.git] / Source / WebKit / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  * Copyright (C) 2010 Igalia S.L
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
33
34 #import "DOMCSSStyleDeclarationInternal.h"
35 #import "DOMNodeInternal.h"
36 #import "DOMRangeInternal.h"
37 #import "WebApplicationCache.h"
38 #import "WebBackForwardListInternal.h"
39 #import "WebBaseNetscapePluginView.h"
40 #import "WebCache.h"
41 #import "WebChromeClient.h"
42 #import "WebContextMenuClient.h"
43 #import "WebDOMOperationsPrivate.h"
44 #import "WebDataSourceInternal.h"
45 #import "WebDatabaseManagerInternal.h"
46 #import "WebDefaultEditingDelegate.h"
47 #import "WebDefaultPolicyDelegate.h"
48 #import "WebDefaultUIDelegate.h"
49 #import "WebDelegateImplementationCaching.h"
50 #import "WebDeviceOrientationClient.h"
51 #import "WebDeviceOrientationProvider.h"
52 #import "WebDocument.h"
53 #import "WebDocumentInternal.h"
54 #import "WebDownload.h"
55 #import "WebDownloadInternal.h"
56 #import "WebDragClient.h"
57 #import "WebDynamicScrollBarsViewInternal.h"
58 #import "WebEditingDelegate.h"
59 #import "WebEditorClient.h"
60 #import "WebFormDelegatePrivate.h"
61 #import "WebFrameInternal.h"
62 #import "WebFrameViewInternal.h"
63 #import "WebFullScreenController.h"
64 #import "WebGeolocationClient.h"
65 #import "WebGeolocationPositionInternal.h"
66 #import "WebHTMLRepresentation.h"
67 #import "WebHTMLViewInternal.h"
68 #import "WebHistoryItemInternal.h"
69 #import "WebIconDatabaseInternal.h"
70 #import "WebInspector.h"
71 #import "WebInspectorClient.h"
72 #import "WebKitErrors.h"
73 #import "WebKitLogging.h"
74 #import "WebKitNSStringExtras.h"
75 #import "WebKitStatisticsPrivate.h"
76 #import "WebKitSystemBits.h"
77 #import "WebKitVersionChecks.h"
78 #import "WebLocalizableStrings.h"
79 #import "WebNSDataExtras.h"
80 #import "WebNSDataExtrasPrivate.h"
81 #import "WebNSDictionaryExtras.h"
82 #import "WebNSEventExtras.h"
83 #import "WebNSObjectExtras.h"
84 #import "WebNSPasteboardExtras.h"
85 #import "WebNSPrintOperationExtras.h"
86 #import "WebNSURLExtras.h"
87 #import "WebNSURLRequestExtras.h"
88 #import "WebNSViewExtras.h"
89 #import "WebNodeHighlight.h"
90 #import "WebPDFView.h"
91 #import "WebPanelAuthenticationHandler.h"
92 #import "WebPlatformStrategies.h"
93 #import "WebPluginDatabase.h"
94 #import "WebPluginHalterClient.h"
95 #import "WebPolicyDelegate.h"
96 #import "WebPreferenceKeysPrivate.h"
97 #import "WebPreferencesPrivate.h"
98 #import "WebScriptDebugDelegate.h"
99 #import "WebScriptWorldInternal.h"
100 #import "WebStorageManagerInternal.h"
101 #import "WebSystemInterface.h"
102 #import "WebTextCompletionController.h"
103 #import "WebTextIterator.h"
104 #import "WebUIDelegate.h"
105 #import "WebUIDelegatePrivate.h"
106 #import <CoreFoundation/CFSet.h>
107 #import <Foundation/NSURLConnection.h>
108 #import <JavaScriptCore/APICast.h>
109 #import <JavaScriptCore/JSValueRef.h>
110 #import <WebCore/AbstractDatabase.h>
111 #import <WebCore/ApplicationCacheStorage.h>
112 #import <WebCore/BackForwardListImpl.h>
113 #import <WebCore/MemoryCache.h>
114 #import <WebCore/ColorMac.h>
115 #import <WebCore/CSSComputedStyleDeclaration.h>
116 #import <WebCore/Cursor.h>
117 #import <WebCore/Document.h>
118 #import <WebCore/DocumentLoader.h>
119 #import <WebCore/DragController.h>
120 #import <WebCore/DragData.h>
121 #import <WebCore/Editor.h>
122 #import <WebCore/EventHandler.h>
123 #import <WebCore/ExceptionHandlers.h>
124 #import <WebCore/FocusController.h>
125 #import <WebCore/Frame.h>
126 #import <WebCore/FrameLoader.h>
127 #import <WebCore/FrameSelection.h>
128 #import <WebCore/FrameTree.h>
129 #import <WebCore/FrameView.h>
130 #import <WebCore/GCController.h>
131 #import <WebCore/HTMLMediaElement.h>
132 #import <WebCore/HTMLNames.h>
133 #import <WebCore/HistoryItem.h>
134 #import <WebCore/IconDatabase.h>
135 #import <WebCore/JSCSSStyleDeclaration.h>
136 #import <WebCore/JSDocument.h>
137 #import <WebCore/JSElement.h>
138 #import <WebCore/JSNodeList.h>
139 #import <WebCore/Logging.h>
140 #import <WebCore/MemoryPressureHandler.h>
141 #import <WebCore/MIMETypeRegistry.h>
142 #import <WebCore/NodeList.h>
143 #import <WebCore/Page.h>
144 #import <WebCore/PageCache.h>
145 #import <WebCore/PageGroup.h>
146 #import <WebCore/PlatformMouseEvent.h>
147 #import <WebCore/ProgressTracker.h>
148 #import <WebCore/RenderView.h>
149 #import <WebCore/RenderWidget.h>
150 #import <WebCore/ResourceHandle.h>
151 #import <WebCore/ResourceLoadScheduler.h>
152 #import <WebCore/ResourceRequest.h>
153 #import <WebCore/RuntimeApplicationChecks.h>
154 #import <WebCore/SchemeRegistry.h>
155 #import <WebCore/ScriptController.h>
156 #import <WebCore/ScriptValue.h>
157 #import <WebCore/SecurityOrigin.h>
158 #import <WebCore/Settings.h>
159 #import <WebCore/TextResourceDecoder.h>
160 #import <WebCore/ThreadCheck.h>
161 #import <WebCore/WebCoreObjCExtras.h>
162 #import <WebCore/WebCoreView.h>
163 #import <WebCore/WebVideoFullscreenController.h>
164 #import <WebCore/Widget.h>
165 #import <WebKit/DOM.h>
166 #import <WebKit/DOMExtensions.h>
167 #import <WebKit/DOMPrivate.h>
168 #import <WebKitSystemInterface.h>
169 #import <mach-o/dyld.h>
170 #import <objc/objc-auto.h>
171 #import <objc/objc-runtime.h>
172 #import <runtime/ArrayPrototype.h>
173 #import <runtime/DateInstance.h>
174 #import <runtime/InitializeThreading.h>
175 #import <runtime/JSLock.h>
176 #import <runtime/JSValue.h>
177 #import <wtf/Assertions.h>
178 #import <wtf/HashTraits.h>
179 #import <wtf/RefCountedLeakCounter.h>
180 #import <wtf/RefPtr.h>
181 #import <wtf/StdLibExtras.h>
182 #import <wtf/Threading.h>
183
184 #if ENABLE(DASHBOARD_SUPPORT)
185 #import <WebKit/WebDashboardRegion.h>
186 #endif
187
188 #if ENABLE(CLIENT_BASED_GEOLOCATION)
189 #import <WebCore/GeolocationController.h>
190 #import <WebCore/GeolocationError.h>
191 #endif
192
193 #if ENABLE(GLIB_SUPPORT)
194 #import <glib.h>
195 #endif
196
197 @interface NSSpellChecker (WebNSSpellCheckerDetails)
198 - (void)_preflightChosenSpellServer;
199 @end
200
201 @interface NSView (WebNSViewDetails)
202 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
203 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
204 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
205 @end
206
207 @interface NSWindow (WebNSWindowDetails) 
208 - (id)_oldFirstResponderBeforeBecoming;
209 - (void)_enableScreenUpdatesIfNeeded;
210 - (BOOL)_wrapsCarbonWindow;
211 @end
212
213 using namespace WebCore;
214 using namespace JSC;
215
216 #if defined(__ppc__) || defined(__ppc64__)
217 #define PROCESSOR "PPC"
218 #elif defined(__i386__) || defined(__x86_64__)
219 #define PROCESSOR "Intel"
220 #else
221 #error Unknown architecture
222 #endif
223
224 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
225 macro(alignCenter) \
226 macro(alignJustified) \
227 macro(alignLeft) \
228 macro(alignRight) \
229 macro(capitalizeWord) \
230 macro(centerSelectionInVisibleArea) \
231 macro(changeAttributes) \
232 macro(changeBaseWritingDirection) \
233 macro(changeBaseWritingDirectionToLTR) \
234 macro(changeBaseWritingDirectionToRTL) \
235 macro(changeColor) \
236 macro(changeDocumentBackgroundColor) \
237 macro(changeFont) \
238 macro(changeSpelling) \
239 macro(checkSpelling) \
240 macro(complete) \
241 macro(copy) \
242 macro(copyFont) \
243 macro(cut) \
244 macro(delete) \
245 macro(deleteBackward) \
246 macro(deleteBackwardByDecomposingPreviousCharacter) \
247 macro(deleteForward) \
248 macro(deleteToBeginningOfLine) \
249 macro(deleteToBeginningOfParagraph) \
250 macro(deleteToEndOfLine) \
251 macro(deleteToEndOfParagraph) \
252 macro(deleteToMark) \
253 macro(deleteWordBackward) \
254 macro(deleteWordForward) \
255 macro(ignoreSpelling) \
256 macro(indent) \
257 macro(insertBacktab) \
258 macro(insertLineBreak) \
259 macro(insertNewline) \
260 macro(insertNewlineIgnoringFieldEditor) \
261 macro(insertParagraphSeparator) \
262 macro(insertTab) \
263 macro(insertTabIgnoringFieldEditor) \
264 macro(lowercaseWord) \
265 macro(makeBaseWritingDirectionLeftToRight) \
266 macro(makeBaseWritingDirectionRightToLeft) \
267 macro(makeTextWritingDirectionLeftToRight) \
268 macro(makeTextWritingDirectionNatural) \
269 macro(makeTextWritingDirectionRightToLeft) \
270 macro(moveBackward) \
271 macro(moveBackwardAndModifySelection) \
272 macro(moveDown) \
273 macro(moveDownAndModifySelection) \
274 macro(moveForward) \
275 macro(moveForwardAndModifySelection) \
276 macro(moveLeft) \
277 macro(moveLeftAndModifySelection) \
278 macro(moveParagraphBackwardAndModifySelection) \
279 macro(moveParagraphForwardAndModifySelection) \
280 macro(moveRight) \
281 macro(moveRightAndModifySelection) \
282 macro(moveToBeginningOfDocument) \
283 macro(moveToBeginningOfDocumentAndModifySelection) \
284 macro(moveToBeginningOfLine) \
285 macro(moveToBeginningOfLineAndModifySelection) \
286 macro(moveToBeginningOfParagraph) \
287 macro(moveToBeginningOfParagraphAndModifySelection) \
288 macro(moveToBeginningOfSentence) \
289 macro(moveToBeginningOfSentenceAndModifySelection) \
290 macro(moveToEndOfDocument) \
291 macro(moveToEndOfDocumentAndModifySelection) \
292 macro(moveToEndOfLine) \
293 macro(moveToEndOfLineAndModifySelection) \
294 macro(moveToEndOfParagraph) \
295 macro(moveToEndOfParagraphAndModifySelection) \
296 macro(moveToEndOfSentence) \
297 macro(moveToEndOfSentenceAndModifySelection) \
298 macro(moveToLeftEndOfLine) \
299 macro(moveToLeftEndOfLineAndModifySelection) \
300 macro(moveToRightEndOfLine) \
301 macro(moveToRightEndOfLineAndModifySelection) \
302 macro(moveUp) \
303 macro(moveUpAndModifySelection) \
304 macro(moveWordBackward) \
305 macro(moveWordBackwardAndModifySelection) \
306 macro(moveWordForward) \
307 macro(moveWordForwardAndModifySelection) \
308 macro(moveWordLeft) \
309 macro(moveWordLeftAndModifySelection) \
310 macro(moveWordRight) \
311 macro(moveWordRightAndModifySelection) \
312 macro(outdent) \
313 macro(orderFrontSubstitutionsPanel) \
314 macro(pageDown) \
315 macro(pageDownAndModifySelection) \
316 macro(pageUp) \
317 macro(pageUpAndModifySelection) \
318 macro(paste) \
319 macro(pasteAsPlainText) \
320 macro(pasteAsRichText) \
321 macro(pasteFont) \
322 macro(performFindPanelAction) \
323 macro(scrollLineDown) \
324 macro(scrollLineUp) \
325 macro(scrollPageDown) \
326 macro(scrollPageUp) \
327 macro(scrollToBeginningOfDocument) \
328 macro(scrollToEndOfDocument) \
329 macro(selectAll) \
330 macro(selectLine) \
331 macro(selectParagraph) \
332 macro(selectSentence) \
333 macro(selectToMark) \
334 macro(selectWord) \
335 macro(setMark) \
336 macro(showGuessPanel) \
337 macro(startSpeaking) \
338 macro(stopSpeaking) \
339 macro(subscript) \
340 macro(superscript) \
341 macro(swapWithMark) \
342 macro(takeFindStringFromSelection) \
343 macro(toggleBaseWritingDirection) \
344 macro(transpose) \
345 macro(underline) \
346 macro(unscript) \
347 macro(uppercaseWord) \
348 macro(yank) \
349 macro(yankAndSelect) \
350
351 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
352 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
353
354 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
355 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
356 #define UniversalAccessDomain CFSTR("com.apple.universalaccess")
357
358 static BOOL s_didSetCacheModel;
359 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
360
361 #ifndef NDEBUG
362 static const char webViewIsOpen[] = "At least one WebView is still open.";
363 #endif
364
365 @interface NSObject (WebValidateWithoutDelegate)
366 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
367 @end
368
369 @interface _WebSafeForwarder : NSObject
370 {
371     id target; // Non-retained. Don't retain delegates.
372     id defaultTarget;
373     BOOL catchExceptions;
374 }
375 - (id)initWithTarget:(id)target defaultTarget:(id)defaultTarget catchExceptions:(BOOL)catchExceptions;
376 @end
377
378 @interface WebView (WebFileInternal)
379 - (BOOL)_isLoading;
380 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
381 - (WebFrame *)_focusedFrame;
382 + (void)_preflightSpellChecker;
383 - (BOOL)_continuousCheckingAllowed;
384 - (NSResponder *)_responderForResponderOperations;
385 #if USE(ACCELERATED_COMPOSITING)
386 - (void)_clearLayerSyncLoopObserver;
387 #endif
388 #if ENABLE(GLIB_SUPPORT)
389 - (void)_clearGlibLoopObserver;
390 #endif
391 @end
392
393 static void patchMailRemoveAttributesMethod();
394
395 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
396 NSString *WebElementFrameKey =              @"WebElementFrame";
397 NSString *WebElementImageKey =              @"WebElementImage";
398 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
399 NSString *WebElementImageRectKey =          @"WebElementImageRect";
400 NSString *WebElementImageURLKey =           @"WebElementImageURL";
401 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
402 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
403 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
404 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
405 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
406 NSString *WebElementMediaURLKey =           @"WebElementMediaURL";
407 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
408 NSString *WebElementTitleKey =              @"WebElementTitle";
409 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
410 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
411 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
412
413 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
414 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
415 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
416
417 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
418 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
419 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
420 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
421 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
422
423 enum { WebViewVersion = 4 };
424
425 #define timedLayoutSize 4096
426
427 static NSMutableSet *schemesWithRepresentationsSet;
428
429 NSString *_WebCanGoBackKey =            @"canGoBack";
430 NSString *_WebCanGoForwardKey =         @"canGoForward";
431 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
432 NSString *_WebIsLoadingKey =            @"isLoading";
433 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
434 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
435 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
436 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
437
438 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
439
440 @interface WebProgressItem : NSObject
441 {
442 @public
443     long long bytesReceived;
444     long long estimatedLength;
445 }
446 @end
447
448 @implementation WebProgressItem
449 @end
450
451 static BOOL continuousSpellCheckingEnabled;
452 static BOOL grammarCheckingEnabled;
453 #ifndef BUILDING_ON_LEOPARD
454 static BOOL automaticQuoteSubstitutionEnabled;
455 static BOOL automaticLinkDetectionEnabled;
456 static BOOL automaticDashSubstitutionEnabled;
457 static BOOL automaticTextReplacementEnabled;
458 static BOOL automaticSpellingCorrectionEnabled;
459 #endif
460
461 @implementation WebView (AllWebViews)
462
463 static CFSetCallBacks NonRetainingSetCallbacks = {
464     0,
465     NULL,
466     NULL,
467     CFCopyDescription,
468     CFEqual,
469     CFHash
470 };
471
472 static CFMutableSetRef allWebViewsSet;
473
474 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
475 {
476     if (!allWebViewsSet)
477         return;
478
479     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
480 }
481
482 - (void)_removeFromAllWebViewsSet
483 {
484     if (allWebViewsSet)
485         CFSetRemoveValue(allWebViewsSet, self);
486 }
487
488 - (void)_addToAllWebViewsSet
489 {
490     if (!allWebViewsSet)
491         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
492
493     CFSetSetValue(allWebViewsSet, self);
494 }
495
496 @end
497
498 @implementation WebView (WebPrivate)
499
500 static inline int callGestalt(OSType selector)
501 {
502     SInt32 value = 0;
503     Gestalt(selector, &value);
504     return value;
505 }
506
507 // Uses underscores instead of dots because if "4." ever appears in a user agent string, old DHTML libraries treat it as Netscape 4.
508 static NSString *createMacOSXVersionString()
509 {
510     // Can't use -[NSProcessInfo operatingSystemVersionString] because it has too much stuff we don't want.
511     int major = callGestalt(gestaltSystemVersionMajor);
512     ASSERT(major);
513
514     int minor = callGestalt(gestaltSystemVersionMinor);
515     int bugFix = callGestalt(gestaltSystemVersionBugFix);
516     if (bugFix)
517         return [[NSString alloc] initWithFormat:@"%d_%d_%d", major, minor, bugFix];
518     if (minor)
519         return [[NSString alloc] initWithFormat:@"%d_%d", major, minor];
520     return [[NSString alloc] initWithFormat:@"%d", major];
521 }
522
523 static NSString *createUserVisibleWebKitVersionString()
524 {
525     // If the version is 4 digits long or longer, then the first digit represents
526     // the version of the OS. Our user agent string should not include this first digit,
527     // so strip it off and report the rest as the version. <rdar://problem/4997547>
528     NSString *fullVersion = [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
529     NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
530     if (nonDigitRange.location == NSNotFound && [fullVersion length] >= 4)
531         return [[fullVersion substringFromIndex:1] copy];
532     if (nonDigitRange.location != NSNotFound && nonDigitRange.location >= 4)
533         return [[fullVersion substringFromIndex:1] copy];
534     return [fullVersion copy];
535 }
536
537 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
538 {
539     // Note: Do *not* move the initialization of osVersion nor webKitVersion into the declaration.
540     // Garbage collection won't correctly mark the global variable in that case <rdar://problem/5733674>.
541     static NSString *osVersion;
542     static NSString *webKitVersion;
543     if (!osVersion)
544         osVersion = createMacOSXVersionString();
545     if (!webKitVersion)
546         webKitVersion = createUserVisibleWebKitVersionString();
547     if ([applicationName length])
548         return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X %@) AppleWebKit/%@ (KHTML, like Gecko) %@", osVersion, webKitVersion, applicationName];
549     return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X %@) AppleWebKit/%@ (KHTML, like Gecko)", osVersion, webKitVersion];
550 }
551
552 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
553 {
554     if (!exception || !context)
555         return;
556
557     JSLock lock(SilenceAssertionsOnly);
558     JSC::ExecState* execState = toJS(context);
559
560     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
561     if (!toJSDOMWindow(execState->lexicalGlobalObject()))
562         return;
563
564     reportException(execState, toJS(execState, exception));
565 }
566
567 static void WebKitInitializeApplicationCachePathIfNecessary()
568 {
569 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
570     static BOOL initialized = NO;
571     if (initialized)
572         return;
573
574     NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
575     if (!appName)
576         appName = [[NSProcessInfo processInfo] processName];
577     
578     ASSERT(appName);
579
580     NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
581
582     cacheStorage().setCacheDirectory(cacheDir);
583     initialized = YES;
584 #endif
585 }
586
587 static bool runningLeopardMail()
588 {
589 #ifdef BUILDING_ON_LEOPARD
590     return applicationIsAppleMail();
591 #endif
592     return NO;
593 }
594
595 static bool runningTigerMail()
596 {
597     return NO;    
598 }
599
600 static bool coreVideoHas7228836Fix()
601 {
602 #ifdef BUILDING_ON_LEOPARD
603     NSBundle* coreVideoFrameworkBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/CoreVideo.framework"];
604     double version = [[coreVideoFrameworkBundle objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey] doubleValue];
605     return (version >= 48);
606 #endif
607     return true;
608 }
609
610 static bool shouldEnableLoadDeferring()
611 {
612     return !applicationIsAdobeInstaller();
613 }
614
615 - (void)_dispatchPendingLoadRequests
616 {
617     resourceLoadScheduler()->servePendingRequests();
618 }
619
620 - (void)_registerDraggedTypes
621 {
622     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
623     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
624     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
625     [types addObjectsFromArray:URLTypes];
626     [self registerForDraggedTypes:[types allObjects]];
627     [types release];
628 }
629
630 - (BOOL)_usesDocumentViews
631 {
632     return _private->usesDocumentViews;
633 }
634
635 static NSString *leakMailQuirksUserScriptContents()
636 {
637     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"MailQuirksUserScript" ofType:@"js"];
638     NSStringEncoding encoding;
639     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
640 }
641
642 - (void)_injectMailQuirksScript
643 {
644     static NSString *mailQuirksScriptContents = leakMailQuirksUserScriptContents();
645     core(self)->group().addUserScriptToWorld(core([WebScriptWorld world]),
646         mailQuirksScriptContents, KURL(), nullptr, nullptr, InjectAtDocumentEnd, InjectInAllFrames);
647 }
648
649 static bool needsOutlookQuirksScript()
650 {
651     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
652         && applicationIsMicrosoftOutlook();
653     return isOutlookNeedingQuirksScript;
654 }
655
656 static NSString *leakOutlookQuirksUserScriptContents()
657 {
658     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
659     NSStringEncoding encoding;
660     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
661 }
662
663 -(void)_injectOutlookQuirksScript
664 {
665     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
666     core(self)->group().addUserScriptToWorld(core([WebScriptWorld world]),
667         outlookQuirksScriptContents, KURL(), nullptr, nullptr, InjectAtDocumentEnd, InjectInAllFrames);
668 }
669
670 static bool needsSolarWalkQuirksScript()
671 {
672     static bool isSolarWalkNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
673     && applicationIsSolarWalk();
674     return isSolarWalkNeedingQuirksScript;
675 }
676
677 static NSString *leakSolarWalkQuirksUserScriptContents()
678 {
679     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"SolarWalkQuirksUserScript" ofType:@"js"];
680     NSStringEncoding encoding;
681     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
682 }
683
684 -(void)_injectSolarWalkQuirksScript
685 {
686     static NSString *solarWalkQuirksScriptContents = leakSolarWalkQuirksUserScriptContents();
687     core(self)->group().addUserScriptToWorld(core([WebScriptWorld world]),
688         solarWalkQuirksScriptContents, KURL(), nullptr, nullptr, InjectAtDocumentEnd, InjectInAllFrames);
689 }
690
691 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
692 {
693     WebCoreThreadViolationCheckRoundTwo();
694
695 #ifndef NDEBUG
696     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
697 #endif
698     
699     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
700     [standardPreferences willAddToWebView];
701
702     _private->preferences = [standardPreferences retain];
703     _private->catchesDelegateExceptions = YES;
704     _private->mainFrameDocumentReady = NO;
705     _private->drawsBackground = YES;
706     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
707     _private->usesDocumentViews = usesDocumentViews;
708     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
709
710     WebFrameView *frameView = nil;
711     if (_private->usesDocumentViews) {
712         NSRect f = [self frame];
713         frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
714         [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
715         [self addSubview:frameView];
716         [frameView release];
717     }
718
719     static bool didOneTimeInitialization = false;
720     if (!didOneTimeInitialization) {
721         WebKitInitializeLoggingChannelsIfNecessary();
722         WebCore::InitializeLoggingChannelsIfNecessary();
723         [WebHistoryItem initWindowWatcherIfNecessary];
724 #if ENABLE(DATABASE)
725         WebKitInitializeDatabasesIfNecessary();
726 #endif
727
728 #if ENABLE(DOM_STORAGE)
729         WebKitInitializeStorageIfNecessary();
730 #endif
731         WebKitInitializeApplicationCachePathIfNecessary();
732         patchMailRemoveAttributesMethod();
733         
734         // Initialize our platform strategies.
735         WebPlatformStrategies::initialize();
736         Settings::setDefaultMinDOMTimerInterval(0.004);
737
738         didOneTimeInitialization = true;
739     }
740
741     Page::PageClients pageClients;
742     pageClients.chromeClient = new WebChromeClient(self);
743     pageClients.contextMenuClient = new WebContextMenuClient(self);
744     pageClients.editorClient = new WebEditorClient(self);
745     pageClients.dragClient = new WebDragClient(self);
746     pageClients.inspectorClient = new WebInspectorClient(self);
747     pageClients.pluginHalterClient = adoptPtr(new WebPluginHalterClient(self));
748 #if ENABLE(CLIENT_BASED_GEOLOCATION)
749     pageClients.geolocationClient = new WebGeolocationClient(self);
750 #endif
751 #if ENABLE(DEVICE_ORIENTATION)
752     pageClients.deviceOrientationClient = new WebDeviceOrientationClient(self);
753 #endif
754     _private->page = new Page(pageClients);
755
756     _private->page->setCanStartMedia([self window]);
757     _private->page->settings()->setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
758
759     if (needsOutlookQuirksScript()) {
760         _private->page->settings()->setShouldInjectUserScriptsInInitialEmptyDocument(true);
761         [self _injectOutlookQuirksScript];
762     }
763
764     if (needsSolarWalkQuirksScript()) {
765         _private->page->settings()->setShouldInjectUserScriptsInInitialEmptyDocument(true);
766         [self _injectSolarWalkQuirksScript];
767     }
768
769     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
770
771     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
772
773     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
774         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
775     else
776         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
777
778     [self _addToAllWebViewsSet];
779     [self setGroupName:groupName];
780     
781     // If there's already a next key view (e.g., from a nib), wire it up to our
782     // contained frame view. In any case, wire our next key view up to the our
783     // contained frame view. This works together with our becomeFirstResponder 
784     // and setNextKeyView overrides.
785     NSView *nextKeyView = [self nextKeyView];
786     if (nextKeyView && nextKeyView != frameView)
787         [frameView setNextKeyView:nextKeyView];
788     [super setNextKeyView:frameView];
789
790     if ([[self class] shouldIncludeInWebKitStatistics])
791         ++WebViewCount;
792
793     [self _registerDraggedTypes];
794
795     WebPreferences *prefs = [self preferences];
796     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
797                                                  name:WebPreferencesChangedInternalNotification object:prefs];
798
799     [self _preferencesChanged:[self preferences]];
800     [[self preferences] _postPreferencesChangedAPINotification];
801
802     memoryPressureHandler().install();
803
804     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
805         // Originally, we allowed all local loads.
806         SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForAll);
807     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
808         // Later, we allowed local loads for local URLs and documents loaded
809         // with substitute data.
810         SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForLocalAndSubstituteData);
811     }
812
813     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
814         ResourceHandle::forceContentSniffing();
815
816 #if ENABLE(GLIB_SUPPORT)
817     [self _scheduleGlibContextIterations];
818 #endif
819
820     if (runningTigerMail() || runningLeopardMail())
821         [self _injectMailQuirksScript];
822 }
823
824 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
825 {
826     self = [super initWithFrame:f];
827     if (!self)
828         return nil;
829
830 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
831     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
832     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
833     // need for Safari to unset it to prevent it from being passed to applications it launches.
834     // Unsetting it when a WebView is first created is as good a place as any.
835     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
836     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
837         unsetenv("DYLD_FRAMEWORK_PATH");
838         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
839     }
840 #endif
841
842     _private = [[WebViewPrivate alloc] init];
843     [self _commonInitializationWithFrameName:frameName groupName:groupName usesDocumentViews:usesDocumentViews];
844     [self setMaintainsBackForwardList: YES];
845     return self;
846 }
847
848 - (BOOL)_mustDrawUnionedRect:(NSRect)rect singleRects:(const NSRect *)rects count:(NSInteger)count
849 {
850     // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
851     // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
852     // The reason for the workaround is that this method is called explicitly from the code
853     // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
854     const int cRectThreshold = 10;
855     const float cWastedSpaceThreshold = 0.75f;
856     BOOL useUnionedRect = (count <= 1) || (count > cRectThreshold);
857     if (!useUnionedRect) {
858         // Attempt to guess whether or not we should use the unioned rect or the individual rects.
859         // We do this by computing the percentage of "wasted space" in the union.  If that wasted space
860         // is too large, then we will do individual rect painting instead.
861         float unionPixels = (rect.size.width * rect.size.height);
862         float singlePixels = 0;
863         for (int i = 0; i < count; ++i)
864             singlePixels += rects[i].size.width * rects[i].size.height;
865         float wastedSpace = 1 - (singlePixels / unionPixels);
866         if (wastedSpace <= cWastedSpaceThreshold)
867             useUnionedRect = YES;
868     }
869     return useUnionedRect;
870 }
871
872 - (void)drawSingleRect:(NSRect)rect
873 {
874     ASSERT(!_private->usesDocumentViews);
875     
876     [NSGraphicsContext saveGraphicsState];
877     NSRectClip(rect);
878
879     @try {
880         [[self mainFrame] _drawRect:rect contentsOnly:NO];
881
882         [[self _UIDelegateForwarder] webView:self didDrawRect:rect];
883
884         if (WebNodeHighlight *currentHighlight = [self currentNodeHighlight])
885             [currentHighlight setNeedsUpdateInTargetViewRect:rect];
886
887         [NSGraphicsContext restoreGraphicsState];
888     } @catch (NSException *localException) {
889         [NSGraphicsContext restoreGraphicsState];
890         LOG_ERROR("Exception caught while drawing: %@", localException);
891         [localException raise];
892     }
893 }
894
895 - (BOOL)isFlipped 
896 {
897     return _private && !_private->usesDocumentViews;
898 }
899
900 - (void)setFrameSize:(NSSize)size
901 {
902     if (!_private->usesDocumentViews && !NSEqualSizes(_private->lastLayoutSize, size)) {
903         Frame* frame = [self _mainCoreFrame];
904         // FIXME: Viewless WebKit is broken with Safari banners (e.g., the Find banner).  We'll have to figure out a way for
905         // Safari to communicate that this space is being consumed.  For WebKit with document views, there's no
906         // need to do an explicit resize, since WebFrameViews have auto resizing turned on and will handle changing
907         // their bounds automatically. See <rdar://problem/6835573> for details.
908         frame->view()->resize(IntSize(size));
909         frame->view()->setNeedsLayout();
910         [self setNeedsDisplay:YES];
911         _private->lastLayoutSize = size;
912     }
913
914     [super setFrameSize:size];
915 }
916
917 - (void)_viewWillDrawInternal
918 {
919     Frame* frame = [self _mainCoreFrame];
920     if (frame && frame->view())
921         frame->view()->updateLayoutAndStyleIfNeededRecursive();
922 }
923
924 - (void)viewWillDraw
925 {
926     if (!_private->usesDocumentViews)
927         [self _viewWillDrawInternal];
928     [super viewWillDraw];
929 }
930
931
932
933 - (void)drawRect:(NSRect)rect
934 {
935     if (_private->usesDocumentViews)
936         return [super drawRect:rect];
937     
938     ASSERT_MAIN_THREAD();
939
940     const NSRect *rects;
941     NSInteger count;
942     [self getRectsBeingDrawn:&rects count:&count];
943
944     
945     if ([self _mustDrawUnionedRect:rect singleRects:rects count:count])
946         [self drawSingleRect:rect];
947     else
948         for (int i = 0; i < count; ++i)
949             [self drawSingleRect:rects[i]];
950 }
951
952 + (NSArray *)_supportedMIMETypes
953 {
954     // Load the plug-in DB allowing plug-ins to install types.
955     [WebPluginDatabase sharedDatabase];
956     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
957 }
958
959 + (NSArray *)_supportedFileExtensions
960 {
961     NSMutableSet *extensions = [[NSMutableSet alloc] init];
962     NSArray *MIMETypes = [self _supportedMIMETypes];
963     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
964     NSString *MIMEType;
965     while ((MIMEType = [enumerator nextObject]) != nil) {
966         NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
967         if (extensionsForType) {
968             [extensions addObjectsFromArray:extensionsForType];
969         }
970     }
971     NSArray *uniqueExtensions = [extensions allObjects];
972     [extensions release];
973     return uniqueExtensions;
974 }
975
976 static NSMutableSet *knownPluginMIMETypes()
977 {
978     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
979     
980     return mimeTypes;
981 }
982
983 + (void)_registerPluginMIMEType:(NSString *)MIMEType
984 {
985     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
986     [knownPluginMIMETypes() addObject:MIMEType];
987 }
988
989 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
990 {
991     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
992     [knownPluginMIMETypes() removeObject:MIMEType];
993 }
994
995 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
996 {
997     MIMEType = [MIMEType lowercaseString];
998     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
999     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1000
1001     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1002         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1003
1004         if (allowPlugins) {
1005             // Load the plug-in DB allowing plug-ins to install types.
1006             [WebPluginDatabase sharedDatabase];
1007         }
1008
1009         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1010         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1011         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1012     }
1013     
1014     if (viewClass && repClass) {
1015         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1016             // Special-case WebHTMLView for text types that shouldn't be shown.
1017             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1018                 return NO;
1019
1020             // If the MIME type is a known plug-in we might not want to load it.
1021             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1022                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1023                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1024                 
1025                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1026                 if (!isSupportedByWebKit)
1027                     return NO;
1028             }
1029         }
1030         if (vClass)
1031             *vClass = viewClass;
1032         if (rClass)
1033             *rClass = repClass;
1034         return YES;
1035     }
1036     
1037     return NO;
1038 }
1039
1040 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1041 {
1042     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1043         return YES;
1044
1045     if (_private->pluginDatabase) {
1046         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1047         if (pluginPackage) {
1048             if (vClass)
1049                 *vClass = [WebHTMLView class];
1050             if (rClass)
1051                 *rClass = [WebHTMLRepresentation class];
1052             return YES;
1053         }
1054     }
1055     
1056     return NO;
1057 }
1058
1059 + (void)_setAlwaysUseATSU:(BOOL)f
1060 {
1061     [self _setAlwaysUsesComplexTextCodePath:f];
1062 }
1063
1064 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1065 {
1066     Font::setCodePath(f ? Font::Complex : Font::Auto);
1067 }
1068
1069 + (void)_setAllowsRoundingHacks:(BOOL)allowsRoundingHacks
1070 {
1071     TextRun::setAllowsRoundingHacks(allowsRoundingHacks);
1072 }
1073
1074 + (BOOL)_allowsRoundingHacks
1075 {
1076     return TextRun::allowsRoundingHacks();
1077 }
1078
1079 + (BOOL)canCloseAllWebViews
1080 {
1081     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1082 }
1083
1084 + (void)closeAllWebViews
1085 {
1086     DOMWindow::dispatchAllPendingUnloadEvents();
1087
1088     // This will close the WebViews in a random order. Change this if close order is important.
1089     // Make a new set to avoid mutating the set we are enumerating.
1090     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
1091     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1092     while (WebView *webView = [enumerator nextObject])
1093         [webView close];
1094 }
1095
1096 + (BOOL)canShowFile:(NSString *)path
1097 {
1098     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1099 }
1100
1101 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1102 {
1103     return WKGetPreferredExtensionForMIMEType(type);
1104 }
1105
1106 - (BOOL)_isClosed
1107 {
1108     return !_private || _private->closed;
1109 }
1110
1111 - (void)_closePluginDatabases
1112 {
1113     pluginDatabaseClientCount--;
1114
1115     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1116
1117     // Unload the WebView local plug-in database. 
1118     if (_private->pluginDatabase) {
1119         [_private->pluginDatabase destroyAllPluginInstanceViews];
1120         [_private->pluginDatabase close];
1121         [_private->pluginDatabase release];
1122         _private->pluginDatabase = nil;
1123     }
1124     
1125     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1126     if (!pluginDatabaseClientCount && applicationIsTerminating)
1127         [WebPluginDatabase closeSharedDatabase];
1128 }
1129
1130 - (void)_closeWithFastTeardown 
1131 {
1132 #ifndef NDEBUG
1133     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1134 #endif
1135
1136     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1137     [[NSNotificationCenter defaultCenter] removeObserver:self];
1138
1139     [self _closePluginDatabases];
1140 }
1141
1142 static bool fastDocumentTeardownEnabled()
1143 {
1144 #ifdef NDEBUG
1145     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1146 #else
1147     static bool initialized = false;
1148     static bool enabled = false;
1149     if (!initialized) {
1150         // This allows debug builds to default to not have fast teardown, so leak checking still works.
1151         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1152         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1153         if (setting)
1154             enabled = ![setting boolValue];
1155         initialized = true;
1156     }
1157 #endif
1158     return enabled;
1159 }
1160
1161 // _close is here only for backward compatibility; clients and subclasses should use
1162 // public method -close instead.
1163 - (void)_close
1164 {
1165     if (!_private || _private->closed)
1166         return;
1167
1168     _private->closed = YES;
1169     [self _removeFromAllWebViewsSet];
1170
1171     [self _closingEventHandling];
1172
1173 #ifndef NDEBUG
1174     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1175 #endif
1176
1177     // To quit the apps fast we skip document teardown, except plugins
1178     // need to be destroyed and unloaded.
1179     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1180         [self _closeWithFastTeardown];
1181         return;
1182     }
1183
1184 #if ENABLE(VIDEO)
1185     [self _exitFullscreen];
1186 #endif
1187
1188     if (Frame* mainFrame = [self _mainCoreFrame])
1189         mainFrame->loader()->detachFromParent();
1190
1191     [self setHostWindow:nil];
1192
1193     [self setDownloadDelegate:nil];
1194     [self setEditingDelegate:nil];
1195     [self setFrameLoadDelegate:nil];
1196     [self setPolicyDelegate:nil];
1197     [self setResourceLoadDelegate:nil];
1198     [self setScriptDebugDelegate:nil];
1199     [self setUIDelegate:nil];
1200
1201     [_private->inspector webViewClosed];
1202
1203     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1204     [self removeDragCaret];
1205
1206     // Deleteing the WebCore::Page will clear the page cache so we call destroy on 
1207     // all the plug-ins in the page cache to break any retain cycles.
1208     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1209     Page* page = _private->page;
1210     _private->page = 0;
1211     delete page;
1212
1213     if (_private->hasSpellCheckerDocumentTag) {
1214         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1215         _private->hasSpellCheckerDocumentTag = NO;
1216     }
1217
1218 #if USE(ACCELERATED_COMPOSITING)
1219     [self _clearLayerSyncLoopObserver];
1220 #endif
1221     
1222 #if ENABLE(GLIB_SUPPORT)
1223     [self _clearGlibLoopObserver];
1224 #endif
1225
1226     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1227     [[NSNotificationCenter defaultCenter] removeObserver:self];
1228
1229     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1230
1231     WebPreferences *preferences = _private->preferences;
1232     _private->preferences = nil;
1233     [preferences didRemoveFromWebView];
1234     [preferences release];
1235
1236     [self _closePluginDatabases];
1237
1238 #ifndef NDEBUG
1239     // Need this to make leak messages accurate.
1240     if (applicationIsTerminating) {
1241         gcController().garbageCollectNow();
1242         [WebCache setDisabled:YES];
1243     }
1244 #endif
1245 }
1246
1247 // Indicates if the WebView is in the midst of a user gesture.
1248 - (BOOL)_isProcessingUserGesture
1249 {
1250     return ScriptController::processingUserGesture();
1251 }
1252
1253 + (NSString *)_MIMETypeForFile:(NSString *)path
1254 {
1255     NSString *extension = [path pathExtension];
1256     NSString *MIMEType = nil;
1257
1258     // Get the MIME type from the extension.
1259     if ([extension length] != 0) {
1260         MIMEType = WKGetMIMETypeForExtension(extension);
1261     }
1262
1263     // If we can't get a known MIME type from the extension, sniff.
1264     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1265         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1266         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1267         [handle closeFile];
1268         if ([data length] != 0) {
1269             MIMEType = [data _webkit_guessedMIMEType];
1270         }
1271         if ([MIMEType length] == 0) {
1272             MIMEType = @"application/octet-stream";
1273         }
1274     }
1275
1276     return MIMEType;
1277 }
1278
1279 - (WebDownload *)_downloadURL:(NSURL *)URL
1280 {
1281     ASSERT(URL);
1282     
1283     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1284     WebDownload *download = [WebDownload _downloadWithRequest:request
1285                                                      delegate:_private->downloadDelegate
1286                                                     directory:nil];
1287     [request release];
1288     
1289     return download;
1290 }
1291
1292 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1293 {
1294     NSDictionary *features = [[NSDictionary alloc] init];
1295     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1296                                             createWebViewWithRequest:nil
1297                                                       windowFeatures:features];
1298     [features release];
1299     if (!newWindowWebView)
1300         return nil;
1301
1302     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1303     return newWindowWebView;
1304 }
1305
1306 - (WebInspector *)inspector
1307 {
1308     if (!_private->inspector)
1309         _private->inspector = [[WebInspector alloc] initWithWebView:self];
1310     return _private->inspector;
1311 }
1312
1313 - (WebCore::Page*)page
1314 {
1315     return _private->page;
1316 }
1317
1318 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1319 {
1320     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1321     NSArray *menuItems = defaultMenuItems;
1322
1323     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
1324     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
1325     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
1326     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1327         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
1328         if (!menuItems)
1329             return nil;
1330     }
1331
1332     unsigned count = [menuItems count];
1333     if (!count)
1334         return nil;
1335
1336     NSMenu *menu = [[NSMenu alloc] init];
1337     for (unsigned i = 0; i < count; i++)
1338         [menu addItem:[menuItems objectAtIndex:i]];
1339
1340     return [menu autorelease];
1341 }
1342
1343 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1344 {
1345     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1346     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1347     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1348     if (!dictionary)
1349         return;
1350     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1351 }
1352
1353 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1354 {
1355     if (!_private->page)
1356         return;
1357     
1358     if (!otherView->_private->page)
1359         return;
1360     
1361     // It turns out the right combination of behavior is done with the back/forward load
1362     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
1363     // in the back forward list, and go to the current one.
1364
1365     BackForwardList* backForwardList = _private->page->backForwardList();
1366     ASSERT(!backForwardList->currentItem()); // destination list should be empty
1367
1368     BackForwardList* otherBackForwardList = otherView->_private->page->backForwardList();
1369     if (!otherBackForwardList->currentItem())
1370         return; // empty back forward list, bail
1371     
1372     HistoryItem* newItemToGoTo = 0;
1373
1374     int lastItemIndex = otherBackForwardList->forwardListCount();
1375     for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
1376         if (i == 0) {
1377             // If this item is showing , save away its current scroll and form state,
1378             // since that might have changed since loading and it is normally not saved
1379             // until we leave that page.
1380             otherView->_private->page->mainFrame()->loader()->history()->saveDocumentAndScrollState();
1381         }
1382         RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
1383         if (i == 0) 
1384             newItemToGoTo = newItem.get();
1385         backForwardList->addItem(newItem.release());
1386     }
1387     
1388     ASSERT(newItemToGoTo);
1389     _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
1390 }
1391
1392 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
1393 {
1394     _private->formDelegate = delegate;
1395 }
1396
1397 - (id<WebFormDelegate>)_formDelegate
1398 {
1399     return _private->formDelegate;
1400 }
1401
1402 - (BOOL)_needsAdobeFrameReloadingQuirk
1403 {
1404     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
1405         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
1406         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
1407         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
1408         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
1409         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
1410         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
1411         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
1412         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
1413         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
1414
1415     return needsQuirk;
1416 }
1417
1418 - (BOOL)_needsLinkElementTextCSSQuirk
1419 {
1420     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
1421         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
1422     return needsQuirk;
1423 }
1424
1425 - (BOOL)_needsKeyboardEventDisambiguationQuirks
1426 {
1427     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
1428     return needsQuirks;
1429 }
1430
1431 - (BOOL)_needsFrameLoadDelegateRetainQuirk
1432 {
1433     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
1434     return needsQuirk;
1435 }
1436
1437 static bool needsSelfRetainWhileLoadingQuirk()
1438 {
1439     static bool needsQuirk = applicationIsAperture();
1440     return needsQuirk;
1441 }
1442
1443 - (BOOL)_needsPreHTML5ParserQuirks
1444 {    
1445     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
1446     // with the new HTML5 parser. If these applications were linked against a
1447     // version of WebKit prior to the introduction of the HTML5 parser, enable
1448     // parser quirks to maintain compatibility. For details, see 
1449     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
1450     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
1451     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1452         && (applicationIsAOLInstantMessenger() || applicationIsMicrosoftMyDay());
1453     
1454     // Mail.app must continue to display HTML email that contains quirky markup.
1455     static bool isAppleMail = applicationIsAppleMail();
1456
1457     return isApplicationNeedingParserQuirks
1458         || isAppleMail
1459 #if ENABLE(DASHBOARD_SUPPORT)
1460         // Pre-HTML5 parser quirks are required to remain compatible with many
1461         // Dashboard widgets. See <rdar://problem/8175982>.
1462         || (_private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode())
1463 #endif
1464         || [[self preferences] usePreHTML5ParserQuirks];
1465 }
1466
1467 - (BOOL)_needsUnrestrictedGetMatchedCSSRules
1468 {
1469     static bool needsUnrestrictedGetMatchedCSSRules = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_GET_MATCHED_CSS_RULES_RESTRICTIONS) && applicationIsSafari();
1470     return needsUnrestrictedGetMatchedCSSRules;
1471 }
1472
1473 - (void)_preferencesChangedNotification:(NSNotification *)notification
1474 {
1475     WebPreferences *preferences = (WebPreferences *)[notification object];
1476     [self _preferencesChanged:preferences];
1477 }
1478
1479 - (void)_preferencesChanged:(WebPreferences *)preferences
1480 {    
1481     ASSERT(preferences == [self preferences]);
1482     if (!_private->userAgentOverridden)
1483         _private->userAgent = String();
1484
1485     // Cache this value so we don't have to read NSUserDefaults on each page load
1486     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
1487
1488     // Update corresponding WebCore Settings object.
1489     if (!_private->page)
1490         return;
1491     
1492     Settings* settings = _private->page->settings();
1493     
1494     settings->setCursiveFontFamily([preferences cursiveFontFamily]);
1495     settings->setDefaultFixedFontSize([preferences defaultFixedFontSize]);
1496     settings->setDefaultFontSize([preferences defaultFontSize]);
1497     settings->setDefaultTextEncodingName([preferences defaultTextEncodingName]);
1498     settings->setUsesEncodingDetector([preferences usesEncodingDetector]);
1499     settings->setFantasyFontFamily([preferences fantasyFontFamily]);
1500     settings->setFixedFontFamily([preferences fixedFontFamily]);
1501     settings->setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
1502     settings->setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
1503     settings->setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
1504     settings->setJavaEnabled([preferences isJavaEnabled]);
1505     settings->setJavaScriptEnabled([preferences isJavaScriptEnabled]);
1506     settings->setWebSecurityEnabled([preferences isWebSecurityEnabled]);
1507     settings->setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
1508     settings->setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
1509     settings->setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
1510     settings->setMinimumFontSize([preferences minimumFontSize]);
1511     settings->setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
1512     settings->setPluginsEnabled([preferences arePlugInsEnabled]);
1513 #if ENABLE(DATABASE)
1514     AbstractDatabase::setIsAvailable([preferences databasesEnabled]);
1515 #endif
1516     settings->setLocalStorageEnabled([preferences localStorageEnabled]);
1517     settings->setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
1518     settings->setPrivateBrowsingEnabled([preferences privateBrowsingEnabled]);
1519     settings->setSansSerifFontFamily([preferences sansSerifFontFamily]);
1520     settings->setSerifFontFamily([preferences serifFontFamily]);
1521     settings->setStandardFontFamily([preferences standardFontFamily]);
1522     settings->setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
1523     settings->setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
1524     settings->setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
1525     settings->setTextAreasAreResizable([preferences textAreasAreResizable]);
1526     settings->setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
1527     settings->setEditableLinkBehavior(core([preferences editableLinkBehavior]));
1528     settings->setEditingBehaviorType(core([preferences editingBehavior]));
1529     settings->setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
1530     settings->setDOMPasteAllowed([preferences isDOMPasteAllowed]);
1531     settings->setUsesPageCache([self usesPageCache]);
1532     settings->setShowsURLsInToolTips([preferences showsURLsInToolTips]);
1533     settings->setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
1534     settings->setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
1535     settings->setApplicationChromeMode([preferences applicationChromeModeEnabled]);
1536     if ([preferences userStyleSheetEnabled]) {
1537         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
1538         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
1539             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
1540         settings->setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
1541     } else
1542         settings->setUserStyleSheetLocation([NSURL URLWithString:@""]);
1543     settings->setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
1544     settings->setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
1545     settings->setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
1546     settings->setNeedsLeopardMailQuirks(runningLeopardMail());
1547     settings->setNeedsTigerMailQuirks(runningTigerMail());
1548     settings->setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
1549     settings->setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
1550     settings->setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
1551     settings->setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
1552     settings->setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
1553     settings->setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
1554     settings->setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
1555     settings->setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
1556     
1557     // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
1558     // Until we fix that, I will comment out the test (CFM)
1559     settings->setAcceleratedCompositingEnabled((coreVideoHas7228836Fix() || [preferences webGLEnabled] || 
1560         [preferences accelerated2dCanvasEnabled]) && [preferences acceleratedCompositingEnabled]);
1561     settings->setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1562     settings->setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);    
1563     settings->setShowDebugBorders([preferences showDebugBorders]);
1564     settings->setShowRepaintCounter([preferences showRepaintCounter]);
1565     settings->setPluginAllowedRunTime([preferences pluginAllowedRunTime]);
1566     settings->setWebAudioEnabled([preferences webAudioEnabled]);
1567     settings->setWebGLEnabled([preferences webGLEnabled]);
1568     settings->setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
1569     settings->setLoadDeferringEnabled(shouldEnableLoadDeferring());
1570     settings->setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
1571     settings->setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
1572     settings->setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
1573 #if ENABLE(FULLSCREEN_API)
1574     settings->setFullScreenEnabled([preferences fullScreenEnabled]);
1575 #endif
1576 #ifndef BUILDING_ON_LEOPARD
1577     // Asynchronous spell checking API is available for 10.6 or later.
1578     settings->setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
1579 #endif
1580     settings->setMemoryInfoEnabled([preferences memoryInfoEnabled]);
1581     settings->setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
1582     settings->setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
1583     settings->setCrossOriginCheckInGetMatchedCSSRulesDisabled([self _needsUnrestrictedGetMatchedCSSRules]);
1584     settings->setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
1585     settings->setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
1586 #if USE(AVFOUNDATION)
1587 #if ENABLE(FULLSCREEN_API)
1588     settings->setAVFoundationEnabled([preferences isAVFoundationEnabled] && [preferences fullScreenEnabled]);
1589 #else
1590     settings->setAVFoundationEnabled(false);
1591 #endif
1592 #endif
1593 #if ENABLE(WEB_SOCKETS)
1594     settings->setUseHixie76WebSocketProtocol([preferences isHixie76WebSocketProtocolEnabled]);
1595 #endif
1596
1597     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
1598     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
1599
1600     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
1601     if (_private->zoomsTextOnly != zoomsTextOnly)
1602         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
1603 }
1604
1605 static inline IMP getMethod(id o, SEL s)
1606 {
1607     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
1608 }
1609
1610 - (void)_cacheResourceLoadDelegateImplementations
1611 {
1612     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
1613     id delegate = _private->resourceProgressDelegate;
1614
1615     if (!delegate) {
1616         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
1617         return;
1618     }
1619
1620     cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
1621     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
1622     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
1623     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
1624     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1625 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
1626     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
1627 #endif
1628     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
1629     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
1630     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
1631     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
1632     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
1633     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
1634     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
1635     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
1636 }
1637
1638 - (void)_cacheFrameLoadDelegateImplementations
1639 {
1640     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
1641     id delegate = _private->frameLoadDelegate;
1642
1643     if (!delegate) {
1644         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
1645         return;
1646     }
1647
1648     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
1649     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
1650     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
1651     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
1652     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
1653     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
1654     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
1655     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
1656     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
1657     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
1658     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
1659     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
1660     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
1661     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
1662     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
1663     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
1664     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
1665     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
1666     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
1667     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
1668     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
1669     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
1670     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
1671     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
1672     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
1673 }
1674
1675 - (void)_cacheScriptDebugDelegateImplementations
1676 {
1677     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
1678     id delegate = _private->scriptDebugDelegate;
1679
1680     if (!delegate) {
1681         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
1682         return;
1683     }
1684
1685     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
1686     if (cache->didParseSourceFunc)
1687         cache->didParseSourceExpectsBaseLineNumber = YES;
1688     else {
1689         cache->didParseSourceExpectsBaseLineNumber = NO;
1690         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
1691     }
1692
1693     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
1694     cache->didEnterCallFrameFunc = getMethod(delegate, @selector(webView:didEnterCallFrame:sourceId:line:forWebFrame:));
1695     cache->willExecuteStatementFunc = getMethod(delegate, @selector(webView:willExecuteStatement:sourceId:line:forWebFrame:));
1696     cache->willLeaveCallFrameFunc = getMethod(delegate, @selector(webView:willLeaveCallFrame:sourceId:line:forWebFrame:));
1697
1698     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
1699     if (cache->exceptionWasRaisedFunc)
1700         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
1701     else {
1702         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
1703         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
1704     }
1705 }
1706
1707 - (void)_cacheHistoryDelegateImplementations
1708 {
1709     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
1710     id delegate = _private->historyDelegate;
1711
1712     if (!delegate) {
1713         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
1714         return;
1715     }
1716
1717     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
1718     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
1719     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
1720     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
1721     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
1722 }
1723
1724 - (id)_policyDelegateForwarder
1725 {
1726     if (!_private->policyDelegateForwarder)
1727         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate] catchExceptions:_private->catchesDelegateExceptions];
1728     return _private->policyDelegateForwarder;
1729 }
1730
1731 - (id)_UIDelegateForwarder
1732 {
1733     if (!_private->UIDelegateForwarder)
1734         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate] catchExceptions:_private->catchesDelegateExceptions];
1735     return _private->UIDelegateForwarder;
1736 }
1737
1738 - (id)_editingDelegateForwarder
1739 {
1740     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
1741     // Not sure if that is a bug or not.
1742     if (!_private)
1743         return nil;
1744
1745     if (!_private->editingDelegateForwarder)
1746         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate] catchExceptions:_private->catchesDelegateExceptions];
1747     return _private->editingDelegateForwarder;
1748 }
1749
1750 - (void)_closeWindow
1751 {
1752     [[self _UIDelegateForwarder] webViewClose:self];
1753 }
1754
1755 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
1756 {
1757     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1758     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1759     
1760     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1761     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
1762     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1763     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
1764 }
1765
1766 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
1767 {
1768     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
1769     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1770
1771     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1772     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
1773     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1774     if ([viewClass class] == [WebHTMLView class])
1775         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
1776     
1777     // This is used to make _representationExistsForURLScheme faster.
1778     // Without this set, we'd have to create the MIME type each time.
1779     if (schemesWithRepresentationsSet == nil) {
1780         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1781     }
1782     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1783 }
1784
1785 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1786 {
1787     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1788 }
1789
1790 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1791 {
1792     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1793 }
1794
1795 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
1796 {
1797     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
1798     if (!request)
1799         return NO;
1800
1801     if ([NSURLConnection canHandleRequest:request])
1802         return YES;
1803
1804     NSString *scheme = [[request URL] scheme];
1805
1806     // Representations for URL schemes work at the top level.
1807     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
1808         return YES;
1809         
1810     return [scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"];
1811 }
1812
1813 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1814 {
1815     return [self _canHandleRequest:request forMainFrame:YES];
1816 }
1817
1818 + (NSString *)_decodeData:(NSData *)data
1819 {
1820     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
1821     RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("text/html"); // bookmark files are HTML
1822     String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
1823     result += decoder->flush();
1824     return result;
1825 }
1826
1827 - (void)_pushPerformingProgrammaticFocus
1828 {
1829     _private->programmaticFocusCount++;
1830 }
1831
1832 - (void)_popPerformingProgrammaticFocus
1833 {
1834     _private->programmaticFocusCount--;
1835 }
1836
1837 - (BOOL)_isPerformingProgrammaticFocus
1838 {
1839     return _private->programmaticFocusCount != 0;
1840 }
1841
1842 - (void)_didChangeValueForKey: (NSString *)key
1843 {
1844     LOG (Bindings, "calling didChangeValueForKey: %@", key);
1845     [self didChangeValueForKey: key];
1846 }
1847
1848 - (void)_willChangeValueForKey: (NSString *)key
1849 {
1850     LOG (Bindings, "calling willChangeValueForKey: %@", key);
1851     [self willChangeValueForKey: key];
1852 }
1853
1854 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1855     static NSSet *manualNotifyKeys = nil;
1856     if (!manualNotifyKeys)
1857         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1858             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
1859             nil];
1860     if ([manualNotifyKeys containsObject:key])
1861         return NO;
1862     return YES;
1863 }
1864
1865 - (NSArray *)_declaredKeys {
1866     static NSArray *declaredKeys = nil;
1867     if (!declaredKeys)
1868         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1869             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1870     return declaredKeys;
1871 }
1872
1873 - (void)setObservationInfo:(void *)info
1874 {
1875     _private->observationInfo = info;
1876 }
1877
1878 - (void *)observationInfo
1879 {
1880     return _private->observationInfo;
1881 }
1882
1883 - (void)_willChangeBackForwardKeys
1884 {
1885     [self _willChangeValueForKey: _WebCanGoBackKey];
1886     [self _willChangeValueForKey: _WebCanGoForwardKey];
1887 }
1888
1889 - (void)_didChangeBackForwardKeys
1890 {
1891     [self _didChangeValueForKey: _WebCanGoBackKey];
1892     [self _didChangeValueForKey: _WebCanGoForwardKey];
1893 }
1894
1895 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1896 {
1897     if (needsSelfRetainWhileLoadingQuirk())
1898         [self retain];
1899
1900     [self _willChangeBackForwardKeys];
1901     if (frame == [self mainFrame]){
1902         // Force an observer update by sending a will/did.
1903         [self _willChangeValueForKey: _WebIsLoadingKey];
1904         [self _didChangeValueForKey: _WebIsLoadingKey];
1905
1906         [self _willChangeValueForKey: _WebMainFrameURLKey];
1907     }
1908
1909     [NSApp setWindowsNeedUpdate:YES];
1910 }
1911
1912 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1913 {
1914     if (frame == [self mainFrame])
1915         [self _didChangeValueForKey: _WebMainFrameURLKey];
1916     [NSApp setWindowsNeedUpdate:YES];
1917 }
1918
1919 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1920 {
1921     if (needsSelfRetainWhileLoadingQuirk())
1922         [self performSelector:@selector(release) withObject:nil afterDelay:0];
1923         
1924     [self _didChangeBackForwardKeys];
1925     if (frame == [self mainFrame]){
1926         // Force an observer update by sending a will/did.
1927         [self _willChangeValueForKey: _WebIsLoadingKey];
1928         [self _didChangeValueForKey: _WebIsLoadingKey];
1929     }
1930     [NSApp setWindowsNeedUpdate:YES];
1931 }
1932
1933 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1934 {
1935     if (needsSelfRetainWhileLoadingQuirk())
1936         [self performSelector:@selector(release) withObject:nil afterDelay:0];
1937
1938     [self _didChangeBackForwardKeys];
1939     if (frame == [self mainFrame]){
1940         // Force an observer update by sending a will/did.
1941         [self _willChangeValueForKey: _WebIsLoadingKey];
1942         [self _didChangeValueForKey: _WebIsLoadingKey];
1943     }
1944     [NSApp setWindowsNeedUpdate:YES];
1945 }
1946
1947 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1948 {
1949     if (needsSelfRetainWhileLoadingQuirk())
1950         [self performSelector:@selector(release) withObject:nil afterDelay:0];
1951
1952     [self _didChangeBackForwardKeys];
1953     if (frame == [self mainFrame]){
1954         // Force an observer update by sending a will/did.
1955         [self _willChangeValueForKey: _WebIsLoadingKey];
1956         [self _didChangeValueForKey: _WebIsLoadingKey];
1957         
1958         [self _didChangeValueForKey: _WebMainFrameURLKey];
1959     }
1960     [NSApp setWindowsNeedUpdate:YES];
1961 }
1962
1963 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1964 {
1965     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1966     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1967     NSCachedURLResponse *cachedResponse;
1968 #if USE(CFURLSTORAGESESSIONS)
1969     if (CFURLStorageSessionRef storageSession = ResourceHandle::privateBrowsingStorageSession())
1970         cachedResponse = WKCachedResponseForRequest(storageSession, request);
1971     else
1972 #endif
1973         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1974     [request release];
1975     return cachedResponse;
1976 }
1977
1978 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1979 {
1980     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1981     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1982     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
1983                         element:domElement
1984                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1985                           title:[element objectForKey:WebElementImageAltStringKey] 
1986                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1987                           types:types
1988                          source:nil];
1989 }
1990
1991 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1992 {
1993     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1994                      andTitle:[element objectForKey:WebElementLinkLabelKey]
1995                         types:types];
1996 }
1997
1998 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1999 {
2000     if (!_private->page)
2001         return;
2002     _private->page->dragController()->setDidInitiateDrag(initiatedDrag);
2003 }
2004
2005 #if ENABLE(DASHBOARD_SUPPORT)
2006
2007 #define DASHBOARD_CONTROL_LABEL @"control"
2008
2009 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
2010 {
2011     NSRect adjustedBounds = bounds;
2012     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
2013     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
2014     adjustedBounds.size = bounds.size;
2015
2016     NSRect adjustedClip;
2017     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
2018     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
2019     adjustedClip.size = clip.size;
2020
2021     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
2022         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
2023     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
2024     if (!scrollerRegions) {
2025         scrollerRegions = [[NSMutableArray alloc] init];
2026         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
2027         [scrollerRegions release];
2028     }
2029     [scrollerRegions addObject:region];
2030     [region release];
2031 }
2032
2033 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
2034 {    
2035     NSView *documentView = [[kit(frameView->frame()) frameView] documentView];
2036
2037     const HashSet<RefPtr<Widget> >* children = frameView->children();
2038     HashSet<RefPtr<Widget> >::const_iterator end = children->end();
2039     for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != end; ++it) {
2040         Widget* widget = (*it).get();
2041         if (widget->isFrameView()) {
2042             [self _addScrollerDashboardRegionsForFrameView:static_cast<FrameView*>(widget) dashboardRegions:regions];
2043             continue;
2044         }
2045
2046         if (!widget->isScrollbar())
2047             continue;
2048
2049         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
2050         // it's not common to need this to be correct in Dashboard widgets.
2051         NSRect bounds = widget->frameRect();
2052         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
2053     }
2054 }
2055
2056 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
2057 {
2058     // Add scroller regions for NSScroller and WebCore scrollbars
2059     NSUInteger count = [views count];
2060     for (NSUInteger i = 0; i < count; i++) {
2061         NSView *view = [views objectAtIndex:i];
2062         
2063         if ([view isKindOfClass:[WebHTMLView class]]) {
2064             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
2065                 if (FrameView* coreView = coreFrame->view())
2066                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
2067             }
2068         } else if ([view isKindOfClass:[NSScroller class]]) {
2069             // AppKit places absent scrollers at -100,-100
2070             if ([view frame].origin.y < 0)
2071                 continue;
2072             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
2073         }
2074         [self _addScrollerDashboardRegions:regions from:[view subviews]];
2075     }
2076 }
2077
2078 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
2079 {
2080     [self _addScrollerDashboardRegions:regions from:[self subviews]];
2081 }
2082
2083 - (NSDictionary *)_dashboardRegions
2084 {
2085     // Only return regions from main frame.
2086     Frame* mainFrame = [self _mainCoreFrame];
2087     if (!mainFrame)
2088         return nil;
2089
2090     const Vector<DashboardRegionValue>& regions = mainFrame->document()->dashboardRegions();
2091     size_t size = regions.size();
2092
2093     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
2094     for (size_t i = 0; i < size; i++) {
2095         const DashboardRegionValue& region = regions[i];
2096
2097         if (region.type == StyleDashboardRegion::None)
2098             continue;
2099
2100         NSString *label = region.label;
2101         WebDashboardRegionType type = WebDashboardRegionTypeNone;
2102         if (region.type == StyleDashboardRegion::Circle)
2103             type = WebDashboardRegionTypeCircle;
2104         else if (region.type == StyleDashboardRegion::Rectangle)
2105             type = WebDashboardRegionTypeRectangle;
2106         NSMutableArray *regionValues = [webRegions objectForKey:label];
2107         if (!regionValues) {
2108             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
2109             [webRegions setObject:regionValues forKey:label];
2110             [regionValues release];
2111         }
2112
2113         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:region.bounds clip:region.clip type:type];
2114         [regionValues addObject:webRegion];
2115         [webRegion release];
2116     }
2117
2118     [self _addScrollerDashboardRegions:webRegions];
2119
2120     return webRegions;
2121 }
2122
2123 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
2124 {
2125     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
2126     // specific support for the backward compatibility mode flag.
2127     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
2128         _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(true);
2129     
2130     switch (behavior) {
2131         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
2132             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
2133             break;
2134         }
2135         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
2136             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
2137             break;
2138         }
2139         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
2140             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
2141             break;
2142         }
2143         case WebDashboardBehaviorAllowWheelScrolling: {
2144             _private->dashboardBehaviorAllowWheelScrolling = flag;
2145             break;
2146         }
2147         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
2148             if (_private->page)
2149                 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(flag);
2150             break;
2151         }
2152     }
2153
2154     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
2155     // compatibility mode. See <rdar://problem/8175982>.
2156     if (_private->page)
2157         _private->page->settings()->setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2158 }
2159
2160 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
2161 {
2162     switch (behavior) {
2163         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
2164             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
2165         }
2166         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
2167             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
2168         }
2169         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
2170             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
2171         }
2172         case WebDashboardBehaviorAllowWheelScrolling: {
2173             return _private->dashboardBehaviorAllowWheelScrolling;
2174         }
2175         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
2176             return _private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode();
2177         }
2178     }
2179     return NO;
2180 }
2181
2182 #endif /* ENABLE(DASHBOARD_SUPPORT) */
2183
2184 + (void)_setShouldUseFontSmoothing:(BOOL)f
2185 {
2186     Font::setShouldUseSmoothing(f);
2187 }
2188
2189 + (BOOL)_shouldUseFontSmoothing
2190 {
2191     return Font::shouldUseSmoothing();
2192 }
2193
2194 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
2195 {
2196     setUsesTestModeFocusRingColor(f);
2197 }
2198
2199 + (BOOL)_usesTestModeFocusRingColor
2200 {
2201     return usesTestModeFocusRingColor();
2202 }
2203
2204 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
2205 {
2206     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2207     if (flag) {
2208         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
2209     } else {
2210         [scrollview setVerticalScrollingModeLocked:NO];
2211         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
2212     }
2213 }
2214
2215 - (BOOL)alwaysShowVerticalScroller
2216 {
2217     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2218     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
2219 }
2220
2221 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
2222 {
2223     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2224     if (flag) {
2225         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
2226     } else {
2227         [scrollview setHorizontalScrollingModeLocked:NO];
2228         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
2229     }
2230 }
2231
2232 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
2233 {
2234     if (Frame* mainFrame = [self _mainCoreFrame])
2235         mainFrame->view()->setProhibitsScrolling(prohibits);
2236 }
2237
2238 - (BOOL)alwaysShowHorizontalScroller
2239 {
2240     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2241     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
2242 }
2243
2244 - (void)_setInViewSourceMode:(BOOL)flag
2245 {
2246     if (Frame* mainFrame = [self _mainCoreFrame])
2247         mainFrame->setInViewSourceMode(flag);
2248 }
2249
2250 - (BOOL)_inViewSourceMode
2251 {
2252     Frame* mainFrame = [self _mainCoreFrame];
2253     return mainFrame && mainFrame->inViewSourceMode();
2254 }
2255
2256 - (void)_setUseFastImageScalingMode:(BOOL)flag
2257 {
2258     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
2259         _private->page->setInLowQualityImageInterpolationMode(flag);
2260         [self setNeedsDisplay:YES];
2261     }
2262 }
2263
2264 - (BOOL)_inFastImageScalingMode
2265 {
2266     if (_private->page)
2267         return _private->page->inLowQualityImageInterpolationMode();
2268     return NO;
2269 }
2270
2271 - (BOOL)_cookieEnabled
2272 {
2273     if (_private->page)
2274         return _private->page->cookieEnabled();
2275     return YES;
2276 }
2277
2278 - (void)_setCookieEnabled:(BOOL)enable
2279 {
2280     if (_private->page)
2281         _private->page->setCookieEnabled(enable);
2282 }
2283
2284 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
2285 {
2286     if (!_private->pluginDatabase)
2287         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
2288         
2289     [_private->pluginDatabase setPlugInPaths:newPaths];
2290     [_private->pluginDatabase refresh];
2291 }
2292
2293 - (void)_attachScriptDebuggerToAllFrames
2294 {
2295     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree()->traverseNext())
2296         [kit(frame) _attachScriptDebugger];
2297 }
2298
2299 - (void)_detachScriptDebuggerFromAllFrames
2300 {
2301     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree()->traverseNext())
2302         [kit(frame) _detachScriptDebugger];
2303 }
2304
2305 - (void)setBackgroundColor:(NSColor *)backgroundColor
2306 {
2307     if ([_private->backgroundColor isEqual:backgroundColor])
2308         return;
2309
2310     id old = _private->backgroundColor;
2311     _private->backgroundColor = [backgroundColor retain];
2312     [old release];
2313
2314     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
2315 }
2316
2317 - (NSColor *)backgroundColor
2318 {
2319     return _private->backgroundColor;
2320 }
2321
2322 - (BOOL)defersCallbacks
2323 {
2324     if (!_private->page)
2325         return NO;
2326     return _private->page->defersLoading();
2327 }
2328
2329 - (void)setDefersCallbacks:(BOOL)defer
2330 {
2331     if (!_private->page)
2332         return;
2333     return _private->page->setDefersLoading(defer);
2334 }
2335
2336 // For backwards compatibility with the WebBackForwardList API, we honor both
2337 // a per-WebView and a per-preferences setting for whether to use the page cache.
2338
2339 - (BOOL)usesPageCache
2340 {
2341     return _private->usesPageCache && [[self preferences] usesPageCache];
2342 }
2343
2344 - (void)setUsesPageCache:(BOOL)usesPageCache
2345 {
2346     _private->usesPageCache = usesPageCache;
2347
2348     // Update our own settings and post the public notification only
2349     [self _preferencesChanged:[self preferences]];
2350     [[self preferences] _postPreferencesChangedAPINotification];
2351 }
2352
2353 - (WebHistoryItem *)_globalHistoryItem
2354 {
2355     if (!_private)
2356         return nil;
2357
2358     return kit(_private->_globalHistoryItem.get());
2359 }
2360
2361 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
2362 {
2363     _private->_globalHistoryItem = historyItem;
2364 }
2365
2366 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
2367 {
2368     IntPoint rectStart(rect.origin.x, rect.origin.y);
2369     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
2370     
2371     Frame* coreFrame = [self _mainCoreFrame];
2372     if (!coreFrame)
2373         return nil;
2374     
2375     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
2376     
2377     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
2378 }
2379
2380 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource 
2381 {
2382     NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window]; 
2383     [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window]; 
2384
2385
2386 - (void)_clearUndoRedoOperations
2387 {
2388     if (!_private->page)
2389         return;
2390     _private->page->clearUndoRedoOperations();
2391 }
2392
2393 - (void)_setCatchesDelegateExceptions:(BOOL)f
2394 {
2395     _private->catchesDelegateExceptions = f;
2396 }
2397
2398 - (BOOL)_catchesDelegateExceptions
2399 {
2400     return _private->catchesDelegateExceptions;
2401 }
2402
2403 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
2404 {
2405     Frame* coreFrame = [self _mainCoreFrame];
2406     if (!coreFrame)
2407         return;
2408     coreFrame->editor()->command(name).execute(value);
2409 }
2410
2411 - (void)_setCustomHTMLTokenizerTimeDelay:(double)timeDelay
2412 {
2413     if (!_private->page)
2414         return;
2415     return _private->page->setCustomHTMLTokenizerTimeDelay(timeDelay);
2416 }
2417
2418 - (void)_setCustomHTMLTokenizerChunkSize:(int)chunkSize
2419 {
2420     if (!_private->page)
2421         return;
2422     return _private->page->setCustomHTMLTokenizerChunkSize(chunkSize);
2423 }
2424
2425 - (void)_clearMainFrameName
2426 {
2427     _private->page->mainFrame()->tree()->clearName();
2428 }
2429
2430 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
2431 {
2432     _private->selectTrailingWhitespaceEnabled = flag;
2433     if (flag)
2434         [self setSmartInsertDeleteEnabled:false];
2435 }
2436
2437 - (BOOL)isSelectTrailingWhitespaceEnabled
2438 {
2439     return _private->selectTrailingWhitespaceEnabled;
2440 }
2441
2442 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
2443 {
2444     _private->page->setMemoryCacheClientCallsEnabled(enabled);
2445 }
2446
2447 - (BOOL)areMemoryCacheDelegateCallsEnabled
2448 {
2449     return _private->page->areMemoryCacheClientCallsEnabled();
2450 }
2451
2452 - (void)_setJavaScriptURLsAreAllowed:(BOOL)areAllowed
2453 {
2454     _private->page->setJavaScriptURLsAreAllowed(areAllowed);
2455 }
2456
2457 + (NSCursor *)_pointingHandCursor
2458 {
2459     return handCursor().platformCursor();
2460 }
2461
2462 - (BOOL)_postsAcceleratedCompositingNotifications
2463 {
2464 #if USE(ACCELERATED_COMPOSITING)
2465     return _private->postsAcceleratedCompositingNotifications;
2466 #else
2467     return NO;
2468 #endif
2469
2470 }
2471 - (void)_setPostsAcceleratedCompositingNotifications:(BOOL)flag
2472 {
2473 #if USE(ACCELERATED_COMPOSITING)
2474     _private->postsAcceleratedCompositingNotifications = flag;
2475 #endif
2476 }
2477
2478 - (BOOL)_isUsingAcceleratedCompositing
2479 {
2480 #if USE(ACCELERATED_COMPOSITING)
2481     if (_private->usesDocumentViews) {
2482         Frame* coreFrame = [self _mainCoreFrame];
2483         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
2484             NSView *documentView = [[kit(frame) frameView] documentView];
2485             if ([documentView isKindOfClass:[WebHTMLView class]] && [(WebHTMLView *)documentView _isUsingAcceleratedCompositing])
2486                 return YES;
2487         }
2488     }
2489 #endif
2490     return NO;
2491 }
2492
2493 - (BOOL)interactiveFormValidationEnabled
2494 {
2495     return _private->interactiveFormValidationEnabled;
2496 }
2497
2498 - (void)setInteractiveFormValidationEnabled:(BOOL)enabled
2499 {
2500     _private->interactiveFormValidationEnabled = enabled;
2501 }
2502
2503 - (int)validationMessageTimerMagnification
2504 {
2505     return _private->validationMessageTimerMagnification;
2506 }
2507
2508 - (void)setValidationMessageTimerMagnification:(int)newValue
2509 {
2510     _private->validationMessageTimerMagnification = newValue;
2511 }
2512
2513 - (BOOL)_isSoftwareRenderable
2514 {
2515 #if USE(ACCELERATED_COMPOSITING)
2516     if (_private->usesDocumentViews) {
2517         Frame* coreFrame = [self _mainCoreFrame];
2518         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
2519             if (FrameView* view = frame->view()) {
2520                 if (!view->isSoftwareRenderable())
2521                     return NO;
2522             }
2523         }
2524     }
2525 #endif
2526     return YES;
2527 }
2528
2529 - (void)_setIncludesFlattenedCompositingLayersWhenDrawingToBitmap:(BOOL)flag
2530 {
2531     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = flag;
2532 }
2533
2534 - (BOOL)_includesFlattenedCompositingLayersWhenDrawingToBitmap
2535 {
2536     return _private->includesFlattenedCompositingLayersWhenDrawingToBitmap;
2537 }
2538
2539 #if ENABLE(NETSCAPE_PLUGIN_API)
2540 static WebBaseNetscapePluginView *_pluginViewForNode(DOMNode *node)
2541 {
2542     if (!node)
2543         return nil;
2544     
2545     Node* coreNode = core(node);
2546     if (!coreNode)
2547         return nil;
2548     
2549     RenderObject* renderer = coreNode->renderer();
2550     if (!renderer || !renderer->isWidget())
2551         return nil;
2552     
2553     Widget* widget = toRenderWidget(renderer)->widget();
2554     if (!widget || !widget->platformWidget())
2555         return nil;
2556     
2557     NSView *view = widget->platformWidget();
2558     if (![view isKindOfClass:[WebBaseNetscapePluginView class]])
2559         return nil;
2560     
2561     return (WebBaseNetscapePluginView *)view;
2562 }
2563 #endif // ENABLE(NETSCAPE_PLUGIN_API)
2564
2565 + (BOOL)_isNodeHaltedPlugin:(DOMNode *)node
2566 {
2567 #if ENABLE(NETSCAPE_PLUGIN_API)
2568     return [_pluginViewForNode(node) isHalted];
2569 #else
2570     return YES;
2571 #endif
2572 }
2573
2574 + (BOOL)_hasPluginForNodeBeenHalted:(DOMNode *)node
2575 {
2576 #if ENABLE(NETSCAPE_PLUGIN_API)
2577     return [_pluginViewForNode(node) hasBeenHalted];
2578 #else
2579     return YES;
2580 #endif
2581 }
2582 + (void)_restartHaltedPluginForNode:(DOMNode *)node
2583 {
2584 #if ENABLE(NETSCAPE_PLUGIN_API)
2585     if (!node)
2586         return;
2587     
2588     [_pluginViewForNode(node) resumeFromHalt];
2589 #endif
2590 }
2591
2592 - (NSPasteboard *)_insertionPasteboard
2593 {
2594     return _private ? _private->insertionPasteboard : nil;
2595 }
2596
2597 + (void)_addOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2598 {
2599     SecurityOrigin::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2600 }
2601
2602 + (void)_removeOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2603 {
2604     SecurityOrigin::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2605 }
2606
2607 +(void)_resetOriginAccessWhitelists
2608 {
2609     SecurityOrigin::resetOriginAccessWhitelists();
2610 }
2611
2612 - (void)_updateActiveState
2613 {
2614     if (_private && _private->page)
2615         _private->page->focusController()->setActive([[self window] isKeyWindow]);
2616 }
2617
2618 static PassOwnPtr<Vector<String> > toStringVector(NSArray* patterns)
2619 {
2620     // Convert the patterns into Vectors.
2621     NSUInteger count = [patterns count];
2622     if (count == 0)
2623         return nullptr;
2624     OwnPtr<Vector<String> > patternsVector = adoptPtr(new Vector<String>);
2625     for (NSUInteger i = 0; i < count; ++i) {
2626         id entry = [patterns objectAtIndex:i];
2627         if ([entry isKindOfClass:[NSString class]])
2628             patternsVector->append(String((NSString*)entry));
2629     }
2630     return patternsVector.release();
2631 }
2632
2633 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2634                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2635                 injectionTime:(WebUserScriptInjectionTime)injectionTime
2636 {
2637     [WebView _addUserScriptToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectionTime:injectionTime injectedFrames:WebInjectInAllFrames];
2638 }
2639
2640 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2641                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2642                 injectionTime:(WebUserScriptInjectionTime)injectionTime
2643                injectedFrames:(WebUserContentInjectedFrames)injectedFrames
2644 {
2645     String group(groupName);
2646     if (group.isEmpty())
2647         return;
2648     
2649     PageGroup* pageGroup = PageGroup::pageGroup(group);
2650     if (!pageGroup)
2651         return;
2652     
2653     pageGroup->addUserScriptToWorld(core(world), source, url, toStringVector(whitelist), toStringVector(blacklist), 
2654                                     injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd,
2655                                     injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
2656 }
2657
2658 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2659                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2660 {
2661     [WebView _addUserStyleSheetToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectedFrames:WebInjectInAllFrames];
2662 }
2663
2664 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2665                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2666                    injectedFrames:(WebUserContentInjectedFrames)injectedFrames
2667 {
2668     String group(groupName);
2669     if (group.isEmpty())
2670         return;
2671     
2672     PageGroup* pageGroup = PageGroup::pageGroup(group);
2673     if (!pageGroup)
2674         return;
2675
2676     pageGroup->addUserStyleSheetToWorld(core(world), source, url, toStringVector(whitelist), toStringVector(blacklist), injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
2677 }
2678
2679 + (void)_removeUserScriptFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2680 {
2681     String group(groupName);
2682     if (group.isEmpty())
2683         return;
2684     
2685     PageGroup* pageGroup = PageGroup::pageGroup(group);
2686     if (!pageGroup)
2687         return;
2688
2689     pageGroup->removeUserScriptFromWorld(core(world), url);
2690 }
2691
2692 + (void)_removeUserStyleSheetFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2693 {
2694     String group(groupName);
2695     if (group.isEmpty())
2696         return;
2697     
2698     PageGroup* pageGroup = PageGroup::pageGroup(group);
2699     if (!pageGroup)
2700         return;
2701
2702     pageGroup->removeUserStyleSheetFromWorld(core(world), url);
2703 }
2704
2705 + (void)_removeUserScriptsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2706 {
2707     String group(groupName);
2708     if (group.isEmpty())
2709         return;
2710     
2711     PageGroup* pageGroup = PageGroup::pageGroup(group);
2712     if (!pageGroup)
2713         return;
2714
2715     pageGroup->removeUserScriptsFromWorld(core(world));
2716 }
2717
2718 + (void)_removeUserStyleSheetsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2719 {
2720     String group(groupName);
2721     if (group.isEmpty())
2722         return;
2723     
2724     PageGroup* pageGroup = PageGroup::pageGroup(group);
2725     if (!pageGroup)
2726         return;
2727
2728     pageGroup->removeUserStyleSheetsFromWorld(core(world));
2729 }
2730
2731 + (void)_removeAllUserContentFromGroup:(NSString *)groupName
2732 {
2733     String group(groupName);
2734     if (group.isEmpty())
2735         return;
2736     
2737     PageGroup* pageGroup = PageGroup::pageGroup(group);
2738     if (!pageGroup)
2739         return;
2740     
2741     pageGroup->removeAllUserContent();
2742 }
2743
2744 - (BOOL)cssAnimationsSuspended
2745 {
2746     return _private->cssAnimationsSuspended;
2747 }
2748
2749 - (void)setCSSAnimationsSuspended:(BOOL)suspended
2750 {
2751     if (suspended == _private->cssAnimationsSuspended)
2752         return;
2753         
2754     _private->cssAnimationsSuspended = suspended;
2755     
2756     Frame* frame = core([self mainFrame]);
2757     if (suspended)
2758         frame->animation()->suspendAnimations();
2759     else
2760         frame->animation()->resumeAnimations();
2761 }
2762
2763 + (void)_setDomainRelaxationForbidden:(BOOL)forbidden forURLScheme:(NSString *)scheme
2764 {
2765     SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
2766 }
2767
2768 + (void)_registerURLSchemeAsSecure:(NSString *)scheme
2769 {
2770     SchemeRegistry::registerURLSchemeAsSecure(scheme);
2771 }
2772
2773 - (void)_scaleWebView:(float)scale atOrigin:(NSPoint)origin
2774 {
2775     Frame* coreFrame = [self _mainCoreFrame];
2776     if (!coreFrame)
2777         return;
2778
2779     coreFrame->scalePage(scale, IntPoint(origin));
2780 }
2781
2782 - (float)_viewScaleFactor
2783 {
2784     Frame* coreFrame = [self _mainCoreFrame];
2785     if (!coreFrame)
2786         return 1;
2787
2788     return coreFrame->pageScaleFactor();
2789 }
2790
2791 - (void)_setUseFixedLayout:(BOOL)fixed
2792 {
2793     Frame* coreFrame = [self _mainCoreFrame];
2794     if (!coreFrame)
2795         return;
2796
2797     FrameView* view = coreFrame->view();
2798     if (!view)
2799         return;
2800
2801     view->setUseFixedLayout(fixed);
2802     if (!fixed)
2803         view->setFixedLayoutSize(IntSize());
2804 }
2805
2806 - (void)_setFixedLayoutSize:(NSSize)size
2807 {
2808     Frame* coreFrame = [self _mainCoreFrame];
2809     if (!coreFrame)
2810         return;
2811     
2812     FrameView* view = coreFrame->view();
2813     if (!view)
2814         return;
2815     
2816     view->setFixedLayoutSize(IntSize(size));
2817     view->forceLayout();
2818 }
2819
2820 - (BOOL)_useFixedLayout
2821 {
2822     Frame* coreFrame = [self _mainCoreFrame];
2823     if (!coreFrame)
2824         return NO;
2825     
2826     FrameView* view = coreFrame->view();
2827     if (!view)
2828         return NO;
2829     
2830     return view->useFixedLayout();
2831 }
2832
2833 - (NSSize)_fixedLayoutSize
2834 {
2835     Frame* coreFrame = [self _mainCoreFrame];
2836     if (!coreFrame)
2837         return IntSize();
2838     
2839     FrameView* view = coreFrame->view();
2840     if (!view)
2841         return IntSize();
2842
2843     return view->fixedLayoutSize();
2844 }
2845
2846 - (NSUInteger)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit
2847 {
2848     return [self countMatchesForText:string options:(caseFlag ? 0 : WebFindOptionsCaseInsensitive) highlight:highlight limit:limit markMatches:YES];
2849 }
2850
2851 - (NSUInteger)countMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit markMatches:(BOOL)markMatches
2852 {
2853     return [self countMatchesForText:string options:(caseFlag ? 0 : WebFindOptionsCaseInsensitive) highlight:highlight limit:limit markMatches:markMatches];
2854 }
2855
2856 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag startInSelection:(BOOL)startInSelection
2857 {
2858     return [self findString:string options:((forward ? 0 : WebFindOptionsBackwards) | (caseFlag ? 0 : WebFindOptionsCaseInsensitive) | (wrapFlag ? WebFindOptionsWrapAround : 0) | (startInSelection ? WebFindOptionsStartInSelection : 0))];
2859 }
2860
2861 + (void)_setLoadResourcesSerially:(BOOL)serialize 
2862 {
2863     resourceLoadScheduler()->setSerialLoadingEnabled(serialize);
2864 }
2865
2866 + (double)_defaultMinimumTimerInterval
2867 {
2868     return Settings::defaultMinDOMTimerInterval();
2869 }
2870
2871 - (void)_setMinimumTimerInterval:(double)intervalInSeconds
2872 {
2873     if (_private->page)
2874         _private->page->settings()->setMinDOMTimerInterval(intervalInSeconds);
2875 }
2876
2877 + (BOOL)_HTTPPipeliningEnabled
2878 {
2879     return ResourceRequest::httpPipeliningEnabled();
2880 }
2881
2882 + (void)_setHTTPPipeliningEnabled:(BOOL)enabled
2883 {
2884     ResourceRequest::setHTTPPipeliningEnabled(enabled);
2885 }
2886
2887 @end
2888
2889 @implementation _WebSafeForwarder
2890
2891 // Used to send messages to delegates that implement informal protocols.
2892
2893 - (id)initWithTarget:(id)t defaultTarget:(id)dt catchExceptions:(BOOL)c
2894 {
2895     self = [super init];
2896     if (!self)
2897         return nil;
2898     target = t; // Non retained.
2899     defaultTarget = dt;
2900     catchExceptions = c;
2901     return self;
2902 }
2903
2904 - (void)forwardInvocation:(NSInvocation *)invocation
2905 {
2906     if ([target respondsToSelector:[invocation selector]]) {
2907         if (catchExceptions) {
2908             @try {
2909                 [invocation invokeWithTarget:target];
2910             } @catch(id exception) {
2911                 ReportDiscardedDelegateException([invocation selector], exception);
2912             }
2913         } else
2914             [invocation invokeWithTarget:target];
2915         return;
2916     }
2917
2918     if ([defaultTarget respondsToSelector:[invocation selector]])
2919         [invocation invokeWithTarget:defaultTarget];
2920
2921     // Do nothing quietly if method not implemented.
2922 }
2923
2924 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
2925 {
2926     return [defaultTarget methodSignatureForSelector:aSelector];
2927 }
2928
2929 @end
2930
2931 @implementation WebView
2932
2933 + (void)initialize
2934 {
2935     static BOOL initialized = NO;
2936     if (initialized)
2937         return;
2938     initialized = YES;
2939
2940     InitWebCoreSystemInterface();
2941     JSC::initializeThreading();
2942     WTF::initializeMainThreadToProcessMainThread();
2943
2944     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate) name:NSApplicationWillTerminateNotification object:NSApp];
2945     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:) name:WebPreferencesChangedInternalNotification object:nil];
2946     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesRemovedNotification:) name:WebPreferencesRemovedNotification object:nil];    
2947
2948     continuousSpellCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebContinuousSpellCheckingEnabled];
2949     grammarCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebGrammarCheckingEnabled];
2950
2951 #ifndef BUILDING_ON_LEOPARD
2952     automaticQuoteSubstitutionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticQuoteSubstitutionEnabled];
2953     automaticLinkDetectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticLinkDetectionEnabled];
2954     automaticDashSubstitutionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticDashSubstitutionEnabled];
2955     automaticTextReplacementEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticTextReplacementEnabled];
2956     automaticSpellingCorrectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticSpellingCorrectionEnabled];
2957 #endif
2958
2959 #if !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD)
2960     if (![[NSUserDefaults standardUserDefaults] objectForKey:WebAutomaticTextReplacementEnabled])
2961         automaticTextReplacementEnabled = [NSSpellChecker isAutomaticTextReplacementEnabled];
2962     if (![[NSUserDefaults standardUserDefaults] objectForKey:WebAutomaticSpellingCorrectionEnabled])
2963         automaticSpellingCorrectionEnabled = [NSSpellChecker isAutomaticSpellingCorrectionEnabled];
2964 #endif
2965 }
2966
2967 + (void)_applicationWillTerminate
2968 {   
2969     applicationIsTerminating = YES;
2970
2971     if (fastDocumentTeardownEnabled())
2972         [self closeAllWebViews];
2973
2974     if (!pluginDatabaseClientCount)
2975         [WebPluginDatabase closeSharedDatabase];
2976
2977     PageGroup::closeLocalStorage();
2978 }
2979
2980 + (BOOL)_canShowMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2981 {
2982     return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType allowingPlugins:allowPlugins];
2983 }
2984
2985 + (BOOL)canShowMIMEType:(NSString *)MIMEType
2986 {
2987     return [self _canShowMIMEType:MIMEType allowingPlugins:YES];
2988 }
2989
2990 - (BOOL)_canShowMIMEType:(NSString *)MIMEType
2991 {
2992     return [[self class] _canShowMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]];
2993 }
2994
2995 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
2996 {
2997     if (![_private->preferences arePlugInsEnabled])
2998         return nil;
2999
3000     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
3001     if (pluginPackage)
3002         return pluginPackage;
3003     
3004     if (_private->pluginDatabase)
3005         return [_private->pluginDatabase pluginForMIMEType:MIMEType];
3006     
3007     return nil;
3008 }
3009
3010 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
3011 - (WebBasePluginPackage *)_videoProxyPluginForMIMEType:(NSString *)MIMEType
3012 {
3013     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
3014     if (pluginPackage)
3015         return pluginPackage;
3016
3017     if (_private->pluginDatabase)
3018         return [_private->pluginDatabase pluginForMIMEType:MIMEType];
3019
3020     return nil;
3021 }
3022 #endif
3023
3024 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
3025 {
3026     if (![_private->preferences arePlugInsEnabled])
3027         return nil;
3028
3029     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForExtension:extension];
3030     if (pluginPackage)
3031         return pluginPackage;
3032     
3033     if (_private->pluginDatabase)
3034         return [_private->pluginDatabase pluginForExtension:extension];
3035     
3036     return nil;
3037 }
3038
3039 - (void)addPluginInstanceView:(NSView *)view
3040 {
3041     if (!_private->pluginDatabase)
3042         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3043     [_private->pluginDatabase addPluginInstanceView:view];
3044 }
3045
3046 - (void)removePluginInstanceView:(NSView *)view
3047 {
3048     if (_private->pluginDatabase)
3049         [_private->pluginDatabase removePluginInstanceView:view];    
3050 }
3051
3052 - (void)removePluginInstanceViewsFor:(WebFrame*)webFrame 
3053 {
3054     if (_private->pluginDatabase)
3055         [_private->pluginDatabase removePluginInstanceViewsFor:webFrame];    
3056 }
3057
3058 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
3059 {
3060     if (![_private->preferences arePlugInsEnabled])
3061         return NO;
3062
3063     if ([[WebPluginDatabase sharedDatabase] isMIMETypeRegistered:MIMEType])
3064         return YES;
3065         
3066     if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
3067         return YES;
3068     
3069     return NO;
3070 }
3071
3072 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
3073 {
3074     return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
3075 }
3076
3077 + (NSArray *)MIMETypesShownAsHTML
3078 {
3079     NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
3080     NSEnumerator *enumerator = [viewTypes keyEnumerator];
3081     id key;
3082     NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
3083     
3084     while ((key = [enumerator nextObject])) {
3085         if ([viewTypes objectForKey:key] == [WebHTMLView class])
3086             [array addObject:key];
3087     }
3088     
3089     return array;
3090 }
3091
3092 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
3093 {
3094     NSDictionary *viewTypes = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] copy];
3095     NSEnumerator *enumerator = [viewTypes keyEnumerator];
3096     id key;
3097     while ((key = [enumerator nextObject])) {
3098         if ([viewTypes objectForKey:key] == [WebHTMLView class])
3099             [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
3100     }
3101     
3102     int i, count = [MIMETypes count];
3103     for (i = 0; i < count; i++) {
3104         [WebView registerViewClass:[WebHTMLView class] 
3105                 representationClass:[WebHTMLRepresentation class] 
3106                 forMIMEType:[MIMETypes objectAtIndex:i]];
3107     }
3108     [viewTypes release];
3109 }
3110
3111 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
3112 {
3113     return [pasteboard _web_bestURL];
3114 }
3115
3116 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
3117 {
3118     return [pasteboard stringForType:WebURLNamePboardType];
3119 }
3120
3121 + (void)registerURLSchemeAsLocal:(NSString *)protocol
3122 {
3123     SchemeRegistry::registerURLSchemeAsLocal(protocol);
3124 }
3125
3126 - (id)_initWithArguments:(NSDictionary *) arguments
3127 {
3128     NSCoder *decoder = [arguments objectForKey:@"decoder"];
3129     if (decoder) {
3130         self = [self initWithCoder:decoder];
3131     } else {
3132         ASSERT([arguments objectForKey:@"frame"]);
3133         NSValue *frameValue = [arguments objectForKey:@"frame"];
3134         NSRect frame = (frameValue ? [frameValue rectValue] : NSZeroRect);
3135         NSString *frameName = [arguments objectForKey:@"frameName"];
3136         NSString *groupName = [arguments objectForKey:@"groupName"];
3137         self = [self initWithFrame:frame frameName:frameName groupName:groupName];
3138     }
3139
3140     return self;
3141 }
3142
3143 static bool clientNeedsWebViewInitThreadWorkaround()
3144 {
3145     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_WEBVIEW_INIT_THREAD_WORKAROUND))
3146         return false;
3147
3148     NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
3149
3150     // Installer.
3151     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.installer"])
3152         return true;
3153
3154     // Automator.
3155     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Automator"])
3156         return true;
3157
3158     // Automator Runner.
3159     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.AutomatorRunner"])
3160         return true;
3161
3162     // Automator workflows.
3163     if ([bundleIdentifier _webkit_hasCaseInsensitivePrefix:@"com.apple.Automator."])
3164         return true;
3165
3166 #ifdef BUILDING_ON_LEOPARD
3167     // Mail.
3168     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Mail"])
3169         return true;
3170 #endif
3171
3172     return false;
3173 }
3174
3175 static bool needsWebViewInitThreadWorkaround()
3176 {
3177     static bool isOldClient = clientNeedsWebViewInitThreadWorkaround();
3178     return isOldClient && !pthread_main_np();
3179 }
3180
3181 - (id)initWithFrame:(NSRect)f
3182 {
3183     return [self initWithFrame:f frameName:nil groupName:nil];
3184 }
3185
3186 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
3187 {
3188     if (needsWebViewInitThreadWorkaround())
3189         return [[self _webkit_invokeOnMainThread] initWithFrame:f frameName:frameName groupName:groupName];
3190
3191     WebCoreThreadViolationCheckRoundTwo();
3192     return [self _initWithFrame:f frameName:frameName groupName:groupName usesDocumentViews:YES];
3193 }
3194
3195 - (id)initWithCoder:(NSCoder *)decoder
3196 {
3197     if (needsWebViewInitThreadWorkaround())
3198         return [[self _webkit_invokeOnMainThread] initWithCoder:decoder];
3199
3200     WebCoreThreadViolationCheckRoundTwo();
3201     WebView *result = nil;
3202
3203     @try {
3204         NSString *frameName;
3205         NSString *groupName;
3206         WebPreferences *preferences;
3207         BOOL useBackForwardList = NO;
3208         BOOL allowsUndo = YES;
3209         
3210         result = [super initWithCoder:decoder];
3211         result->_private = [[WebViewPrivate alloc] init];
3212
3213         // We don't want any of the archived subviews. The subviews will always
3214         // be created in _commonInitializationFrameName:groupName:.
3215         [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
3216
3217         if ([decoder allowsKeyedCoding]) {
3218             frameName = [decoder decodeObjectForKey:@"FrameName"];
3219             groupName = [decoder decodeObjectForKey:@"GroupName"];
3220             preferences = [decoder decodeObjectForKey:@"Preferences"];
3221             useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
3222             if ([decoder containsValueForKey:@"AllowsUndo"])
3223                 allowsUndo = [decoder decodeBoolForKey:@"AllowsUndo"];
3224         } else {
3225             int version;
3226             [decoder decodeValueOfObjCType:@encode(int) at:&version];
3227             frameName = [decoder decodeObject];
3228             groupName = [decoder decodeObject];
3229             preferences = [decoder decodeObject];
3230             if (version > 1)
3231                 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
3232             // The allowsUndo field is no longer written out in encodeWithCoder, but since there are
3233             // version 3 NIBs that have this field encoded, we still need to read it in.
3234             if (version == 3)
3235                 [decoder decodeValuesOfObjCTypes:"c", &allowsUndo];
3236         }
3237
3238         if (![frameName isKindOfClass:[NSString class]])
3239             frameName = nil;
3240         if (![groupName isKindOfClass:[NSString class]])
3241             groupName = nil;
3242         if (![preferences isKindOfClass:[WebPreferences class]])
3243             preferences = nil;
3244
3245         LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
3246         [result _commonInitializationWithFrameName:frameName groupName:groupName usesDocumentViews:YES];
3247         static_cast<BackForwardListImpl*>([result page]->backForwardList())->setEnabled(useBackForwardList);
3248         result->_private->allowsUndo = allowsUndo;
3249         if (preferences)
3250             [result setPreferences:preferences];
3251     } @catch (NSException *localException) {
3252         result = nil;
3253         [self release];
3254     }
3255
3256     return result;
3257 }
3258
3259 - (void)encodeWithCoder:(NSCoder *)encoder
3260 {
3261     // Set asside the subviews before we archive. We don't want to archive any subviews.
3262     // The subviews will always be created in _commonInitializationFrameName:groupName:.
3263     id originalSubviews = _subviews;
3264     _subviews = nil;
3265
3266     [super encodeWithCoder:encoder];
3267
3268     // Restore the subviews we set aside.
3269     _subviews = originalSubviews;
3270
3271     BOOL useBackForwardList = _private->page && static_cast<BackForwardListImpl*>(_private->page->backForwardList())->enabled();
3272     if ([encoder allowsKeyedCoding]) {
3273         [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
3274         [encoder encodeObject:[self groupName] forKey:@"GroupName"];
3275         [encoder encodeObject:[self preferences] forKey:@"Preferences"];
3276         [encoder encodeBool:useBackForwardList forKey:@"UseBackForwardList"];
3277         [encoder encodeBool:_private->allowsUndo forKey:@"AllowsUndo"];
3278     } else {
3279         int version = WebViewVersion;
3280         [encoder encodeValueOfObjCType:@encode(int) at:&version];
3281         [encoder encodeObject:[[self mainFrame] name]];
3282         [encoder encodeObject:[self groupName]];
3283         [encoder encodeObject:[self preferences]];
3284         [encoder encodeValuesOfObjCTypes:"c", &useBackForwardList];
3285         // DO NOT encode any new fields here, doing so will break older WebKit releases.
3286     }
3287
3288     LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)useBackForwardList);
3289 }
3290
3291 - (void)dealloc
3292 {
3293     if (WebCoreObjCScheduleDeallocateOnMainThread([WebView class], self))
3294         return;
3295
3296     // call close to ensure we tear-down completely
3297     // this maintains our old behavior for existing applications
3298     [self close];
3299
3300     if ([[self class] shouldIncludeInWebKitStatistics])
3301         --WebViewCount;
3302
3303     if ([self _needsFrameLoadDelegateRetainQuirk])
3304         [_private->frameLoadDelegate release];
3305         
3306     [_private release];
3307     // [super dealloc] can end up dispatching against _private (3466082)
3308     _private = nil;
3309
3310     [super dealloc];
3311 }
3312
3313 - (void)finalize
3314 {
3315     ASSERT(_private->closed);
3316
3317     --WebViewCount;
3318
3319     [super finalize];
3320 }
3321
3322 - (void)close
3323 {
3324     // _close existed first, and some clients might be calling or overriding it, so call through.
3325     [self _close];
3326 }
3327
3328 - (void)setShouldCloseWithWindow:(BOOL)close
3329 {
3330     _private->shouldCloseWithWindow = close;
3331 }
3332
3333 - (BOOL)shouldCloseWithWindow
3334 {
3335     return _private->shouldCloseWithWindow;
3336 }
3337
3338 - (void)addWindowObserversForWindow:(NSWindow *)window
3339 {
3340     if (window) {
3341         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
3342             name:NSWindowDidBecomeKeyNotification object:nil];
3343         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
3344             name:NSWindowDidResignKeyNotification object:nil];
3345         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillOrderOnScreen:)
3346             name:WKWindowWillOrderOnScreenNotification() object:window];
3347     }
3348 }
3349
3350 - (void)removeWindowObservers
3351 {
3352     NSWindow *window = [self window];
3353     if (window) {
3354         [[NSNotificationCenter defaultCenter] removeObserver:self
3355             name:NSWindowDidBecomeKeyNotification object:nil];
3356         [[NSNotificationCenter defaultCenter] removeObserver:self
3357             name:NSWindowDidResignKeyNotification object:nil];
3358         [[NSNotificationCenter defaultCenter] removeObserver:self
3359             name:WKWindowWillOrderOnScreenNotification() object:window];
3360     }
3361 }
3362
3363 - (void)viewWillMoveToWindow:(NSWindow *)window
3364 {
3365     // Don't do anything if the WebView isn't initialized.
3366     // This happens when decoding a WebView in a nib.
3367     // FIXME: What sets up the observer of NSWindowWillCloseNotification in this case?
3368     if (!_private || _private->closed)
3369         return;
3370     
3371     if ([self window] && [self window] != [self hostWindow])
3372         [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
3373
3374     if (window) {
3375         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
3376          
3377         // Ensure that we will receive the events that WebHTMLView (at least) needs.
3378         // The following are expensive enough that we don't want to call them over
3379         // and over, so do them when we move into a window.
3380         [window setAcceptsMouseMovedEvents:YES];
3381         WKSetNSWindowShouldPostEventNotifications(window, YES);
3382     } else {
3383         _private->page->setCanStartMedia(false);
3384         _private->page->willMoveOffscreen();
3385     }
3386         
3387     if (window != [self window]) {
3388         [self removeWindowObservers];
3389         [self addWindowObserversForWindow:window];
3390     }
3391 }
3392
3393 - (void)viewDidMoveToWindow
3394 {
3395     // Don't do anything if we aren't initialized.  This happens
3396     // when decoding a WebView.  When WebViews are decoded their subviews
3397     // are created by initWithCoder: and so won't be normally
3398     // initialized.  The stub views are discarded by WebView.
3399     if (!_private || _private->closed)
3400         return;
3401
3402     if ([self window]) {
3403         _private->page->setCanStartMedia(true);
3404         _private->page->didMoveOnscreen();
3405     }
3406     
3407     [self _updateActiveState];
3408 }
3409
3410 - (void)_windowDidBecomeKey:(NSNotification *)notification
3411 {
3412     NSWindow *keyWindow = [notification object];
3413     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
3414         [self _updateActiveState];
3415 }
3416
3417 - (void)_windowDidResignKey:(NSNotification *)notification
3418 {
3419     NSWindow *formerKeyWindow = [notification object];
3420     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet])
3421         [self _updateActiveState];
3422 }
3423
3424 - (void)_windowWillOrderOnScreen:(NSNotification *)notification
3425 {
3426     if (![self shouldUpdateWhileOffscreen])
3427         [self setNeedsDisplay:YES];
3428 }
3429
3430 - (void)_windowWillClose:(NSNotification *)notification
3431 {
3432     if ([self shouldCloseWithWindow] && ([self window] == [self hostWindow] || ([self window] && ![self hostWindow]) || (![self window] && [self hostWindow])))
3433         [self close];
3434 }
3435
3436 - (void)setPreferences:(WebPreferences *)prefs
3437 {
3438     if (!prefs)
3439         prefs = [WebPreferences standardPreferences];
3440
3441     if (_private->preferences == prefs)
3442         return;
3443
3444     [prefs willAddToWebView];
3445
3446     WebPreferences *oldPrefs = _private->preferences;
3447
3448     [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedInternalNotification object:[self preferences]];
3449     [WebPreferences _removeReferenceForIdentifier:[oldPrefs identifier]];
3450
3451     _private->preferences = [prefs retain];
3452
3453     // After registering for the notification, post it so the WebCore settings update.
3454     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
3455         name:WebPreferencesChangedInternalNotification object:[self preferences]];
3456     [self _preferencesChanged:[self preferences]];
3457     [[self preferences] _postPreferencesChangedAPINotification];
3458
3459     [oldPrefs didRemoveFromWebView];
3460     [oldPrefs release];
3461 }
3462
3463 - (WebPreferences *)preferences
3464 {
3465     return _private->preferences;
3466 }
3467
3468 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
3469 {
3470     if (!_private->closed && ![anIdentifier isEqual:[[self preferences] identifier]]) {
3471         WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
3472         [self setPreferences:prefs];
3473         [prefs release];
3474     }
3475 }
3476
3477 - (NSString *)preferencesIdentifier
3478 {
3479     return [[self preferences] identifier];
3480 }
3481
3482
3483 - (void)setUIDelegate:delegate
3484 {
3485     _private->UIDelegate = delegate;
3486     [_private->UIDelegateForwarder release];
3487     _private->UIDelegateForwarder = nil;
3488 }
3489
3490 - (id)UIDelegate
3491 {
3492     return _private->UIDelegate;
3493 }
3494
3495 - (void)setResourceLoadDelegate: delegate
3496 {
3497     _private->resourceProgressDelegate = delegate;
3498     [self _cacheResourceLoadDelegateImplementations];
3499 }
3500
3501 - (id)resourceLoadDelegate
3502 {
3503     return _private->resourceProgressDelegate;
3504 }
3505
3506 - (void)setDownloadDelegate: delegate
3507 {
3508     _private->downloadDelegate = delegate;
3509 }
3510
3511
3512 - (id)downloadDelegate
3513 {
3514     return _private->downloadDelegate;
3515 }
3516
3517 - (void)setPolicyDelegate:delegate
3518 {
3519     _private->policyDelegate = delegate;
3520     [_private->policyDelegateForwarder release];
3521     _private->policyDelegateForwarder = nil;
3522 }
3523
3524 - (id)policyDelegate
3525 {
3526     return _private->policyDelegate;
3527 }
3528
3529 - (void)setFrameLoadDelegate:delegate
3530 {
3531     // <rdar://problem/6950660> - Due to some subtle WebKit changes - presumably to delegate callback behavior - we've
3532     // unconvered a latent bug in at least one WebKit app where the delegate wasn't properly retained by the app and
3533     // was dealloc'ed before being cleared.
3534     // This is an effort to keep such apps working for now.
3535     if ([self _needsFrameLoadDelegateRetainQuirk]) {
3536         [delegate retain];
3537         [_private->frameLoadDelegate release];
3538     }
3539     
3540     _private->frameLoadDelegate = delegate;
3541     [self _cacheFrameLoadDelegateImplementations];
3542
3543 #if ENABLE(ICONDATABASE)
3544     // If this delegate wants callbacks for icons, fire up the icon database.
3545     if (_private->frameLoadDelegateImplementations.didReceiveIconForFrameFunc)
3546         [WebIconDatabase sharedIconDatabase];
3547 #endif
3548 }
3549
3550 - (id)frameLoadDelegate
3551 {
3552     return _private->frameLoadDelegate;
3553 }
3554
3555 - (WebFrame *)mainFrame
3556 {
3557     // This can be called in initialization, before _private has been set up (3465613)
3558     if (!_private || !_private->page)
3559         return nil;
3560     return kit(_private->page->mainFrame());
3561 }
3562
3563 - (WebFrame *)selectedFrame
3564 {
3565     if (_private->usesDocumentViews) {
3566         // If the first responder is a view in our tree, we get the frame containing the first responder.
3567         // This is faster than searching the frame hierarchy, and will give us a result even in the case
3568         // where the focused frame doesn't actually contain a selection.
3569         WebFrame *focusedFrame = [self _focusedFrame];
3570         if (focusedFrame)
3571             return focusedFrame;
3572     }
3573     
3574     // If the first responder is outside of our view tree, we search for a frame containing a selection.
3575     // There should be at most only one of these.
3576     return [[self mainFrame] _findFrameWithSelection];
3577 }
3578
3579 - (WebBackForwardList *)backForwardList
3580 {
3581     if (!_private->page)
3582         return nil;
3583     BackForwardListImpl* list = static_cast<BackForwardListImpl*>(_private->page->backForwardList());
3584     if (!list->enabled())
3585         return nil;
3586     return kit(list);
3587 }
3588
3589 - (void)setMaintainsBackForwardList:(BOOL)flag
3590 {
3591     if (!_private->page)
3592         return;
3593     static_cast<BackForwardListImpl*>(_private->page->backForwardList())->setEnabled(flag);
3594 }
3595
3596 - (BOOL)goBack
3597 {
3598     if (!_private->page)
3599         return NO;
3600     
3601     return _private->page->goBack();
3602 }
3603
3604 - (BOOL)goForward
3605 {
3606     if (!_private->page)
3607         return NO;
3608
3609     return _private->page->goForward();
3610 }