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