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