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