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