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