9ee55ccb53b2ab6693b89c11d3e2635ffe67ca15
[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)canCloseAllWebViews
1075 {
1076     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1077 }
1078
1079 + (void)closeAllWebViews
1080 {
1081     DOMWindow::dispatchAllPendingUnloadEvents();
1082
1083     // This will close the WebViews in a random order. Change this if close order is important.
1084     // Make a new set to avoid mutating the set we are enumerating.
1085     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
1086     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1087     while (WebView *webView = [enumerator nextObject])
1088         [webView close];
1089 }
1090
1091 + (BOOL)canShowFile:(NSString *)path
1092 {
1093     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1094 }
1095
1096 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1097 {
1098     return WKGetPreferredExtensionForMIMEType(type);
1099 }
1100
1101 - (BOOL)_isClosed
1102 {
1103     return !_private || _private->closed;
1104 }
1105
1106 - (void)_closePluginDatabases
1107 {
1108     pluginDatabaseClientCount--;
1109
1110     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1111
1112     // Unload the WebView local plug-in database. 
1113     if (_private->pluginDatabase) {
1114         [_private->pluginDatabase destroyAllPluginInstanceViews];
1115         [_private->pluginDatabase close];
1116         [_private->pluginDatabase release];
1117         _private->pluginDatabase = nil;
1118     }
1119     
1120     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1121     if (!pluginDatabaseClientCount && applicationIsTerminating)
1122         [WebPluginDatabase closeSharedDatabase];
1123 }
1124
1125 - (void)_closeWithFastTeardown 
1126 {
1127 #ifndef NDEBUG
1128     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1129 #endif
1130
1131     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1132     [[NSNotificationCenter defaultCenter] removeObserver:self];
1133
1134     [self _closePluginDatabases];
1135 }
1136
1137 static bool fastDocumentTeardownEnabled()
1138 {
1139 #ifdef NDEBUG
1140     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1141 #else
1142     static bool initialized = false;
1143     static bool enabled = false;
1144     if (!initialized) {
1145         // This allows debug builds to default to not have fast teardown, so leak checking still works.
1146         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1147         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1148         if (setting)
1149             enabled = ![setting boolValue];
1150         initialized = true;
1151     }
1152 #endif
1153     return enabled;
1154 }
1155
1156 // _close is here only for backward compatibility; clients and subclasses should use
1157 // public method -close instead.
1158 - (void)_close
1159 {
1160     if (!_private || _private->closed)
1161         return;
1162
1163     _private->closed = YES;
1164     [self _removeFromAllWebViewsSet];
1165
1166     [self _closingEventHandling];
1167
1168 #ifndef NDEBUG
1169     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1170 #endif
1171
1172     // To quit the apps fast we skip document teardown, except plugins
1173     // need to be destroyed and unloaded.
1174     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1175         [self _closeWithFastTeardown];
1176         return;
1177     }
1178
1179 #if ENABLE(VIDEO)
1180     [self _exitFullscreen];
1181 #endif
1182
1183     if (Frame* mainFrame = [self _mainCoreFrame])
1184         mainFrame->loader()->detachFromParent();
1185
1186     [self setHostWindow:nil];
1187
1188     [self setDownloadDelegate:nil];
1189     [self setEditingDelegate:nil];
1190     [self setFrameLoadDelegate:nil];
1191     [self setPolicyDelegate:nil];
1192     [self setResourceLoadDelegate:nil];
1193     [self setScriptDebugDelegate:nil];
1194     [self setUIDelegate:nil];
1195
1196     [_private->inspector webViewClosed];
1197
1198     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1199     [self removeDragCaret];
1200
1201     // Deleteing the WebCore::Page will clear the page cache so we call destroy on 
1202     // all the plug-ins in the page cache to break any retain cycles.
1203     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1204     Page* page = _private->page;
1205     _private->page = 0;
1206     delete page;
1207
1208     if (_private->hasSpellCheckerDocumentTag) {
1209         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1210         _private->hasSpellCheckerDocumentTag = NO;
1211     }
1212
1213 #if USE(ACCELERATED_COMPOSITING)
1214     [self _clearLayerSyncLoopObserver];
1215 #endif
1216     
1217 #if ENABLE(GLIB_SUPPORT)
1218     [self _clearGlibLoopObserver];
1219 #endif
1220
1221     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1222     [[NSNotificationCenter defaultCenter] removeObserver:self];
1223
1224     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1225
1226     WebPreferences *preferences = _private->preferences;
1227     _private->preferences = nil;
1228     [preferences didRemoveFromWebView];
1229     [preferences release];
1230
1231     [self _closePluginDatabases];
1232
1233 #ifndef NDEBUG
1234     // Need this to make leak messages accurate.
1235     if (applicationIsTerminating) {
1236         gcController().garbageCollectNow();
1237         [WebCache setDisabled:YES];
1238     }
1239 #endif
1240 }
1241
1242 // Indicates if the WebView is in the midst of a user gesture.
1243 - (BOOL)_isProcessingUserGesture
1244 {
1245     return ScriptController::processingUserGesture();
1246 }
1247
1248 + (NSString *)_MIMETypeForFile:(NSString *)path
1249 {
1250     NSString *extension = [path pathExtension];
1251     NSString *MIMEType = nil;
1252
1253     // Get the MIME type from the extension.
1254     if ([extension length] != 0) {
1255         MIMEType = WKGetMIMETypeForExtension(extension);
1256     }
1257
1258     // If we can't get a known MIME type from the extension, sniff.
1259     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1260         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1261         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1262         [handle closeFile];
1263         if ([data length] != 0) {
1264             MIMEType = [data _webkit_guessedMIMEType];
1265         }
1266         if ([MIMEType length] == 0) {
1267             MIMEType = @"application/octet-stream";
1268         }
1269     }
1270
1271     return MIMEType;
1272 }
1273
1274 - (WebDownload *)_downloadURL:(NSURL *)URL
1275 {
1276     ASSERT(URL);
1277     
1278     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1279     WebDownload *download = [WebDownload _downloadWithRequest:request
1280                                                      delegate:_private->downloadDelegate
1281                                                     directory:nil];
1282     [request release];
1283     
1284     return download;
1285 }
1286
1287 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1288 {
1289     NSDictionary *features = [[NSDictionary alloc] init];
1290     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1291                                             createWebViewWithRequest:nil
1292                                                       windowFeatures:features];
1293     [features release];
1294     if (!newWindowWebView)
1295         return nil;
1296
1297     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1298     return newWindowWebView;
1299 }
1300
1301 - (WebInspector *)inspector
1302 {
1303     if (!_private->inspector)
1304         _private->inspector = [[WebInspector alloc] initWithWebView:self];
1305     return _private->inspector;
1306 }
1307
1308 - (WebCore::Page*)page
1309 {
1310     return _private->page;
1311 }
1312
1313 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1314 {
1315     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1316     NSArray *menuItems = defaultMenuItems;
1317
1318     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
1319     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
1320     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
1321     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1322         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
1323         if (!menuItems)
1324             return nil;
1325     }
1326
1327     unsigned count = [menuItems count];
1328     if (!count)
1329         return nil;
1330
1331     NSMenu *menu = [[NSMenu alloc] init];
1332     for (unsigned i = 0; i < count; i++)
1333         [menu addItem:[menuItems objectAtIndex:i]];
1334
1335     return [menu autorelease];
1336 }
1337
1338 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1339 {
1340     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1341     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1342     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1343     if (!dictionary)
1344         return;
1345     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1346 }
1347
1348 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1349 {
1350     if (!_private->page)
1351         return;
1352     
1353     if (!otherView->_private->page)
1354         return;
1355     
1356     // It turns out the right combination of behavior is done with the back/forward load
1357     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
1358     // in the back forward list, and go to the current one.
1359
1360     BackForwardList* backForwardList = _private->page->backForwardList();
1361     ASSERT(!backForwardList->currentItem()); // destination list should be empty
1362
1363     BackForwardList* otherBackForwardList = otherView->_private->page->backForwardList();
1364     if (!otherBackForwardList->currentItem())
1365         return; // empty back forward list, bail
1366     
1367     HistoryItem* newItemToGoTo = 0;
1368
1369     int lastItemIndex = otherBackForwardList->forwardListCount();
1370     for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
1371         if (i == 0) {
1372             // If this item is showing , save away its current scroll and form state,
1373             // since that might have changed since loading and it is normally not saved
1374             // until we leave that page.
1375             otherView->_private->page->mainFrame()->loader()->history()->saveDocumentAndScrollState();
1376         }
1377         RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
1378         if (i == 0) 
1379             newItemToGoTo = newItem.get();
1380         backForwardList->addItem(newItem.release());
1381     }
1382     
1383     ASSERT(newItemToGoTo);
1384     _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
1385 }
1386
1387 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
1388 {
1389     _private->formDelegate = delegate;
1390 }
1391
1392 - (id<WebFormDelegate>)_formDelegate
1393 {
1394     return _private->formDelegate;
1395 }
1396
1397 - (BOOL)_needsAdobeFrameReloadingQuirk
1398 {
1399     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
1400         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
1401         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
1402         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
1403         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
1404         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
1405         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
1406         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
1407         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
1408         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
1409
1410     return needsQuirk;
1411 }
1412
1413 - (BOOL)_needsLinkElementTextCSSQuirk
1414 {
1415     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
1416         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
1417     return needsQuirk;
1418 }
1419
1420 - (BOOL)_needsKeyboardEventDisambiguationQuirks
1421 {
1422     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
1423     return needsQuirks;
1424 }
1425
1426 - (BOOL)_needsFrameLoadDelegateRetainQuirk
1427 {
1428     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
1429     return needsQuirk;
1430 }
1431
1432 static bool needsSelfRetainWhileLoadingQuirk()
1433 {
1434     static bool needsQuirk = applicationIsAperture();
1435     return needsQuirk;
1436 }
1437
1438 - (BOOL)_needsPreHTML5ParserQuirks
1439 {    
1440     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
1441     // with the new HTML5 parser. If these applications were linked against a
1442     // version of WebKit prior to the introduction of the HTML5 parser, enable
1443     // parser quirks to maintain compatibility. For details, see 
1444     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
1445     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
1446     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1447         && (applicationIsAOLInstantMessenger() || applicationIsMicrosoftMyDay());
1448     
1449     // Mail.app must continue to display HTML email that contains quirky markup.
1450     static bool isAppleMail = applicationIsAppleMail();
1451
1452     return isApplicationNeedingParserQuirks
1453         || isAppleMail
1454 #if ENABLE(DASHBOARD_SUPPORT)
1455         // Pre-HTML5 parser quirks are required to remain compatible with many
1456         // Dashboard widgets. See <rdar://problem/8175982>.
1457         || (_private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode())
1458 #endif
1459         || [[self preferences] usePreHTML5ParserQuirks];
1460 }
1461
1462 - (BOOL)_needsUnrestrictedGetMatchedCSSRules
1463 {
1464     static bool needsUnrestrictedGetMatchedCSSRules = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_GET_MATCHED_CSS_RULES_RESTRICTIONS) && applicationIsSafari();
1465     return needsUnrestrictedGetMatchedCSSRules;
1466 }
1467
1468 - (void)_preferencesChangedNotification:(NSNotification *)notification
1469 {
1470     WebPreferences *preferences = (WebPreferences *)[notification object];
1471     [self _preferencesChanged:preferences];
1472 }
1473
1474 - (void)_preferencesChanged:(WebPreferences *)preferences
1475 {    
1476     ASSERT(preferences == [self preferences]);
1477     if (!_private->userAgentOverridden)
1478         _private->userAgent = String();
1479
1480     // Cache this value so we don't have to read NSUserDefaults on each page load
1481     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
1482
1483     // Update corresponding WebCore Settings object.
1484     if (!_private->page)
1485         return;
1486     
1487     Settings* settings = _private->page->settings();
1488     
1489     settings->setCursiveFontFamily([preferences cursiveFontFamily]);
1490     settings->setDefaultFixedFontSize([preferences defaultFixedFontSize]);
1491     settings->setDefaultFontSize([preferences defaultFontSize]);
1492     settings->setDefaultTextEncodingName([preferences defaultTextEncodingName]);
1493     settings->setUsesEncodingDetector([preferences usesEncodingDetector]);
1494     settings->setFantasyFontFamily([preferences fantasyFontFamily]);
1495     settings->setFixedFontFamily([preferences fixedFontFamily]);
1496     settings->setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
1497     settings->setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
1498     settings->setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
1499     settings->setJavaEnabled([preferences isJavaEnabled]);
1500     settings->setJavaScriptEnabled([preferences isJavaScriptEnabled]);
1501     settings->setWebSecurityEnabled([preferences isWebSecurityEnabled]);
1502     settings->setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
1503     settings->setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
1504     settings->setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
1505     settings->setMinimumFontSize([preferences minimumFontSize]);
1506     settings->setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
1507     settings->setPluginsEnabled([preferences arePlugInsEnabled]);
1508 #if ENABLE(DATABASE)
1509     AbstractDatabase::setIsAvailable([preferences databasesEnabled]);
1510 #endif
1511     settings->setLocalStorageEnabled([preferences localStorageEnabled]);
1512     settings->setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
1513     settings->setPrivateBrowsingEnabled([preferences privateBrowsingEnabled]);
1514     settings->setSansSerifFontFamily([preferences sansSerifFontFamily]);
1515     settings->setSerifFontFamily([preferences serifFontFamily]);
1516     settings->setStandardFontFamily([preferences standardFontFamily]);
1517     settings->setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
1518     settings->setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
1519     settings->setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
1520     settings->setTextAreasAreResizable([preferences textAreasAreResizable]);
1521     settings->setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
1522     settings->setEditableLinkBehavior(core([preferences editableLinkBehavior]));
1523     settings->setEditingBehaviorType(core([preferences editingBehavior]));
1524     settings->setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
1525     settings->setDOMPasteAllowed([preferences isDOMPasteAllowed]);
1526     settings->setUsesPageCache([self usesPageCache]);
1527     settings->setShowsURLsInToolTips([preferences showsURLsInToolTips]);
1528     settings->setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
1529     settings->setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
1530     settings->setApplicationChromeMode([preferences applicationChromeModeEnabled]);
1531     if ([preferences userStyleSheetEnabled]) {
1532         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
1533         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
1534             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
1535         settings->setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
1536     } else
1537         settings->setUserStyleSheetLocation([NSURL URLWithString:@""]);
1538     settings->setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
1539     settings->setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
1540     settings->setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
1541     settings->setNeedsLeopardMailQuirks(runningLeopardMail());
1542     settings->setNeedsTigerMailQuirks(runningTigerMail());
1543     settings->setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
1544     settings->setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
1545     settings->setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
1546     settings->setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
1547     settings->setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
1548     settings->setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
1549     settings->setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
1550     settings->setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
1551     
1552     // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
1553     // Until we fix that, I will comment out the test (CFM)
1554     settings->setAcceleratedCompositingEnabled((coreVideoHas7228836Fix() || [preferences webGLEnabled] || 
1555         [preferences accelerated2dCanvasEnabled]) && [preferences acceleratedCompositingEnabled]);
1556     settings->setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1557     settings->setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);    
1558     settings->setShowDebugBorders([preferences showDebugBorders]);
1559     settings->setShowRepaintCounter([preferences showRepaintCounter]);
1560     settings->setPluginAllowedRunTime([preferences pluginAllowedRunTime]);
1561     settings->setWebAudioEnabled([preferences webAudioEnabled]);
1562     settings->setWebGLEnabled([preferences webGLEnabled]);
1563     settings->setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
1564     settings->setLoadDeferringEnabled(shouldEnableLoadDeferring());
1565     settings->setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
1566     settings->setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
1567     settings->setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
1568 #if ENABLE(FULLSCREEN_API)
1569     settings->setFullScreenEnabled([preferences fullScreenEnabled]);
1570 #endif
1571 #ifndef BUILDING_ON_LEOPARD
1572     // Asynchronous spell checking API is available for 10.6 or later.
1573     settings->setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
1574 #endif
1575     settings->setMemoryInfoEnabled([preferences memoryInfoEnabled]);
1576     settings->setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
1577     settings->setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
1578     settings->setCrossOriginCheckInGetMatchedCSSRulesDisabled([self _needsUnrestrictedGetMatchedCSSRules]);
1579     settings->setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
1580     settings->setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
1581 #if USE(AVFOUNDATION)
1582 #if ENABLE(FULLSCREEN_API)
1583     settings->setAVFoundationEnabled([preferences isAVFoundationEnabled] && [preferences fullScreenEnabled]);
1584 #else
1585     settings->setAVFoundationEnabled(false);
1586 #endif
1587 #endif
1588 #if ENABLE(WEB_SOCKETS)
1589     settings->setUseHixie76WebSocketProtocol([preferences isHixie76WebSocketProtocolEnabled]);
1590 #endif
1591
1592     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
1593     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
1594
1595     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
1596     if (_private->zoomsTextOnly != zoomsTextOnly)
1597         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
1598 }
1599
1600 static inline IMP getMethod(id o, SEL s)
1601 {
1602     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
1603 }
1604
1605 - (void)_cacheResourceLoadDelegateImplementations
1606 {
1607     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
1608     id delegate = _private->resourceProgressDelegate;
1609
1610     if (!delegate) {
1611         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
1612         return;
1613     }
1614
1615     cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
1616     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
1617     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
1618     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
1619     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1620 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
1621     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
1622 #endif
1623     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
1624     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
1625     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
1626     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
1627     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
1628     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
1629     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
1630     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
1631 }
1632
1633 - (void)_cacheFrameLoadDelegateImplementations
1634 {
1635     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
1636     id delegate = _private->frameLoadDelegate;
1637
1638     if (!delegate) {
1639         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
1640         return;
1641     }
1642
1643     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
1644     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
1645     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
1646     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
1647     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
1648     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
1649     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
1650     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
1651     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
1652     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
1653     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
1654     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
1655     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
1656     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
1657     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
1658     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
1659     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
1660     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
1661     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
1662     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
1663     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
1664     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
1665     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
1666     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
1667     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
1668 }
1669
1670 - (void)_cacheScriptDebugDelegateImplementations
1671 {
1672     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
1673     id delegate = _private->scriptDebugDelegate;
1674
1675     if (!delegate) {
1676         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
1677         return;
1678     }
1679
1680     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
1681     if (cache->didParseSourceFunc)
1682         cache->didParseSourceExpectsBaseLineNumber = YES;
1683     else {
1684         cache->didParseSourceExpectsBaseLineNumber = NO;
1685         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
1686     }
1687
1688     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
1689     cache->didEnterCallFrameFunc = getMethod(delegate, @selector(webView:didEnterCallFrame:sourceId:line:forWebFrame:));
1690     cache->willExecuteStatementFunc = getMethod(delegate, @selector(webView:willExecuteStatement:sourceId:line:forWebFrame:));
1691     cache->willLeaveCallFrameFunc = getMethod(delegate, @selector(webView:willLeaveCallFrame:sourceId:line:forWebFrame:));
1692
1693     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
1694     if (cache->exceptionWasRaisedFunc)
1695         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
1696     else {
1697         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
1698         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
1699     }
1700 }
1701
1702 - (void)_cacheHistoryDelegateImplementations
1703 {
1704     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
1705     id delegate = _private->historyDelegate;
1706
1707     if (!delegate) {
1708         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
1709         return;
1710     }
1711
1712     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
1713     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
1714     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
1715     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
1716     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
1717 }
1718
1719 - (id)_policyDelegateForwarder
1720 {
1721     if (!_private->policyDelegateForwarder)
1722         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate] catchExceptions:_private->catchesDelegateExceptions];
1723     return _private->policyDelegateForwarder;
1724 }
1725
1726 - (id)_UIDelegateForwarder
1727 {
1728     if (!_private->UIDelegateForwarder)
1729         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate] catchExceptions:_private->catchesDelegateExceptions];
1730     return _private->UIDelegateForwarder;
1731 }
1732
1733 - (id)_editingDelegateForwarder
1734 {
1735     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
1736     // Not sure if that is a bug or not.
1737     if (!_private)
1738         return nil;
1739
1740     if (!_private->editingDelegateForwarder)
1741         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate] catchExceptions:_private->catchesDelegateExceptions];
1742     return _private->editingDelegateForwarder;
1743 }
1744
1745 - (void)_closeWindow
1746 {
1747     [[self _UIDelegateForwarder] webViewClose:self];
1748 }
1749
1750 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
1751 {
1752     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1753     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1754     
1755     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1756     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
1757     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1758     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
1759 }
1760
1761 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
1762 {
1763     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
1764     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1765
1766     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1767     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
1768     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1769     if ([viewClass class] == [WebHTMLView class])
1770         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
1771     
1772     // This is used to make _representationExistsForURLScheme faster.
1773     // Without this set, we'd have to create the MIME type each time.
1774     if (schemesWithRepresentationsSet == nil) {
1775         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1776     }
1777     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1778 }
1779
1780 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1781 {
1782     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1783 }
1784
1785 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1786 {
1787     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1788 }
1789
1790 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
1791 {
1792     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
1793     if (!request)
1794         return NO;
1795
1796     if ([NSURLConnection canHandleRequest:request])
1797         return YES;
1798
1799     NSString *scheme = [[request URL] scheme];
1800
1801     // Representations for URL schemes work at the top level.
1802     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
1803         return YES;
1804         
1805     return [scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"];
1806 }
1807
1808 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1809 {
1810     return [self _canHandleRequest:request forMainFrame:YES];
1811 }
1812
1813 + (NSString *)_decodeData:(NSData *)data
1814 {
1815     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
1816     RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("text/html"); // bookmark files are HTML
1817     String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
1818     result += decoder->flush();
1819     return result;
1820 }
1821
1822 - (void)_pushPerformingProgrammaticFocus
1823 {
1824     _private->programmaticFocusCount++;
1825 }
1826
1827 - (void)_popPerformingProgrammaticFocus
1828 {
1829     _private->programmaticFocusCount--;
1830 }
1831
1832 - (BOOL)_isPerformingProgrammaticFocus
1833 {
1834     return _private->programmaticFocusCount != 0;
1835 }
1836
1837 - (void)_didChangeValueForKey: (NSString *)key
1838 {
1839     LOG (Bindings, "calling didChangeValueForKey: %@", key);
1840     [self didChangeValueForKey: key];
1841 }
1842
1843 - (void)_willChangeValueForKey: (NSString *)key
1844 {
1845     LOG (Bindings, "calling willChangeValueForKey: %@", key);
1846     [self willChangeValueForKey: key];
1847 }
1848
1849 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1850     static NSSet *manualNotifyKeys = nil;
1851     if (!manualNotifyKeys)
1852         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1853             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
1854             nil];
1855     if ([manualNotifyKeys containsObject:key])
1856         return NO;
1857     return YES;
1858 }
1859
1860 - (NSArray *)_declaredKeys {
1861     static NSArray *declaredKeys = nil;
1862     if (!declaredKeys)
1863         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1864             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1865     return declaredKeys;
1866 }
1867
1868 - (void)setObservationInfo:(void *)info
1869 {
1870     _private->observationInfo = info;
1871 }
1872
1873 - (void *)observationInfo
1874 {
1875     return _private->observationInfo;
1876 }
1877
1878 - (void)_willChangeBackForwardKeys
1879 {
1880     [self _willChangeValueForKey: _WebCanGoBackKey];
1881     [self _willChangeValueForKey: _WebCanGoForwardKey];
1882 }
1883
1884 - (void)_didChangeBackForwardKeys
1885 {
1886     [self _didChangeValueForKey: _WebCanGoBackKey];
1887     [self _didChangeValueForKey: _WebCanGoForwardKey];
1888 }
1889
1890 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1891 {
1892     if (needsSelfRetainWhileLoadingQuirk())
1893         [self retain];
1894
1895     [self _willChangeBackForwardKeys];
1896     if (frame == [self mainFrame]){
1897         // Force an observer update by sending a will/did.
1898         [self _willChangeValueForKey: _WebIsLoadingKey];
1899         [self _didChangeValueForKey: _WebIsLoadingKey];
1900
1901         [self _willChangeValueForKey: _WebMainFrameURLKey];
1902     }
1903
1904     [NSApp setWindowsNeedUpdate:YES];
1905 }
1906
1907 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1908 {
1909     if (frame == [self mainFrame])
1910         [self _didChangeValueForKey: _WebMainFrameURLKey];
1911     [NSApp setWindowsNeedUpdate:YES];
1912 }
1913
1914 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1915 {
1916     if (needsSelfRetainWhileLoadingQuirk())
1917         [self performSelector:@selector(release) withObject:nil afterDelay:0];
1918         
1919     [self _didChangeBackForwardKeys];
1920     if (frame == [self mainFrame]){
1921         // Force an observer update by sending a will/did.
1922         [self _willChangeValueForKey: _WebIsLoadingKey];
1923         [self _didChangeValueForKey: _WebIsLoadingKey];
1924     }
1925     [NSApp setWindowsNeedUpdate:YES];
1926 }
1927
1928 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1929 {
1930     if (needsSelfRetainWhileLoadingQuirk())
1931         [self performSelector:@selector(release) withObject:nil afterDelay:0];
1932
1933     [self _didChangeBackForwardKeys];
1934     if (frame == [self mainFrame]){
1935         // Force an observer update by sending a will/did.
1936         [self _willChangeValueForKey: _WebIsLoadingKey];
1937         [self _didChangeValueForKey: _WebIsLoadingKey];
1938     }
1939     [NSApp setWindowsNeedUpdate:YES];
1940 }
1941
1942 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1943 {
1944     if (needsSelfRetainWhileLoadingQuirk())
1945         [self performSelector:@selector(release) withObject:nil afterDelay:0];
1946
1947     [self _didChangeBackForwardKeys];
1948     if (frame == [self mainFrame]){
1949         // Force an observer update by sending a will/did.
1950         [self _willChangeValueForKey: _WebIsLoadingKey];
1951         [self _didChangeValueForKey: _WebIsLoadingKey];
1952         
1953         [self _didChangeValueForKey: _WebMainFrameURLKey];
1954     }
1955     [NSApp setWindowsNeedUpdate:YES];
1956 }
1957
1958 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1959 {
1960     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1961     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1962     NSCachedURLResponse *cachedResponse;
1963 #if USE(CFURLSTORAGESESSIONS)
1964     if (CFURLStorageSessionRef storageSession = ResourceHandle::privateBrowsingStorageSession())
1965         cachedResponse = WKCachedResponseForRequest(storageSession, request);
1966     else
1967 #endif
1968         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1969     [request release];
1970     return cachedResponse;
1971 }
1972
1973 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1974 {
1975     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1976     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1977     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
1978                         element:domElement
1979                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1980                           title:[element objectForKey:WebElementImageAltStringKey] 
1981                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1982                           types:types
1983                          source:nil];
1984 }
1985
1986 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1987 {
1988     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1989                      andTitle:[element objectForKey:WebElementLinkLabelKey]
1990                         types:types];
1991 }
1992
1993 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1994 {
1995     if (!_private->page)
1996         return;
1997     _private->page->dragController()->setDidInitiateDrag(initiatedDrag);
1998 }
1999
2000 #if ENABLE(DASHBOARD_SUPPORT)
2001
2002 #define DASHBOARD_CONTROL_LABEL @"control"
2003
2004 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
2005 {
2006     NSRect adjustedBounds = bounds;
2007     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
2008     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
2009     adjustedBounds.size = bounds.size;
2010
2011     NSRect adjustedClip;
2012     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
2013     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
2014     adjustedClip.size = clip.size;
2015
2016     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
2017         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
2018     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
2019     if (!scrollerRegions) {
2020         scrollerRegions = [[NSMutableArray alloc] init];
2021         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
2022         [scrollerRegions release];
2023     }
2024     [scrollerRegions addObject:region];
2025     [region release];
2026 }
2027
2028 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
2029 {    
2030     NSView *documentView = [[kit(frameView->frame()) frameView] documentView];
2031
2032     const HashSet<RefPtr<Widget> >* children = frameView->children();
2033     HashSet<RefPtr<Widget> >::const_iterator end = children->end();
2034     for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != end; ++it) {
2035         Widget* widget = (*it).get();
2036         if (widget->isFrameView()) {
2037             [self _addScrollerDashboardRegionsForFrameView:static_cast<FrameView*>(widget) dashboardRegions:regions];
2038             continue;
2039         }
2040
2041         if (!widget->isScrollbar())
2042             continue;
2043
2044         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
2045         // it's not common to need this to be correct in Dashboard widgets.
2046         NSRect bounds = widget->frameRect();
2047         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
2048     }
2049 }
2050
2051 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
2052 {
2053     // Add scroller regions for NSScroller and WebCore scrollbars
2054     NSUInteger count = [views count];
2055     for (NSUInteger i = 0; i < count; i++) {
2056         NSView *view = [views objectAtIndex:i];
2057         
2058         if ([view isKindOfClass:[WebHTMLView class]]) {
2059             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
2060                 if (FrameView* coreView = coreFrame->view())
2061                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
2062             }
2063         } else if ([view isKindOfClass:[NSScroller class]]) {
2064             // AppKit places absent scrollers at -100,-100
2065             if ([view frame].origin.y < 0)
2066                 continue;
2067             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
2068         }
2069         [self _addScrollerDashboardRegions:regions from:[view subviews]];
2070     }
2071 }
2072
2073 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
2074 {
2075     [self _addScrollerDashboardRegions:regions from:[self subviews]];
2076 }
2077
2078 - (NSDictionary *)_dashboardRegions
2079 {
2080     // Only return regions from main frame.
2081     Frame* mainFrame = [self _mainCoreFrame];
2082     if (!mainFrame)
2083         return nil;
2084
2085     const Vector<DashboardRegionValue>& regions = mainFrame->document()->dashboardRegions();
2086     size_t size = regions.size();
2087
2088     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
2089     for (size_t i = 0; i < size; i++) {
2090         const DashboardRegionValue& region = regions[i];
2091
2092         if (region.type == StyleDashboardRegion::None)
2093             continue;
2094
2095         NSString *label = region.label;
2096         WebDashboardRegionType type = WebDashboardRegionTypeNone;
2097         if (region.type == StyleDashboardRegion::Circle)
2098             type = WebDashboardRegionTypeCircle;
2099         else if (region.type == StyleDashboardRegion::Rectangle)
2100             type = WebDashboardRegionTypeRectangle;
2101         NSMutableArray *regionValues = [webRegions objectForKey:label];
2102         if (!regionValues) {
2103             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
2104             [webRegions setObject:regionValues forKey:label];
2105             [regionValues release];
2106         }
2107
2108         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:region.bounds clip:region.clip type:type];
2109         [regionValues addObject:webRegion];
2110         [webRegion release];
2111     }
2112
2113     [self _addScrollerDashboardRegions:webRegions];
2114
2115     return webRegions;
2116 }
2117
2118 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
2119 {
2120     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
2121     // specific support for the backward compatibility mode flag.
2122     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
2123         _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(true);
2124     
2125     switch (behavior) {
2126         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
2127             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
2128             break;
2129         }
2130         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
2131             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
2132             break;
2133         }
2134         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
2135             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
2136             break;
2137         }
2138         case WebDashboardBehaviorAllowWheelScrolling: {
2139             _private->dashboardBehaviorAllowWheelScrolling = flag;
2140             break;
2141         }
2142         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
2143             if (_private->page)
2144                 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(flag);
2145             break;
2146         }
2147     }
2148
2149     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
2150     // compatibility mode. See <rdar://problem/8175982>.
2151     if (_private->page)
2152         _private->page->settings()->setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2153 }
2154
2155 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
2156 {
2157     switch (behavior) {
2158         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
2159             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
2160         }
2161         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
2162             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
2163         }
2164         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
2165             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
2166         }
2167         case WebDashboardBehaviorAllowWheelScrolling: {
2168             return _private->dashboardBehaviorAllowWheelScrolling;
2169         }
2170         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
2171             return _private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode();
2172         }
2173     }
2174     return NO;
2175 }
2176
2177 #endif /* ENABLE(DASHBOARD_SUPPORT) */
2178
2179 + (void)_setShouldUseFontSmoothing:(BOOL)f
2180 {
2181     Font::setShouldUseSmoothing(f);
2182 }
2183
2184 + (BOOL)_shouldUseFontSmoothing
2185 {
2186     return Font::shouldUseSmoothing();
2187 }
2188
2189 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
2190 {
2191     setUsesTestModeFocusRingColor(f);
2192 }
2193
2194 + (BOOL)_usesTestModeFocusRingColor
2195 {
2196     return usesTestModeFocusRingColor();
2197 }
2198
2199 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
2200 {
2201     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2202     if (flag) {
2203         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
2204     } else {
2205         [scrollview setVerticalScrollingModeLocked:NO];
2206         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
2207     }
2208 }
2209
2210 - (BOOL)alwaysShowVerticalScroller
2211 {
2212     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2213     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
2214 }
2215
2216 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
2217 {
2218     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2219     if (flag) {
2220         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
2221     } else {
2222         [scrollview setHorizontalScrollingModeLocked:NO];
2223         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
2224     }
2225 }
2226
2227 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
2228 {
2229     if (Frame* mainFrame = [self _mainCoreFrame])
2230         mainFrame->view()->setProhibitsScrolling(prohibits);
2231 }
2232
2233 - (BOOL)alwaysShowHorizontalScroller
2234 {
2235     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2236     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
2237 }
2238
2239 - (void)_setInViewSourceMode:(BOOL)flag
2240 {
2241     if (Frame* mainFrame = [self _mainCoreFrame])
2242         mainFrame->setInViewSourceMode(flag);
2243 }
2244
2245 - (BOOL)_inViewSourceMode
2246 {
2247     Frame* mainFrame = [self _mainCoreFrame];
2248     return mainFrame && mainFrame->inViewSourceMode();
2249 }
2250
2251 - (void)_setUseFastImageScalingMode:(BOOL)flag
2252 {
2253     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
2254         _private->page->setInLowQualityImageInterpolationMode(flag);
2255         [self setNeedsDisplay:YES];
2256     }
2257 }
2258
2259 - (BOOL)_inFastImageScalingMode
2260 {
2261     if (_private->page)
2262         return _private->page->inLowQualityImageInterpolationMode();
2263     return NO;
2264 }
2265
2266 - (BOOL)_cookieEnabled
2267 {
2268     if (_private->page)
2269         return _private->page->cookieEnabled();
2270     return YES;
2271 }
2272
2273 - (void)_setCookieEnabled:(BOOL)enable
2274 {
2275     if (_private->page)
2276         _private->page->setCookieEnabled(enable);
2277 }
2278
2279 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
2280 {
2281     if (!_private->pluginDatabase)
2282         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
2283         
2284     [_private->pluginDatabase setPlugInPaths:newPaths];
2285     [_private->pluginDatabase refresh];
2286 }
2287
2288 - (void)_attachScriptDebuggerToAllFrames
2289 {
2290     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree()->traverseNext())
2291         [kit(frame) _attachScriptDebugger];
2292 }
2293
2294 - (void)_detachScriptDebuggerFromAllFrames
2295 {
2296     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree()->traverseNext())
2297         [kit(frame) _detachScriptDebugger];
2298 }
2299
2300 - (void)setBackgroundColor:(NSColor *)backgroundColor
2301 {
2302     if ([_private->backgroundColor isEqual:backgroundColor])
2303         return;
2304
2305     id old = _private->backgroundColor;
2306     _private->backgroundColor = [backgroundColor retain];
2307     [old release];
2308
2309     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
2310 }
2311
2312 - (NSColor *)backgroundColor
2313 {
2314     return _private->backgroundColor;
2315 }
2316
2317 - (BOOL)defersCallbacks
2318 {
2319     if (!_private->page)
2320         return NO;
2321     return _private->page->defersLoading();
2322 }
2323
2324 - (void)setDefersCallbacks:(BOOL)defer
2325 {
2326     if (!_private->page)
2327         return;
2328     return _private->page->setDefersLoading(defer);
2329 }
2330
2331 // For backwards compatibility with the WebBackForwardList API, we honor both
2332 // a per-WebView and a per-preferences setting for whether to use the page cache.
2333
2334 - (BOOL)usesPageCache
2335 {
2336     return _private->usesPageCache && [[self preferences] usesPageCache];
2337 }
2338
2339 - (void)setUsesPageCache:(BOOL)usesPageCache
2340 {
2341     _private->usesPageCache = usesPageCache;
2342
2343     // Update our own settings and post the public notification only
2344     [self _preferencesChanged:[self preferences]];
2345     [[self preferences] _postPreferencesChangedAPINotification];
2346 }
2347
2348 - (WebHistoryItem *)_globalHistoryItem
2349 {
2350     if (!_private)
2351         return nil;
2352
2353     return kit(_private->_globalHistoryItem.get());
2354 }
2355
2356 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
2357 {
2358     _private->_globalHistoryItem = historyItem;
2359 }
2360
2361 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
2362 {
2363     IntPoint rectStart(rect.origin.x, rect.origin.y);
2364     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
2365     
2366     Frame* coreFrame = [self _mainCoreFrame];
2367     if (!coreFrame)
2368         return nil;
2369     
2370     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
2371     
2372     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
2373 }
2374
2375 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource 
2376 {
2377     NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window]; 
2378     [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window]; 
2379
2380
2381 - (void)_clearUndoRedoOperations
2382 {
2383     if (!_private->page)
2384         return;
2385     _private->page->clearUndoRedoOperations();
2386 }
2387
2388 - (void)_setCatchesDelegateExceptions:(BOOL)f
2389 {
2390     _private->catchesDelegateExceptions = f;
2391 }
2392
2393 - (BOOL)_catchesDelegateExceptions
2394 {
2395     return _private->catchesDelegateExceptions;
2396 }
2397
2398 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
2399 {
2400     Frame* coreFrame = [self _mainCoreFrame];
2401     if (!coreFrame)
2402         return;
2403     coreFrame->editor()->command(name).execute(value);
2404 }
2405
2406 - (void)_setCustomHTMLTokenizerTimeDelay:(double)timeDelay
2407 {
2408     if (!_private->page)
2409         return;
2410     return _private->page->setCustomHTMLTokenizerTimeDelay(timeDelay);
2411 }
2412
2413 - (void)_setCustomHTMLTokenizerChunkSize:(int)chunkSize
2414 {
2415     if (!_private->page)
2416         return;
2417     return _private->page->setCustomHTMLTokenizerChunkSize(chunkSize);
2418 }
2419
2420 - (void)_clearMainFrameName
2421 {
2422     _private->page->mainFrame()->tree()->clearName();
2423 }
2424
2425 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
2426 {
2427     _private->selectTrailingWhitespaceEnabled = flag;
2428     if (flag)
2429         [self setSmartInsertDeleteEnabled:false];
2430 }
2431
2432 - (BOOL)isSelectTrailingWhitespaceEnabled
2433 {
2434     return _private->selectTrailingWhitespaceEnabled;
2435 }
2436
2437 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
2438 {
2439     _private->page->setMemoryCacheClientCallsEnabled(enabled);
2440 }
2441
2442 - (BOOL)areMemoryCacheDelegateCallsEnabled
2443 {
2444     return _private->page->areMemoryCacheClientCallsEnabled();
2445 }
2446
2447 - (void)_setJavaScriptURLsAreAllowed:(BOOL)areAllowed
2448 {
2449     _private->page->setJavaScriptURLsAreAllowed(areAllowed);
2450 }
2451
2452 + (NSCursor *)_pointingHandCursor
2453 {
2454     return handCursor().platformCursor();
2455 }
2456
2457 - (BOOL)_postsAcceleratedCompositingNotifications
2458 {
2459 #if USE(ACCELERATED_COMPOSITING)
2460     return _private->postsAcceleratedCompositingNotifications;
2461 #else
2462     return NO;
2463 #endif
2464
2465 }
2466 - (void)_setPostsAcceleratedCompositingNotifications:(BOOL)flag
2467 {
2468 #if USE(ACCELERATED_COMPOSITING)
2469     _private->postsAcceleratedCompositingNotifications = flag;
2470 #endif
2471 }
2472
2473 - (BOOL)_isUsingAcceleratedCompositing
2474 {
2475 #if USE(ACCELERATED_COMPOSITING)
2476     if (_private->usesDocumentViews) {
2477         Frame* coreFrame = [self _mainCoreFrame];
2478         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
2479             NSView *documentView = [[kit(frame) frameView] documentView];
2480             if ([documentView isKindOfClass:[WebHTMLView class]] && [(WebHTMLView *)documentView _isUsingAcceleratedCompositing])
2481                 return YES;
2482         }
2483     }
2484 #endif
2485     return NO;
2486 }
2487
2488 - (BOOL)interactiveFormValidationEnabled
2489 {
2490     return _private->interactiveFormValidationEnabled;
2491 }
2492
2493 - (void)setInteractiveFormValidationEnabled:(BOOL)enabled
2494 {
2495     _private->interactiveFormValidationEnabled = enabled;
2496 }
2497
2498 - (int)validationMessageTimerMagnification
2499 {
2500     return _private->validationMessageTimerMagnification;
2501 }
2502
2503 - (void)setValidationMessageTimerMagnification:(int)newValue
2504 {
2505     _private->validationMessageTimerMagnification = newValue;
2506 }
2507
2508 - (BOOL)_isSoftwareRenderable
2509 {
2510 #if USE(ACCELERATED_COMPOSITING)
2511     if (_private->usesDocumentViews) {
2512         Frame* coreFrame = [self _mainCoreFrame];
2513         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
2514             if (FrameView* view = frame->view()) {
2515                 if (!view->isSoftwareRenderable())
2516                     return NO;
2517             }
2518         }
2519     }
2520 #endif
2521     return YES;
2522 }
2523
2524 - (void)_setIncludesFlattenedCompositingLayersWhenDrawingToBitmap:(BOOL)flag
2525 {
2526     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = flag;
2527 }
2528
2529 - (BOOL)_includesFlattenedCompositingLayersWhenDrawingToBitmap
2530 {
2531     return _private->includesFlattenedCompositingLayersWhenDrawingToBitmap;
2532 }
2533
2534 #if ENABLE(NETSCAPE_PLUGIN_API)
2535 static WebBaseNetscapePluginView *_pluginViewForNode(DOMNode *node)
2536 {
2537     if (!node)
2538         return nil;
2539     
2540     Node* coreNode = core(node);
2541     if (!coreNode)
2542         return nil;
2543     
2544     RenderObject* renderer = coreNode->renderer();
2545     if (!renderer || !renderer->isWidget())
2546         return nil;
2547     
2548     Widget* widget = toRenderWidget(renderer)->widget();
2549     if (!widget || !widget->platformWidget())
2550         return nil;
2551     
2552     NSView *view = widget->platformWidget();
2553     if (![view isKindOfClass:[WebBaseNetscapePluginView class]])
2554         return nil;
2555     
2556     return (WebBaseNetscapePluginView *)view;
2557 }
2558 #endif // ENABLE(NETSCAPE_PLUGIN_API)
2559
2560 + (BOOL)_isNodeHaltedPlugin:(DOMNode *)node
2561 {
2562 #if ENABLE(NETSCAPE_PLUGIN_API)
2563     return [_pluginViewForNode(node) isHalted];
2564 #else
2565     return YES;
2566 #endif
2567 }
2568
2569 + (BOOL)_hasPluginForNodeBeenHalted:(DOMNode *)node
2570 {
2571 #if ENABLE(NETSCAPE_PLUGIN_API)
2572     return [_pluginViewForNode(node) hasBeenHalted];
2573 #else
2574     return YES;
2575 #endif
2576 }
2577 + (void)_restartHaltedPluginForNode:(DOMNode *)node
2578 {
2579 #if ENABLE(NETSCAPE_PLUGIN_API)
2580     if (!node)
2581         return;
2582     
2583     [_pluginViewForNode(node) resumeFromHalt];
2584 #endif
2585 }
2586
2587 - (NSPasteboard *)_insertionPasteboard
2588 {
2589     return _private ? _private->insertionPasteboard : nil;
2590 }
2591
2592 + (void)_addOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2593 {
2594     SecurityOrigin::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2595 }
2596
2597 + (void)_removeOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2598 {
2599     SecurityOrigin::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2600 }
2601
2602 +(void)_resetOriginAccessWhitelists
2603 {
2604     SecurityOrigin::resetOriginAccessWhitelists();
2605 }
2606
2607 - (void)_updateActiveState
2608 {
2609     if (_private && _private->page)
2610         _private->page->focusController()->setActive([[self window] isKeyWindow]);
2611 }
2612
2613 static PassOwnPtr<Vector<String> > toStringVector(NSArray* patterns)
2614 {
2615     // Convert the patterns into Vectors.
2616     NSUInteger count = [patterns count];
2617     if (count == 0)
2618         return nullptr;
2619     OwnPtr<Vector<String> > patternsVector = adoptPtr(new Vector<String>);
2620     for (NSUInteger i = 0; i < count; ++i) {
2621         id entry = [patterns objectAtIndex:i];
2622         if ([entry isKindOfClass:[NSString class]])
2623             patternsVector->append(String((NSString*)entry));
2624     }
2625     return patternsVector.release();
2626 }
2627
2628 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2629                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2630                 injectionTime:(WebUserScriptInjectionTime)injectionTime
2631 {
2632     [WebView _addUserScriptToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectionTime:injectionTime injectedFrames:WebInjectInAllFrames];
2633 }
2634
2635 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2636                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2637                 injectionTime:(WebUserScriptInjectionTime)injectionTime
2638                injectedFrames:(WebUserContentInjectedFrames)injectedFrames
2639 {
2640     String group(groupName);
2641     if (group.isEmpty())
2642         return;
2643     
2644     PageGroup* pageGroup = PageGroup::pageGroup(group);
2645     if (!pageGroup)
2646         return;
2647     
2648     pageGroup->addUserScriptToWorld(core(world), source, url, toStringVector(whitelist), toStringVector(blacklist), 
2649                                     injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd,
2650                                     injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
2651 }
2652
2653 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2654                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2655 {
2656     [WebView _addUserStyleSheetToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectedFrames:WebInjectInAllFrames];
2657 }
2658
2659 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2660                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2661                    injectedFrames:(WebUserContentInjectedFrames)injectedFrames
2662 {
2663     String group(groupName);
2664     if (group.isEmpty())
2665         return;
2666     
2667     PageGroup* pageGroup = PageGroup::pageGroup(group);
2668     if (!pageGroup)
2669         return;
2670
2671     pageGroup->addUserStyleSheetToWorld(core(world), source, url, toStringVector(whitelist), toStringVector(blacklist), injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
2672 }
2673
2674 + (void)_removeUserScriptFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2675 {
2676     String group(groupName);
2677     if (group.isEmpty())
2678         return;
2679     
2680     PageGroup* pageGroup = PageGroup::pageGroup(group);
2681     if (!pageGroup)
2682         return;
2683
2684     pageGroup->removeUserScriptFromWorld(core(world), url);
2685 }
2686
2687 + (void)_removeUserStyleSheetFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2688 {
2689     String group(groupName);
2690     if (group.isEmpty())
2691         return;
2692     
2693     PageGroup* pageGroup = PageGroup::pageGroup(group);
2694     if (!pageGroup)
2695         return;
2696
2697     pageGroup->removeUserStyleSheetFromWorld(core(world), url);
2698 }
2699
2700 + (void)_removeUserScriptsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2701 {
2702     String group(groupName);
2703     if (group.isEmpty())
2704         return;
2705     
2706     PageGroup* pageGroup = PageGroup::pageGroup(group);
2707     if (!pageGroup)
2708         return;
2709
2710     pageGroup->removeUserScriptsFromWorld(core(world));
2711 }
2712
2713 + (void)_removeUserStyleSheetsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2714 {
2715     String group(groupName);
2716     if (group.isEmpty())
2717         return;
2718     
2719     PageGroup* pageGroup = PageGroup::pageGroup(group);
2720     if (!pageGroup)
2721         return;
2722
2723     pageGroup->removeUserStyleSheetsFromWorld(core(world));
2724 }
2725
2726 + (void)_removeAllUserContentFromGroup:(NSString *)groupName
2727 {
2728     String group(groupName);
2729     if (group.isEmpty())
2730         return;
2731     
2732     PageGroup* pageGroup = PageGroup::pageGroup(group);
2733     if (!pageGroup)
2734         return;
2735     
2736     pageGroup->removeAllUserContent();
2737 }
2738
2739 - (BOOL)cssAnimationsSuspended
2740 {
2741     return _private->cssAnimationsSuspended;
2742 }
2743
2744 - (void)setCSSAnimationsSuspended:(BOOL)suspended
2745 {
2746     if (suspended == _private->cssAnimationsSuspended)
2747         return;
2748         
2749     _private->cssAnimationsSuspended = suspended;
2750     
2751     Frame* frame = core([self mainFrame]);
2752     if (suspended)
2753         frame->animation()->suspendAnimations();
2754     else
2755         frame->animation()->resumeAnimations();
2756 }
2757
2758 + (void)_setDomainRelaxationForbidden:(BOOL)forbidden forURLScheme:(NSString *)scheme
2759 {
2760     SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
2761 }
2762
2763 + (void)_registerURLSchemeAsSecure:(NSString *)scheme
2764 {
2765     SchemeRegistry::registerURLSchemeAsSecure(scheme);
2766 }
2767
2768 - (void)_scaleWebView:(float)scale atOrigin:(NSPoint)origin
2769 {
2770     Frame* coreFrame = [self _mainCoreFrame];
2771     if (!coreFrame)
2772         return;
2773
2774     coreFrame->scalePage(scale, IntPoint(origin));
2775 }
2776
2777 - (float)_viewScaleFactor
2778 {
2779     Frame* coreFrame = [self _mainCoreFrame];
2780     if (!coreFrame)
2781         return 1;
2782
2783     return coreFrame->pageScaleFactor();
2784 }
2785
2786 - (void)_setUseFixedLayout:(BOOL)fixed
2787 {
2788     Frame* coreFrame = [self _mainCoreFrame];
2789     if (!coreFrame)
2790         return;
2791
2792     FrameView* view = coreFrame->view();
2793     if (!view)
2794         return;
2795
2796     view->setUseFixedLayout(fixed);
2797     if (!fixed)
2798         view->setFixedLayoutSize(IntSize());
2799 }
2800
2801 - (void)_setFixedLayoutSize:(NSSize)size
2802 {
2803     Frame* coreFrame = [self _mainCoreFrame];
2804     if (!coreFrame)
2805         return;
2806     
2807     FrameView* view = coreFrame->view();
2808     if (!view)
2809         return;
2810     
2811     view->setFixedLayoutSize(IntSize(size));
2812     view->forceLayout();
2813 }
2814
2815 - (BOOL)_useFixedLayout
2816 {
2817     Frame* coreFrame = [self _mainCoreFrame];
2818     if (!coreFrame)
2819         return NO;
2820     
2821     FrameView* view = coreFrame->view();
2822     if (!view)
2823         return NO;
2824     
2825     return view->useFixedLayout();
2826 }
2827
2828 - (NSSize)_fixedLayoutSize
2829 {
2830     Frame* coreFrame = [self _mainCoreFrame];
2831     if (!coreFrame)
2832         return IntSize();
2833     
2834     FrameView* view = coreFrame->view();
2835     if (!view)
2836         return IntSize();
2837
2838     return view->fixedLayoutSize();
2839 }
2840
2841 - (NSUInteger)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit
2842 {
2843     return [self countMatchesForText:string options:(caseFlag ? 0 : WebFindOptionsCaseInsensitive) highlight:highlight limit:limit markMatches:YES];
2844 }
2845
2846 - (NSUInteger)countMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit markMatches:(BOOL)markMatches
2847 {
2848     return [self countMatchesForText:string options:(caseFlag ? 0 : WebFindOptionsCaseInsensitive) highlight:highlight limit:limit markMatches:markMatches];
2849 }
2850
2851 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag startInSelection:(BOOL)startInSelection
2852 {
2853     return [self findString:string options:((forward ? 0 : WebFindOptionsBackwards) | (caseFlag ? 0 : WebFindOptionsCaseInsensitive) | (wrapFlag ? WebFindOptionsWrapAround : 0) | (startInSelection ? WebFindOptionsStartInSelection : 0))];
2854 }
2855
2856 + (void)_setLoadResourcesSerially:(BOOL)serialize 
2857 {
2858     resourceLoadScheduler()->setSerialLoadingEnabled(serialize);
2859 }
2860
2861 + (double)_defaultMinimumTimerInterval
2862 {
2863     return Settings::defaultMinDOMTimerInterval();
2864 }
2865
2866 - (void)_setMinimumTimerInterval:(double)intervalInSeconds
2867 {
2868     if (_private->page)
2869         _private->page->settings()->setMinDOMTimerInterval(intervalInSeconds);
2870 }
2871
2872 + (BOOL)_HTTPPipeliningEnabled
2873 {
2874     return ResourceRequest::httpPipeliningEnabled();
2875 }
2876
2877 + (void)_setHTTPPipeliningEnabled:(BOOL)enabled
2878 {
2879     ResourceRequest::setHTTPPipeliningEnabled(enabled);
2880 }
2881
2882 @end
2883
2884 @implementation _WebSafeForwarder
2885
2886 // Used to send messages to delegates that implement informal protocols.
2887
2888 - (id)initWithTarget:(id)t defaultTarget:(id)dt catchExceptions:(BOOL)c
2889 {
2890     self = [super init];
2891     if (!self)
2892         return nil;
2893     target = t; // Non retained.
2894     defaultTarget = dt;
2895     catchExceptions = c;
2896     return self;
2897 }
2898
2899 - (void)forwardInvocation:(NSInvocation *)invocation
2900 {
2901     if ([target respondsToSelector:[invocation selector]]) {
2902         if (catchExceptions) {
2903             @try {
2904                 [invocation invokeWithTarget:target];
2905             } @catch(id exception) {
2906                 ReportDiscardedDelegateException([invocation selector], exception);
2907             }
2908         } else
2909             [invocation invokeWithTarget:target];
2910         return;
2911     }
2912
2913     if ([defaultTarget respondsToSelector:[invocation selector]])
2914         [invocation invokeWithTarget:defaultTarget];
2915
2916     // Do nothing quietly if method not implemented.
2917 }
2918
2919 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
2920 {
2921     return [defaultTarget methodSignatureForSelector:aSelector];
2922 }
2923
2924 @end
2925
2926 @implementation WebView
2927
2928 + (void)initialize
2929 {
2930     static BOOL initialized = NO;
2931     if (initialized)
2932         return;
2933     initialized = YES;
2934
2935     InitWebCoreSystemInterface();
2936     JSC::initializeThreading();
2937     WTF::initializeMainThreadToProcessMainThread();
2938
2939     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate) name:NSApplicationWillTerminateNotification object:NSApp];
2940     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:) name:WebPreferencesChangedInternalNotification object:nil];
2941     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesRemovedNotification:) name:WebPreferencesRemovedNotification object:nil];    
2942
2943     continuousSpellCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebContinuousSpellCheckingEnabled];
2944     grammarCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebGrammarCheckingEnabled];
2945
2946 #ifndef BUILDING_ON_LEOPARD
2947     automaticQuoteSubstitutionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticQuoteSubstitutionEnabled];
2948     automaticLinkDetectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticLinkDetectionEnabled];
2949     automaticDashSubstitutionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticDashSubstitutionEnabled];
2950     automaticTextReplacementEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticTextReplacementEnabled];
2951     automaticSpellingCorrectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticSpellingCorrectionEnabled];
2952 #endif
2953
2954 #if !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD)
2955     if (![[NSUserDefaults standardUserDefaults] objectForKey:WebAutomaticTextReplacementEnabled])
2956         automaticTextReplacementEnabled = [NSSpellChecker isAutomaticTextReplacementEnabled];
2957     if (![[NSUserDefaults standardUserDefaults] objectForKey:WebAutomaticSpellingCorrectionEnabled])
2958         automaticSpellingCorrectionEnabled = [NSSpellChecker isAutomaticSpellingCorrectionEnabled];
2959 #endif
2960 }
2961
2962 + (void)_applicationWillTerminate
2963 {   
2964     applicationIsTerminating = YES;
2965
2966     if (fastDocumentTeardownEnabled())
2967         [self closeAllWebViews];
2968
2969     if (!pluginDatabaseClientCount)
2970         [WebPluginDatabase closeSharedDatabase];
2971
2972     PageGroup::closeLocalStorage();
2973 }
2974
2975 + (BOOL)_canShowMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2976 {
2977     return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType allowingPlugins:allowPlugins];
2978 }
2979
2980 + (BOOL)canShowMIMEType:(NSString *)MIMEType
2981 {
2982     return [self _canShowMIMEType:MIMEType allowingPlugins:YES];
2983 }
2984
2985 - (BOOL)_canShowMIMEType:(NSString *)MIMEType
2986 {
2987     return [[self class] _canShowMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]];
2988 }
2989
2990 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
2991 {
2992     if (![_private->preferences arePlugInsEnabled])
2993         return nil;
2994
2995     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
2996     if (pluginPackage)
2997         return pluginPackage;
2998     
2999     if (_private->pluginDatabase)
3000         return [_private->pluginDatabase pluginForMIMEType:MIMEType];
3001     
3002     return nil;
3003 }
3004
3005 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
3006 - (WebBasePluginPackage *)_videoProxyPluginForMIMEType:(NSString *)MIMEType
3007 {
3008     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
3009     if (pluginPackage)
3010         return pluginPackage;
3011
3012     if (_private->pluginDatabase)
3013         return [_private->pluginDatabase pluginForMIMEType:MIMEType];
3014
3015     return nil;
3016 }
3017 #endif
3018
3019 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
3020 {
3021     if (![_private->preferences arePlugInsEnabled])
3022         return nil;
3023
3024     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForExtension:extension];
3025     if (pluginPackage)
3026         return pluginPackage;
3027     
3028     if (_private->pluginDatabase)
3029         return [_private->pluginDatabase pluginForExtension:extension];
3030     
3031     return nil;
3032 }
3033
3034 - (void)addPluginInstanceView:(NSView *)view
3035 {
3036     if (!_private->pluginDatabase)
3037         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3038     [_private->pluginDatabase addPluginInstanceView:view];
3039 }
3040
3041 - (void)removePluginInstanceView:(NSView *)view
3042 {
3043     if (_private->pluginDatabase)
3044         [_private->pluginDatabase removePluginInstanceView:view];    
3045 }
3046
3047 - (void)removePluginInstanceViewsFor:(WebFrame*)webFrame 
3048 {
3049     if (_private->pluginDatabase)
3050         [_private->pluginDatabase removePluginInstanceViewsFor:webFrame];    
3051 }
3052
3053 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
3054 {
3055     if (![_private->preferences arePlugInsEnabled])
3056         return NO;
3057
3058     if ([[WebPluginDatabase sharedDatabase] isMIMETypeRegistered:MIMEType])
3059         return YES;
3060         
3061     if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
3062         return YES;
3063     
3064     return NO;
3065 }
3066
3067 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
3068 {
3069     return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
3070 }
3071
3072 + (NSArray *)MIMETypesShownAsHTML
3073 {
3074     NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
3075     NSEnumerator *enumerator = [viewTypes keyEnumerator];
3076     id key;
3077     NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
3078     
3079     while ((key = [enumerator nextObject])) {
3080         if ([viewTypes objectForKey:key] == [WebHTMLView class])
3081             [array addObject:key];
3082     }
3083     
3084     return array;
3085 }
3086
3087 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
3088 {
3089     NSDictionary *viewTypes = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] copy];
3090     NSEnumerator *enumerator = [viewTypes keyEnumerator];
3091     id key;
3092     while ((key = [enumerator nextObject])) {
3093         if ([viewTypes objectForKey:key] == [WebHTMLView class])
3094             [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
3095     }
3096     
3097     int i, count = [MIMETypes count];
3098     for (i = 0; i < count; i++) {
3099         [WebView registerViewClass:[WebHTMLView class] 
3100                 representationClass:[WebHTMLRepresentation class] 
3101                 forMIMEType:[MIMETypes objectAtIndex:i]];
3102     }
3103     [viewTypes release];
3104 }
3105
3106 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
3107 {
3108     return [pasteboard _web_bestURL];
3109 }
3110
3111 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
3112 {
3113     return [pasteboard stringForType:WebURLNamePboardType];
3114 }
3115
3116 + (void)registerURLSchemeAsLocal:(NSString *)protocol
3117 {
3118     SchemeRegistry::registerURLSchemeAsLocal(protocol);
3119 }
3120
3121 - (id)_initWithArguments:(NSDictionary *) arguments
3122 {
3123     NSCoder *decoder = [arguments objectForKey:@"decoder"];
3124     if (decoder) {
3125         self = [self initWithCoder:decoder];
3126     } else {
3127         ASSERT([arguments objectForKey:@"frame"]);
3128         NSValue *frameValue = [arguments objectForKey:@"frame"];
3129         NSRect frame = (frameValue ? [frameValue rectValue] : NSZeroRect);
3130         NSString *frameName = [arguments objectForKey:@"frameName"];
3131         NSString *groupName = [arguments objectForKey:@"groupName"];
3132         self = [self initWithFrame:frame frameName:frameName groupName:groupName];
3133     }
3134
3135     return self;
3136 }
3137
3138 static bool clientNeedsWebViewInitThreadWorkaround()
3139 {
3140     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_WEBVIEW_INIT_THREAD_WORKAROUND))
3141         return false;
3142
3143     NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
3144
3145     // Installer.
3146     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.installer"])
3147         return true;
3148
3149     // Automator.
3150     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Automator"])
3151         return true;
3152
3153     // Automator Runner.
3154     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.AutomatorRunner"])
3155         return true;
3156
3157     // Automator workflows.
3158     if ([bundleIdentifier _webkit_hasCaseInsensitivePrefix:@"com.apple.Automator."])
3159         return true;
3160
3161 #ifdef BUILDING_ON_LEOPARD
3162     // Mail.
3163     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Mail"])
3164         return true;
3165 #endif
3166
3167     return false;
3168 }
3169
3170 static bool needsWebViewInitThreadWorkaround()
3171 {
3172     static bool isOldClient = clientNeedsWebViewInitThreadWorkaround();
3173     return isOldClient && !pthread_main_np();
3174 }
3175
3176 - (id)initWithFrame:(NSRect)f
3177 {
3178     return [self initWithFrame:f frameName:nil groupName:nil];
3179 }
3180
3181 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
3182 {
3183     if (needsWebViewInitThreadWorkaround())
3184         return [[self _webkit_invokeOnMainThread] initWithFrame:f frameName:frameName groupName:groupName];
3185
3186     WebCoreThreadViolationCheckRoundTwo();
3187     return [self _initWithFrame:f frameName:frameName groupName:groupName usesDocumentViews:YES];
3188 }
3189
3190 - (id)initWithCoder:(NSCoder *)decoder
3191 {
3192     if (needsWebViewInitThreadWorkaround())
3193         return [[self _webkit_invokeOnMainThread] initWithCoder:decoder];
3194
3195     WebCoreThreadViolationCheckRoundTwo();
3196     WebView *result = nil;
3197
3198     @try {
3199         NSString *frameName;
3200         NSString *groupName;
3201         WebPreferences *preferences;
3202         BOOL useBackForwardList = NO;
3203         BOOL allowsUndo = YES;
3204         
3205         result = [super initWithCoder:decoder];
3206         result->_private = [[WebViewPrivate alloc] init];
3207
3208         // We don't want any of the archived subviews. The subviews will always
3209         // be created in _commonInitializationFrameName:groupName:.
3210         [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
3211
3212         if ([decoder allowsKeyedCoding]) {
3213             frameName = [decoder decodeObjectForKey:@"FrameName"];
3214             groupName = [decoder decodeObjectForKey:@"GroupName"];
3215             preferences = [decoder decodeObjectForKey:@"Preferences"];
3216             useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
3217             if ([decoder containsValueForKey:@"AllowsUndo"])
3218                 allowsUndo = [decoder decodeBoolForKey:@"AllowsUndo"];
3219         } else {
3220             int version;
3221             [decoder decodeValueOfObjCType:@encode(int) at:&version];
3222             frameName = [decoder decodeObject];
3223             groupName = [decoder decodeObject];
3224             preferences = [decoder decodeObject];
3225             if (version > 1)
3226                 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
3227             // The allowsUndo field is no longer written out in encodeWithCoder, but since there are
3228             // version 3 NIBs that have this field encoded, we still need to read it in.
3229             if (version == 3)
3230                 [decoder decodeValuesOfObjCTypes:"c", &allowsUndo];
3231         }
3232
3233         if (![frameName isKindOfClass:[NSString class]])
3234             frameName = nil;
3235         if (![groupName isKindOfClass:[NSString class]])
3236             groupName = nil;
3237         if (![preferences isKindOfClass:[WebPreferences class]])
3238             preferences = nil;
3239
3240         LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
3241         [result _commonInitializationWithFrameName:frameName groupName:groupName usesDocumentViews:YES];
3242         static_cast<BackForwardListImpl*>([result page]->backForwardList())->setEnabled(useBackForwardList);
3243         result->_private->allowsUndo = allowsUndo;
3244         if (preferences)
3245             [result setPreferences:preferences];
3246     } @catch (NSException *localException) {
3247         result = nil;
3248         [self release];
3249     }
3250
3251     return result;
3252 }
3253
3254 - (void)encodeWithCoder:(NSCoder *)encoder
3255 {
3256     // Set asside the subviews before we archive. We don't want to archive any subviews.
3257     // The subviews will always be created in _commonInitializationFrameName:groupName:.
3258     id originalSubviews = _subviews;
3259     _subviews = nil;
3260
3261     [super encodeWithCoder:encoder];
3262
3263     // Restore the subviews we set aside.
3264     _subviews = originalSubviews;
3265
3266     BOOL useBackForwardList = _private->page && static_cast<BackForwardListImpl*>(_private->page->backForwardList())->enabled();
3267     if ([encoder allowsKeyedCoding]) {
3268         [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
3269         [encoder encodeObject:[self groupName] forKey:@"GroupName"];
3270         [encoder encodeObject:[self preferences] forKey:@"Preferences"];
3271         [encoder encodeBool:useBackForwardList forKey:@"UseBackForwardList"];
3272         [encoder encodeBool:_private->allowsUndo forKey:@"AllowsUndo"];
3273     } else {
3274         int version = WebViewVersion;
3275         [encoder encodeValueOfObjCType:@encode(int) at:&version];
3276         [encoder encodeObject:[[self mainFrame] name]];
3277         [encoder encodeObject:[self groupName]];
3278         [encoder encodeObject:[self preferences]];
3279         [encoder encodeValuesOfObjCTypes:"c", &useBackForwardList];
3280         // DO NOT encode any new fields here, doing so will break older WebKit releases.
3281     }
3282
3283     LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)useBackForwardList);
3284 }
3285
3286 - (void)dealloc
3287 {
3288     if (WebCoreObjCScheduleDeallocateOnMainThread([WebView class], self))
3289         return;
3290
3291     // call close to ensure we tear-down completely
3292     // this maintains our old behavior for existing applications
3293     [self close];
3294
3295     if ([[self class] shouldIncludeInWebKitStatistics])
3296         --WebViewCount;
3297
3298     if ([self _needsFrameLoadDelegateRetainQuirk])
3299         [_private->frameLoadDelegate release];
3300         
3301     [_private release];
3302     // [super dealloc] can end up dispatching against _private (3466082)
3303     _private = nil;
3304
3305     [super dealloc];
3306 }
3307
3308 - (void)finalize
3309 {
3310     ASSERT(_private->closed);
3311
3312     --WebViewCount;
3313
3314     [super finalize];
3315 }
3316
3317 - (void)close
3318 {
3319     // _close existed first, and some clients might be calling or overriding it, so call through.
3320     [self _close];
3321 }
3322
3323 - (void)setShouldCloseWithWindow:(BOOL)close
3324 {
3325     _private->shouldCloseWithWindow = close;
3326 }
3327
3328 - (BOOL)shouldCloseWithWindow
3329 {
3330     return _private->shouldCloseWithWindow;
3331 }
3332
3333 - (void)addWindowObserversForWindow:(NSWindow *)window
3334 {
3335     if (window) {
3336         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
3337             name:NSWindowDidBecomeKeyNotification object:nil];
3338         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
3339             name:NSWindowDidResignKeyNotification object:nil];
3340         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillOrderOnScreen:)
3341             name:WKWindowWillOrderOnScreenNotification() object:window];
3342     }
3343 }
3344
3345 - (void)removeWindowObservers
3346 {
3347     NSWindow *window = [self window];
3348     if (window) {
3349         [[NSNotificationCenter defaultCenter] removeObserver:self
3350             name:NSWindowDidBecomeKeyNotification object:nil];
3351         [[NSNotificationCenter defaultCenter] removeObserver:self
3352             name:NSWindowDidResignKeyNotification object:nil];
3353         [[NSNotificationCenter defaultCenter] removeObserver:self
3354             name:WKWindowWillOrderOnScreenNotification() object:window];
3355     }
3356 }
3357
3358 - (void)viewWillMoveToWindow:(NSWindow *)window
3359 {
3360     // Don't do anything if the WebView isn't initialized.
3361     // This happens when decoding a WebView in a nib.
3362     // FIXME: What sets up the observer of NSWindowWillCloseNotification in this case?
3363     if (!_private || _private->closed)
3364         return;
3365     
3366     if ([self window] && [self window] != [self hostWindow])
3367         [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
3368
3369     if (window) {
3370         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
3371          
3372         // Ensure that we will receive the events that WebHTMLView (at least) needs.
3373         // The following are expensive enough that we don't want to call them over
3374         // and over, so do them when we move into a window.
3375         [window setAcceptsMouseMovedEvents:YES];
3376         WKSetNSWindowShouldPostEventNotifications(window, YES);
3377     } else {
3378         _private->page->setCanStartMedia(false);
3379         _private->page->willMoveOffscreen();
3380     }
3381         
3382     if (window != [self window]) {
3383         [self removeWindowObservers];
3384         [self addWindowObserversForWindow:window];
3385     }
3386 }
3387
3388 - (void)viewDidMoveToWindow
3389 {
3390     // Don't do anything if we aren't initialized.  This happens
3391     // when decoding a WebView.  When WebViews are decoded their subviews
3392     // are created by initWithCoder: and so won't be normally
3393     // initialized.  The stub views are discarded by WebView.
3394     if (!_private || _private->closed)
3395         return;
3396
3397     if ([self window]) {
3398         _private->page->setCanStartMedia(true);
3399         _private->page->didMoveOnscreen();
3400     }
3401     
3402     [self _updateActiveState];
3403 }
3404
3405 - (void)_windowDidBecomeKey:(NSNotification *)notification
3406 {
3407     NSWindow *keyWindow = [notification object];
3408     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
3409         [self _updateActiveState];
3410 }
3411
3412 - (void)_windowDidResignKey:(NSNotification *)notification
3413 {
3414     NSWindow *formerKeyWindow = [notification object];
3415     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet])
3416         [self _updateActiveState];
3417 }
3418
3419 - (void)_windowWillOrderOnScreen:(NSNotification *)notification
3420 {
3421     if (![self shouldUpdateWhileOffscreen])
3422         [self setNeedsDisplay:YES];
3423 }
3424
3425 - (void)_windowWillClose:(NSNotification *)notification
3426 {
3427     if ([self shouldCloseWithWindow] && ([self window] == [self hostWindow] || ([self window] && ![self hostWindow]) || (![self window] && [self hostWindow])))
3428         [self close];
3429 }
3430
3431 - (void)setPreferences:(WebPreferences *)prefs
3432 {
3433     if (!prefs)
3434         prefs = [WebPreferences standardPreferences];
3435
3436     if (_private->preferences == prefs)
3437         return;
3438
3439     [prefs willAddToWebView];
3440
3441     WebPreferences *oldPrefs = _private->preferences;
3442
3443     [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedInternalNotification object:[self preferences]];
3444     [WebPreferences _removeReferenceForIdentifier:[oldPrefs identifier]];
3445
3446     _private->preferences = [prefs retain];
3447
3448     // After registering for the notification, post it so the WebCore settings update.
3449     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
3450         name:WebPreferencesChangedInternalNotification object:[self preferences]];
3451     [self _preferencesChanged:[self preferences]];
3452     [[self preferences] _postPreferencesChangedAPINotification];
3453
3454     [oldPrefs didRemoveFromWebView];
3455     [oldPrefs release];
3456 }
3457
3458 - (WebPreferences *)preferences
3459 {
3460     return _private->preferences;
3461 }
3462
3463 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
3464 {
3465     if (!_private->closed && ![anIdentifier isEqual:[[self preferences] identifier]]) {
3466         WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
3467         [self setPreferences:prefs];
3468         [prefs release];
3469     }
3470 }
3471
3472 - (NSString *)preferencesIdentifier
3473 {
3474     return [[self preferences] identifier];
3475 }
3476
3477
3478 - (void)setUIDelegate:delegate
3479 {
3480     _private->UIDelegate = delegate;
3481     [_private->UIDelegateForwarder release];
3482     _private->UIDelegateForwarder = nil;
3483 }
3484
3485 - (id)UIDelegate
3486 {
3487     return _private->UIDelegate;
3488 }
3489
3490 - (void)setResourceLoadDelegate: delegate
3491 {
3492     _private->resourceProgressDelegate = delegate;
3493     [self _cacheResourceLoadDelegateImplementations];
3494 }
3495
3496 - (id)resourceLoadDelegate
3497 {
3498     return _private->resourceProgressDelegate;
3499 }
3500
3501 - (void)setDownloadDelegate: delegate
3502 {
3503     _private->downloadDelegate = delegate;
3504 }
3505
3506
3507 - (id)downloadDelegate
3508 {
3509     return _private->downloadDelegate;
3510 }
3511
3512 - (void)setPolicyDelegate:delegate
3513 {
3514     _private->policyDelegate = delegate;
3515     [_private->policyDelegateForwarder release];
3516     _private->policyDelegateForwarder = nil;
3517 }
3518
3519 - (id)policyDelegate
3520 {
3521     return _private->policyDelegate;
3522 }
3523
3524 - (void)setFrameLoadDelegate:delegate
3525 {
3526     // <rdar://problem/6950660> - Due to some subtle WebKit changes - presumably to delegate callback behavior - we've
3527     // unconvered a latent bug in at least one WebKit app where the delegate wasn't properly retained by the app and
3528     // was dealloc'ed before being cleared.
3529     // This is an effort to keep such apps working for now.
3530     if ([self _needsFrameLoadDelegateRetainQuirk]) {
3531         [delegate retain];
3532         [_private->frameLoadDelegate release];
3533     }
3534     
3535     _private->frameLoadDelegate = delegate;
3536     [self _cacheFrameLoadDelegateImplementations];
3537
3538 #if ENABLE(ICONDATABASE)
3539     // If this delegate wants callbacks for icons, fire up the icon database.
3540     if (_private->frameLoadDelegateImplementations.didReceiveIconForFrameFunc)
3541         [WebIconDatabase sharedIconDatabase];
3542 #endif
3543 }
3544
3545 - (id)frameLoadDelegate
3546 {
3547     return _private->frameLoadDelegate;
3548 }
3549
3550 - (WebFrame *)mainFrame
3551 {
3552     // This can be called in initialization, before _private has been set up (3465613)
3553     if (!_private || !_private->page)
3554         return nil;
3555     return kit(_private->page->mainFrame());
3556 }
3557
3558 - (WebFrame *)selectedFrame
3559 {
3560     if (_private->usesDocumentViews) {
3561         // If the first responder is a view in our tree, we get the frame containing the first responder.
3562         // This is faster than searching the frame hierarchy, and will give us a result even in the case
3563         // where the focused frame doesn't actually contain a selection.
3564         WebFrame *focusedFrame = [self _focusedFrame];
3565         if (focusedFrame)
3566             return focusedFrame;
3567     }
3568     
3569     // If the first responder is outside of our view tree, we search for a frame containing a selection.
3570     // There should be at most only one of these.
3571     return [[self mainFrame] _findFrameWithSelection];
3572 }
3573
3574 - (WebBackForwardList *)backForwardList
3575 {
3576     if (!_private->page)
3577         return nil;
3578     BackForwardListImpl* list = static_cast<BackForwardListImpl*>(_private->page->backForwardList());
3579     if (!list->enabled())
3580         return nil;
3581     return kit(list);
3582 }
3583
3584 - (void)setMaintainsBackForwardList:(BOOL)flag
3585 {
3586     if (!_private->page)
3587         return;
3588     static_cast<BackForwardListImpl*>(_private->page->backForwardList())->setEnabled(flag);
3589 }
3590
3591 - (BOOL)goBack
3592 {
3593     if (!_private->page)
3594         return NO;
3595     
3596     return _private->page->goBack();
3597 }
3598
3599 - (BOOL)goForward
3600 {
3601     if (!_private->page)
3602         return NO;
3603
3604     return _private->page->goForward();
3605 }
3606
3607 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
3608 {
3609     if (!_private->page)
3610         return NO;
3611
3612     _private->page->goToItem(core(item), FrameLoadTypeIndexedBackForward);
3613     return YES;