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