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