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