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