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