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