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