Only expose WKDataDetectorTypes and -[WKWebViewConfiguration dataDetectorTypes] on iOS
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / Cocoa / WKWebView.mm
1 /*
2  * Copyright (C) 2014-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WKWebViewInternal.h"
28
29 #if WK_API_ENABLED
30
31 #import "APIFormClient.h"
32 #import "APIPageConfiguration.h"
33 #import "APISerializedScriptValue.h"
34 #import "CompletionHandlerCallChecker.h"
35 #import "DiagnosticLoggingClient.h"
36 #import "FindClient.h"
37 #import "LegacySessionStateCoding.h"
38 #import "NavigationState.h"
39 #import "ObjCObjectGraph.h"
40 #import "RemoteLayerTreeScrollingPerformanceData.h"
41 #import "RemoteLayerTreeTransaction.h"
42 #import "RemoteObjectRegistry.h"
43 #import "RemoteObjectRegistryMessages.h"
44 #import "UIDelegate.h"
45 #import "ViewGestureController.h"
46 #import "ViewSnapshotStore.h"
47 #import "WKBackForwardListInternal.h"
48 #import "WKBackForwardListItemInternal.h"
49 #import "WKBrowsingContextHandleInternal.h"
50 #import "WKErrorInternal.h"
51 #import "WKHistoryDelegatePrivate.h"
52 #import "WKLayoutMode.h"
53 #import "WKNSData.h"
54 #import "WKNSURLExtras.h"
55 #import "WKNavigationDelegate.h"
56 #import "WKNavigationInternal.h"
57 #import "WKPreferencesInternal.h"
58 #import "WKProcessPoolInternal.h"
59 #import "WKSharedAPICast.h"
60 #import "WKUIDelegate.h"
61 #import "WKUIDelegatePrivate.h"
62 #import "WKUserContentControllerInternal.h"
63 #import "WKWebViewConfigurationInternal.h"
64 #import "WKWebViewContentProvider.h"
65 #import "WKWebsiteDataStoreInternal.h"
66 #import "WebBackForwardList.h"
67 #import "WebCertificateInfo.h"
68 #import "WebFormSubmissionListenerProxy.h"
69 #import "WebKitSystemInterface.h"
70 #import "WebPageGroup.h"
71 #import "WebPageProxy.h"
72 #import "WebPreferencesKeys.h"
73 #import "WebProcessPool.h"
74 #import "WebProcessProxy.h"
75 #import "WebViewImpl.h"
76 #import "_WKDiagnosticLoggingDelegate.h"
77 #import "_WKFindDelegate.h"
78 #import "_WKFormDelegate.h"
79 #import "_WKFrameHandleInternal.h"
80 #import "_WKHitTestResultInternal.h"
81 #import "_WKInputDelegate.h"
82 #import "_WKRemoteObjectRegistryInternal.h"
83 #import "_WKSessionStateInternal.h"
84 #import "_WKVisitedLinkStoreInternal.h"
85 #import <WebCore/IOSurface.h>
86 #import <WebCore/JSDOMBinding.h>
87 #import <WebCore/NSTextFinderSPI.h>
88 #import <WebCore/PlatformScreen.h>
89 #import <WebCore/RuntimeApplicationChecks.h>
90 #import <WebCore/Settings.h>
91 #import <WebCore/WritingMode.h>
92 #import <wtf/HashMap.h>
93 #import <wtf/MathExtras.h>
94 #import <wtf/NeverDestroyed.h>
95 #import <wtf/Optional.h>
96 #import <wtf/RetainPtr.h>
97 #import <wtf/TemporaryChange.h>
98
99 #if PLATFORM(IOS)
100 #import "_WKWebViewPrintFormatter.h"
101 #import "PrintInfo.h"
102 #import "ProcessThrottler.h"
103 #import "RemoteLayerTreeDrawingAreaProxy.h"
104 #import "RemoteScrollingCoordinatorProxy.h"
105 #import "UIKitSPI.h"
106 #import "WKContentViewInteraction.h"
107 #import "WKPDFView.h"
108 #import "WKScrollView.h"
109 #import "WKWebViewContentProviderRegistry.h"
110 #import "WebPageMessages.h"
111 #import "WebVideoFullscreenManagerProxy.h"
112 #import <UIKit/UIApplication.h>
113 #import <WebCore/CoreGraphicsSPI.h>
114 #import <WebCore/DynamicLinkerSPI.h>
115 #import <WebCore/FrameLoaderTypes.h>
116 #import <WebCore/InspectorOverlay.h>
117 #import <WebCore/QuartzCoreSPI.h>
118 #import <WebCore/ScrollableArea.h>
119
120 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
121 #if __has_include(<AccessibilitySupport.h>)
122 #include <AccessibilitySupport.h>
123 #else
124 extern "C" {
125 CFStringRef kAXSAllowForceWebScalingEnabledNotification;
126 }
127 #endif
128 #endif
129
130 @interface UIScrollView (UIScrollViewInternal)
131 - (void)_adjustForAutomaticKeyboardInfo:(NSDictionary*)info animated:(BOOL)animated lastAdjustment:(CGFloat*)lastAdjustment;
132 - (BOOL)_isScrollingToTop;
133 - (BOOL)_isInterruptingDeceleration;
134 - (CGPoint)_animatedTargetOffset;
135 @end
136
137 @interface UIPeripheralHost(UIKitInternal)
138 - (CGFloat)getVerticalOverlapForView:(UIView *)view usingKeyboardInfo:(NSDictionary *)info;
139 @end
140
141 @interface UIView (UIViewInternal)
142 - (UIViewController *)_viewControllerForAncestor;
143 @end
144
145 @interface UIWindow (UIWindowInternal)
146 - (BOOL)_isHostedInAnotherProcess;
147 @end
148
149 @interface UIViewController (UIViewControllerInternal)
150 - (UIViewController *)_rootAncestorViewController;
151 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
152 @end
153
154 enum class DynamicViewportUpdateMode {
155     NotResizing,
156     ResizingWithAnimation,
157     ResizingWithDocumentHidden,
158 };
159
160 #endif // PLATFORM(IOS)
161
162 #if PLATFORM(MAC)
163 #import "WKTextFinderClient.h"
164 #import "WKViewInternal.h"
165 #import <WebCore/ColorMac.h>
166
167 @interface WKWebView () <WebViewImplDelegate>
168 @end
169 #endif
170
171 static HashMap<WebKit::WebPageProxy*, WKWebView *>& pageToViewMap()
172 {
173     static NeverDestroyed<HashMap<WebKit::WebPageProxy*, WKWebView *>> map;
174     return map;
175 }
176
177 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
178 {
179     return pageToViewMap().get(&page);
180 }
181
182 @implementation WKWebView {
183     std::unique_ptr<WebKit::NavigationState> _navigationState;
184     std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
185
186     _WKRenderingProgressEvents _observedRenderingProgressEvents;
187
188     WebKit::WeakObjCPtr<id <_WKInputDelegate>> _inputDelegate;
189
190 #if PLATFORM(IOS)
191     RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
192
193     RetainPtr<WKScrollView> _scrollView;
194     RetainPtr<WKContentView> _contentView;
195
196     BOOL _overridesMinimumLayoutSize;
197     CGSize _minimumLayoutSizeOverride;
198     BOOL _overridesMaximumUnobscuredSize;
199     CGSize _maximumUnobscuredSizeOverride;
200     CGRect _inputViewBounds;
201     CGFloat _viewportMetaTagWidth;
202     BOOL _viewportMetaTagWidthWasExplicit;
203     BOOL _viewportMetaTagCameFromImageDocument;
204     CGFloat _initialScaleFactor;
205     BOOL _fastClickingIsDisabled;
206
207     BOOL _allowsLinkPreview;
208
209     UIEdgeInsets _obscuredInsets;
210     BOOL _haveSetObscuredInsets;
211     BOOL _isChangingObscuredInsetsInteractively;
212
213     UIInterfaceOrientation _interfaceOrientationOverride;
214     BOOL _overridesInterfaceOrientation;
215     
216     BOOL _allowsViewportShrinkToFit;
217
218     BOOL _hasCommittedLoadForMainFrame;
219     BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
220     uint64_t _firstPaintAfterCommitLoadTransactionID;
221     DynamicViewportUpdateMode _dynamicViewportUpdateMode;
222     CATransform3D _resizeAnimationTransformAdjustments;
223     uint64_t _resizeAnimationTransformTransactionID;
224     RetainPtr<UIView> _resizeAnimationView;
225     CGFloat _lastAdjustmentForScroller;
226     Optional<CGRect> _frozenVisibleContentRect;
227     Optional<CGRect> _frozenUnobscuredContentRect;
228
229     BOOL _needsToRestoreScrollPosition;
230     BOOL _commitDidRestoreScrollPosition;
231     WebCore::FloatPoint _scrollOffsetToRestore;
232     WebCore::FloatSize _obscuredInsetWhenSaved;
233
234     BOOL _needsToRestoreUnobscuredCenter;
235     WebCore::FloatPoint _unobscuredCenterToRestore;
236     uint64_t _firstTransactionIDAfterPageRestore;
237     double _scaleToRestore;
238
239     std::unique_ptr<WebKit::ViewGestureController> _gestureController;
240     BOOL _allowsBackForwardNavigationGestures;
241
242     RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
243     RetainPtr<UIView> _customContentFixedOverlayView;
244
245     RetainPtr<NSTimer> _enclosingScrollViewScrollTimer;
246     BOOL _didScrollSinceLastTimerFire;
247
248     WebCore::Color _scrollViewBackgroundColor;
249
250     // This value tracks the current adjustment added to the bottom inset due to the keyboard sliding out from the bottom
251     // when computing obscured content insets. This is used when updating the visible content rects where we should not
252     // include this adjustment.
253     CGFloat _totalScrollViewBottomInsetAdjustmentForKeyboard;
254     BOOL _currentlyAdjustingScrollViewInsetsForKeyboard;
255
256     BOOL _delayUpdateVisibleContentRects;
257     BOOL _hadDelayedUpdateVisibleContentRects;
258
259     BOOL _pageIsPrintingToPDF;
260     RetainPtr<CGPDFDocumentRef> _printedDocument;
261     Vector<std::function<void ()>> _snapshotsDeferredDuringResize;
262 #endif
263 #if PLATFORM(MAC)
264     std::unique_ptr<WebKit::WebViewImpl> _impl;
265     RetainPtr<WKTextFinderClient> _textFinderClient;
266 #endif
267 }
268
269 - (instancetype)initWithFrame:(CGRect)frame
270 {
271     return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
272 }
273
274 #if PLATFORM(IOS)
275 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
276 {
277     switch (orientation) {
278     case UIInterfaceOrientationUnknown:
279     case UIInterfaceOrientationPortrait:
280         return 0;
281     case UIInterfaceOrientationPortraitUpsideDown:
282         return 180;
283     case UIInterfaceOrientationLandscapeLeft:
284         return -90;
285     case UIInterfaceOrientationLandscapeRight:
286         return 90;
287     }
288 }
289
290 static int32_t deviceOrientation()
291 {
292     return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
293 }
294
295 - (BOOL)_isShowingVideoPictureInPicture
296 {
297 #if !HAVE(AVKIT)
298     return false;
299 #else
300     if (!_page || !_page->videoFullscreenManager())
301         return false;
302     
303     return _page->videoFullscreenManager()->hasMode(WebCore::HTMLMediaElementEnums::VideoFullscreenModePictureInPicture);
304 #endif
305 }
306
307 - (BOOL)_mayAutomaticallyShowVideoPictureInPicture
308 {
309 #if !HAVE(AVKIT)
310     return false;
311 #else
312     if (!_page || !_page->videoFullscreenManager())
313         return false;
314
315     return _page->videoFullscreenManager()->mayAutomaticallyShowVideoPictureInPicture();
316 #endif
317 }
318
319 static bool shouldAllowPictureInPictureMediaPlayback()
320 {
321     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
322     return shouldAllowPictureInPictureMediaPlayback;
323 }
324
325 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
326 static void forceAlwaysUserScalableChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
327 {
328     ASSERT(observer);
329     WKWebView* webview = static_cast<WKWebView*>(observer);
330     [webview _updateForceAlwaysUserScalable];
331 }
332 #endif
333
334 #endif
335
336 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS)
337 static WebCore::DataDetectorTypes fromWKDataDetectorTypes(uint64_t types)
338 {
339     if (static_cast<WKDataDetectorTypes>(types) == WKDataDetectorTypeNone)
340         return WebCore::DataDetectorTypeNone;
341     if (static_cast<WKDataDetectorTypes>(types) == WKDataDetectorTypeAll)
342         return WebCore::DataDetectorTypeAll;
343     
344     uint32_t value = WebCore::DataDetectorTypeNone;
345     if (types & WKDataDetectorTypePhoneNumber)
346         value |= WebCore::DataDetectorTypePhoneNumber;
347     if (types & WKDataDetectorTypeLink)
348         value |= WebCore::DataDetectorTypeLink;
349     if (types & WKDataDetectorTypeAddress)
350         value |= WebCore::DataDetectorTypeAddress;
351     if (types & WKDataDetectorTypeCalendarEvent)
352         value |= WebCore::DataDetectorTypeCalendarEvent;
353     if (types & WKDataDetectorTypeTrackingNumber)
354         value |= WebCore::DataDetectorTypeTrackingNumber;
355     if (types & WKDataDetectorTypeFlightNumber)
356         value |= WebCore::DataDetectorTypeFlightNumber;
357     if (types & WKDataDetectorTypeSpotlightSuggestion)
358         value |= WebCore::DataDetectorTypeSpotlightSuggestion;
359
360     return static_cast<WebCore::DataDetectorTypes>(value);
361 }
362 #endif
363
364 #if PLATFORM(MAC)
365 static uint32_t convertUserInterfaceDirectionPolicy(WKUserInterfaceDirectionPolicy policy)
366 {
367     switch (policy) {
368     case WKUserInterfaceDirectionPolicyContent:
369         return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
370     case WKUserInterfaceDirectionPolicySystem:
371         return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::System);
372     }
373     return static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content);
374 }
375
376 static uint32_t convertSystemLayoutDirection(NSUserInterfaceLayoutDirection direction)
377 {
378     switch (direction) {
379     case NSUserInterfaceLayoutDirectionLeftToRight:
380         return static_cast<uint32_t>(WebCore::LTR);
381     case NSUserInterfaceLayoutDirectionRightToLeft:
382         return static_cast<uint32_t>(WebCore::RTL);
383     }
384     return static_cast<uint32_t>(WebCore::LTR);
385 }
386 #endif
387
388 - (void)_initializeWithConfiguration:(WKWebViewConfiguration *)configuration
389 {
390     if (!configuration)
391         [NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
392
393     _configuration = adoptNS([configuration copy]);
394
395     if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
396         WKProcessPool *processPool = [_configuration processPool];
397         WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
398         if (processPool && processPool != relatedWebViewProcessPool)
399             [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
400
401         [_configuration setProcessPool:relatedWebViewProcessPool];
402     }
403
404     [_configuration _validate];
405
406     WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
407     processPool.setResourceLoadStatisticsEnabled(configuration.websiteDataStore._resourceLoadStatisticsEnabled);
408     
409     auto pageConfiguration = API::PageConfiguration::create();
410
411     pageConfiguration->setProcessPool(&processPool);
412     pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
413     if (WKWebView *relatedWebView = [_configuration _relatedWebView])
414         pageConfiguration->setRelatedPage(relatedWebView->_page.get());
415
416     pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
417     pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
418     pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
419     pageConfiguration->setTreatsSHA1SignedCertificatesAsInsecure([_configuration _treatsSHA1SignedCertificatesAsInsecure]);
420
421     RefPtr<WebKit::WebPageGroup> pageGroup;
422     NSString *groupIdentifier = configuration._groupIdentifier;
423     if (groupIdentifier.length) {
424         pageGroup = WebKit::WebPageGroup::create(configuration._groupIdentifier);
425         pageConfiguration->setPageGroup(pageGroup.get());
426     }
427
428     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
429
430     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldRespectImageOrientationKey(), WebKit::WebPreferencesStore::Value(!![_configuration _respectsImageOrientation]));
431     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldPrintBackgroundsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _printsBackgrounds]));
432     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey(), WebKit::WebPreferencesStore::Value([_configuration _incrementalRenderingSuppressionTimeout]));
433     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::javaScriptMarkupEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsJavaScriptMarkup]));
434     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::shouldConvertPositionStyleOnCopyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _convertsPositionStyleOnCopy]));
435     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::httpEquivEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowsMetaRefresh]));
436     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowUniversalAccessFromFileURLsKey(), WebKit::WebPreferencesStore::Value(!![_configuration _allowUniversalAccessFromFileURLs]));
437     
438 #if PLATFORM(MAC)
439     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::showsURLsInToolTipsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _showsURLsInToolTips]));
440     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::serviceControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _serviceControlsEnabled]));
441     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::imageControlsEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _imageControlsEnabled]));
442
443     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(convertUserInterfaceDirectionPolicy([_configuration userInterfaceDirectionPolicy])));
444     // We are in the View's initialization routine, so our client hasn't had time to set our user interface direction.
445     // Therefore, according to the docs[1], "this property contains the value reported by the app's userInterfaceLayoutDirection property."
446     // [1] http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/index.html#//apple_ref/doc/uid/20000014-SW222
447     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(convertSystemLayoutDirection(self.userInterfaceLayoutDirection)));
448 #endif
449
450 #if PLATFORM(IOS)
451     pageConfiguration->setAlwaysRunsAtForegroundPriority([_configuration _alwaysRunsAtForegroundPriority]);
452
453     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
454     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey(), WebKit::WebPreferencesStore::Value(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]));
455     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback()));
456     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration requiresUserActionForMediaPlayback]));
457     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::userInterfaceDirectionPolicyKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::UserInterfaceDirectionPolicy::Content)));
458     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::systemLayoutDirectionKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(WebCore::LTR)));
459 #endif
460
461     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForVideoPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration _requiresUserActionForVideoPlayback]));
462     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForAudioPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration _requiresUserActionForAudioPlayback]));
463     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mainContentUserGestureOverrideEnabledKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mainContentUserGestureOverrideEnabled]));
464     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::invisibleAutoplayNotPermittedKey(), WebKit::WebPreferencesStore::Value(!![_configuration _invisibleAutoplayNotPermitted]));
465     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaDataLoadsAutomaticallyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mediaDataLoadsAutomatically]));
466
467 // FIXME: <rdar://problem/25135244> Remove bundle checks for attachmentElementEnabled
468 #if PLATFORM(IOS)
469     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(WebCore::IOSApplication::isMobileMail() ? true : !![_configuration _attachmentElementEnabled]));
470 #else
471     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::attachmentElementEnabledKey(), WebKit::WebPreferencesStore::Value(WebCore::MacApplication::isAppleMail() ? true : !![_configuration _attachmentElementEnabled]));
472 #endif
473
474 #if ENABLE(DATA_DETECTION) && PLATFORM(IOS)
475     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::dataDetectorTypesKey(), WebKit::WebPreferencesStore::Value(static_cast<uint32_t>(fromWKDataDetectorTypes([_configuration dataDetectorTypes]))));
476 #endif
477 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
478     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsAirPlayForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsAirPlayForMediaPlayback]));
479 #endif
480
481 #if USE(APPLE_INTERNAL_SDK)
482 #import <WebKitAdditions/WKWebViewInitialization.mm>
483 #endif
484
485 #if PLATFORM(IOS)
486     CGRect bounds = self.bounds;
487     _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
488     [_scrollView setInternalDelegate:self];
489     [_scrollView setBouncesZoom:YES];
490
491     [self addSubview:_scrollView.get()];
492
493     _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds processPool:processPool configuration:WTFMove(pageConfiguration) webView:self]);
494
495     _page = [_contentView page];
496     _page->setDeviceOrientation(deviceOrientation());
497
498     [_contentView layer].anchorPoint = CGPointZero;
499     [_contentView setFrame:bounds];
500     [_scrollView addSubview:_contentView.get()];
501     [_scrollView addSubview:[_contentView unscaledView]];
502     [self _updateScrollViewBackground];
503
504     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
505     _initialScaleFactor = 1;
506     _fastClickingIsDisabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitFastClickingDisabled"];
507
508     [self _frameOrBoundsChanged];
509
510     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
511     [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
512     [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
513     [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
514     [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
515     [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
516     [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
517     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
518     
519 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
520     CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), forceAlwaysUserScalableChangedCallback, kAXSAllowForceWebScalingEnabledNotification, 0, CFNotificationSuspensionBehaviorDeliverImmediately);
521 #endif
522
523     [[_configuration _contentProviderRegistry] addPage:*_page];
524 #endif
525
526 #if PLATFORM(MAC)
527     _impl = std::make_unique<WebKit::WebViewImpl>(self, self, processPool, WTFMove(pageConfiguration));
528     _page = &_impl->page();
529
530     _impl->setAutomaticallyAdjustsContentInsets(true);
531 #endif
532
533     _page->setBackgroundExtendsBeyondPage(true);
534
535     if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
536         _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
537
538     _navigationState = std::make_unique<WebKit::NavigationState>(self);
539     _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
540     _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
541     _page->setDiagnosticLoggingClient(std::make_unique<WebKit::DiagnosticLoggingClient>(self));
542
543     pageToViewMap().add(_page.get(), self);
544 }
545
546 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
547 {
548     if (!(self = [super initWithFrame:frame]))
549         return nil;
550
551     [self _initializeWithConfiguration:configuration];
552
553     return self;
554 }
555
556 - (instancetype)initWithCoder:(NSCoder *)coder
557 {
558     if (!(self = [super initWithCoder:coder]))
559         return nil;
560
561     WKWebViewConfiguration *configuration = [coder decodeObjectForKey:@"configuration"];
562     [self _initializeWithConfiguration:configuration];
563
564     self.allowsBackForwardNavigationGestures = [coder decodeBoolForKey:@"allowsBackForwardNavigationGestures"];
565     self.customUserAgent = [coder decodeObjectForKey:@"customUserAgent"];
566     self.allowsLinkPreview = [coder decodeBoolForKey:@"allowsLinkPreview"];
567
568 #if PLATFORM(MAC)
569     self.allowsMagnification = [coder decodeBoolForKey:@"allowsMagnification"];
570     self.magnification = [coder decodeDoubleForKey:@"magnification"];
571 #endif
572
573     return self;
574 }
575
576 - (void)encodeWithCoder:(NSCoder *)coder
577 {
578     [coder encodeObject:_configuration.get() forKey:@"configuration"];
579
580     [coder encodeBool:self.allowsBackForwardNavigationGestures forKey:@"allowsBackForwardNavigationGestures"];
581     [coder encodeObject:self.customUserAgent forKey:@"customUserAgent"];
582     [coder encodeBool:self.allowsLinkPreview forKey:@"allowsLinkPreview"];
583
584 #if PLATFORM(MAC)
585     [coder encodeBool:self.allowsMagnification forKey:@"allowsMagnification"];
586     [coder encodeDouble:self.magnification forKey:@"magnification"];
587 #endif
588 }
589
590 - (void)dealloc
591 {
592 #if PLATFORM(MAC)
593     [_textFinderClient willDestroyView:self];
594 #endif
595
596 #if PLATFORM(IOS)
597     [_contentView _webViewDestroyed];
598
599     if (_remoteObjectRegistry)
600         _page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID());
601
602     _page->close();
603
604     [_remoteObjectRegistry _invalidate];
605     [[_configuration _contentProviderRegistry] removePage:*_page];
606 #if PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
607     CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), nullptr, nullptr);
608 #endif
609     [[NSNotificationCenter defaultCenter] removeObserver:self];
610     [_scrollView setInternalDelegate:nil];
611 #endif
612
613     pageToViewMap().remove(_page.get());
614
615     [super dealloc];
616 }
617
618 - (WKWebViewConfiguration *)configuration
619 {
620     return [[_configuration copy] autorelease];
621 }
622
623 - (WKBackForwardList *)backForwardList
624 {
625     return wrapper(_page->backForwardList());
626 }
627
628 - (id <WKNavigationDelegate>)navigationDelegate
629 {
630     return _navigationState->navigationDelegate().autorelease();
631 }
632
633 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
634 {
635     _page->setNavigationClient(_navigationState->createNavigationClient());
636     _navigationState->setNavigationDelegate(navigationDelegate);
637 }
638
639 - (id <WKUIDelegate>)UIDelegate
640 {
641     return _uiDelegate->delegate().autorelease();
642 }
643
644 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
645 {
646 #if ENABLE(CONTEXT_MENUS)
647     _page->setContextMenuClient(_uiDelegate->createContextMenuClient());
648 #endif
649     _page->setUIClient(_uiDelegate->createUIClient());
650     _uiDelegate->setDelegate(UIDelegate);
651 }
652
653 - (WKNavigation *)loadRequest:(NSURLRequest *)request
654 {
655     auto navigation = _page->loadRequest(request);
656     if (!navigation)
657         return nil;
658
659     return [wrapper(*navigation.release().leakRef()) autorelease];
660 }
661
662 - (WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
663 {
664     if (![URL isFileURL])
665         [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", URL];
666
667     if (![readAccessURL isFileURL])
668         [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", readAccessURL];
669
670     auto navigation = _page->loadFile([URL _web_originalDataAsWTFString], [readAccessURL _web_originalDataAsWTFString]);
671     if (!navigation)
672         return nil;
673
674     return [wrapper(*navigation.release().leakRef()) autorelease];
675 }
676
677 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
678 {
679     NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
680
681     return [self loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL];
682 }
683
684 - (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
685 {
686     auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString);
687     if (!navigation)
688         return nil;
689
690     return [wrapper(*navigation.release().leakRef()) autorelease];
691 }
692
693 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
694 {
695     auto navigation = _page->goToBackForwardItem(&item._item);
696     if (!navigation)
697         return nil;
698
699     return [wrapper(*navigation.release().leakRef()) autorelease];
700 }
701
702 - (NSString *)title
703 {
704     return _page->pageLoadState().title();
705 }
706
707 - (NSURL *)URL
708 {
709     return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
710 }
711
712 - (BOOL)isLoading
713 {
714     return _page->pageLoadState().isLoading();
715 }
716
717 - (double)estimatedProgress
718 {
719     return _page->pageLoadState().estimatedProgress();
720 }
721
722 - (BOOL)hasOnlySecureContent
723 {
724     return _page->pageLoadState().hasOnlySecureContent();
725 }
726
727 - (SecTrustRef)serverTrust
728 {
729 #if HAVE(SEC_TRUST_SERIALIZATION)
730     auto certificateInfo = _page->pageLoadState().certificateInfo();
731     if (!certificateInfo)
732         return nil;
733
734     return certificateInfo->certificateInfo().trust();
735 #else
736     return nil;
737 #endif
738 }
739
740 - (BOOL)canGoBack
741 {
742     return _page->pageLoadState().canGoBack();
743 }
744
745 - (BOOL)canGoForward
746 {
747     return _page->pageLoadState().canGoForward();
748 }
749
750 - (WKNavigation *)goBack
751 {
752     auto navigation = _page->goBack();
753     if (!navigation)
754         return nil;
755  
756     return [wrapper(*navigation.release().leakRef()) autorelease];
757 }
758
759 - (WKNavigation *)goForward
760 {
761     auto navigation = _page->goForward();
762     if (!navigation)
763         return nil;
764
765     return [wrapper(*navigation.release().leakRef()) autorelease];
766 }
767
768 - (WKNavigation *)reload
769 {
770     const bool reloadFromOrigin = false;
771     const bool contentBlockersEnabled = true;
772     auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
773     if (!navigation)
774         return nil;
775
776     return [wrapper(*navigation.release().leakRef()) autorelease];
777 }
778
779 - (WKNavigation *)reloadFromOrigin
780 {
781     const bool reloadFromOrigin = true;
782     const bool contentBlockersEnabled = true;
783     auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
784     if (!navigation)
785         return nil;
786
787     return [wrapper(*navigation.release().leakRef()) autorelease];
788 }
789
790 - (void)stopLoading
791 {
792     _page->stopLoading();
793 }
794
795 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
796 {
797     switch (error) {
798     case WebKit::CallbackBase::Error::None:
799         ASSERT_NOT_REACHED();
800         return WKErrorUnknown;
801
802     case WebKit::CallbackBase::Error::Unknown:
803         return WKErrorUnknown;
804
805     case WebKit::CallbackBase::Error::ProcessExited:
806         return WKErrorWebContentProcessTerminated;
807
808     case WebKit::CallbackBase::Error::OwnerWasInvalidated:
809         return WKErrorWebViewInvalidated;
810     }
811 }
812
813 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
814 {
815     auto handler = adoptNS([completionHandler copy]);
816
817     _page->runJavaScriptInMainFrame(javaScriptString, [handler](API::SerializedScriptValue* serializedScriptValue, bool hadException, const WebCore::ExceptionDetails& details, WebKit::ScriptValueCallback::Error errorCode) {
818         if (!handler)
819             return;
820
821         if (errorCode != WebKit::ScriptValueCallback::Error::None) {
822             auto error = createNSError(callbackErrorCode(errorCode));
823             if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
824                 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
825                 // because that can trigger re-entrancy bugs in WebKit.
826                 // FIXME: It would be even better if GenericCallback did this for us.
827                 dispatch_async(dispatch_get_main_queue(), [handler, error] {
828                     auto rawHandler = (void (^)(id, NSError *))handler.get();
829                     rawHandler(nil, error.get());
830                 });
831                 return;
832             }
833
834             auto rawHandler = (void (^)(id, NSError *))handler.get();
835             rawHandler(nil, error.get());
836             return;
837         }
838
839         auto rawHandler = (void (^)(id, NSError *))handler.get();
840         if (hadException) {
841             ASSERT(!serializedScriptValue);
842
843             RetainPtr<NSMutableDictionary> userInfo = adoptNS([[NSMutableDictionary alloc] init]);
844
845             [userInfo setObject:localizedDescriptionForErrorCode(WKErrorJavaScriptExceptionOccurred) forKey:NSLocalizedDescriptionKey];
846             [userInfo setObject:static_cast<NSString *>(details.message) forKey:_WKJavaScriptExceptionMessageErrorKey];
847             [userInfo setObject:@(details.lineNumber) forKey:_WKJavaScriptExceptionLineNumberErrorKey];
848             [userInfo setObject:@(details.columnNumber) forKey:_WKJavaScriptExceptionColumnNumberErrorKey];
849
850             if (!details.sourceURL.isEmpty())
851                 [userInfo setObject:[NSURL _web_URLWithWTFString:details.sourceURL] forKey:_WKJavaScriptExceptionSourceURLErrorKey];
852
853             rawHandler(nil, adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:WKErrorJavaScriptExceptionOccurred userInfo:userInfo.get()]).get());
854             return;
855         }
856
857         if (!serializedScriptValue) {
858             rawHandler(nil, createNSError(WKErrorJavaScriptResultTypeIsUnsupported).get());
859             return;
860         }
861
862         id body = API::SerializedScriptValue::deserialize(*serializedScriptValue->internalRepresentation(), 0);
863         rawHandler(body, nil);
864     });
865 }
866
867 - (NSString *)customUserAgent
868 {
869     return _page->customUserAgent();
870 }
871
872 - (void)setCustomUserAgent:(NSString *)customUserAgent
873 {
874     _page->setCustomUserAgent(customUserAgent);
875 }
876
877 - (WKPageRef)_pageForTesting
878 {
879     return toAPI(_page.get());
880 }
881
882 - (BOOL)allowsLinkPreview
883 {
884 #if PLATFORM(MAC)
885     return _impl->allowsLinkPreview();
886 #elif PLATFORM(IOS)
887     return _allowsLinkPreview;
888 #endif
889 }
890
891 - (void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
892 {
893 #if PLATFORM(MAC)
894     _impl->setAllowsLinkPreview(allowsLinkPreview);
895     return;
896 #elif PLATFORM(IOS)
897     if (_allowsLinkPreview == allowsLinkPreview)
898         return;
899
900     _allowsLinkPreview = allowsLinkPreview;
901
902 #if HAVE(LINK_PREVIEW)
903     if (_allowsLinkPreview)
904         [_contentView _registerPreview];
905     else
906         [_contentView _unregisterPreview];
907 #endif // HAVE(LINK_PREVIEW)
908 #endif // PLATFORM(IOS)
909 }
910
911 #pragma mark iOS-specific methods
912
913 #if PLATFORM(IOS)
914
915 - (BOOL)_isBackground
916 {
917     if ([self _isDisplayingPDF])
918         return [(WKPDFView *)_customContentView isBackground];
919
920     return [_contentView isBackground];
921 }
922
923 - (void)setFrame:(CGRect)frame
924 {
925     CGRect oldFrame = self.frame;
926     [super setFrame:frame];
927
928     if (!CGSizeEqualToSize(oldFrame.size, frame.size))
929         [self _frameOrBoundsChanged];
930 }
931
932 - (void)setBounds:(CGRect)bounds
933 {
934     CGRect oldBounds = self.bounds;
935     [super setBounds:bounds];
936     [_customContentFixedOverlayView setFrame:self.bounds];
937
938     if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
939         [self _frameOrBoundsChanged];
940 }
941
942 - (UIScrollView *)scrollView
943 {
944     return _scrollView.get();
945 }
946
947 - (WKBrowsingContextController *)browsingContextController
948 {
949     return [_contentView browsingContextController];
950 }
951
952 - (BOOL)becomeFirstResponder
953 {
954     return [self._currentContentView becomeFirstResponder] || [super becomeFirstResponder];
955 }
956
957 - (BOOL)canBecomeFirstResponder
958 {
959     if (self._currentContentView == _contentView && [_contentView isResigningFirstResponder])
960         return NO;
961     return YES;
962 }
963
964 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
965 {
966     return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
967 }
968
969 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
970 {
971     return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
972         && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
973 }
974
975 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
976 {
977     float deviceScaleFactor = page.deviceScaleFactor();
978     return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
979 }
980
981 - (UIView *)_currentContentView
982 {
983     return _customContentView ? _customContentView.get() : _contentView.get();
984 }
985
986 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
987 {
988     return [_configuration _contentProviderRegistry];
989 }
990
991 - (WKSelectionGranularity)_selectionGranularity
992 {
993     return [_configuration selectionGranularity];
994 }
995
996 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
997 {
998     if (pageHasCustomContentView) {
999         [_customContentView removeFromSuperview];
1000         [_customContentFixedOverlayView removeFromSuperview];
1001
1002         Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1003         ASSERT(representationClass);
1004         _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self]);
1005         _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1006         [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1007
1008         [[_contentView unscaledView] removeFromSuperview];
1009         [_contentView removeFromSuperview];
1010         [_scrollView addSubview:_customContentView.get()];
1011         [self addSubview:_customContentFixedOverlayView.get()];
1012
1013         [_customContentView web_setMinimumSize:self.bounds.size];
1014         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1015     } else if (_customContentView) {
1016         [_customContentView removeFromSuperview];
1017         _customContentView = nullptr;
1018
1019         [_customContentFixedOverlayView removeFromSuperview];
1020         _customContentFixedOverlayView = nullptr;
1021
1022         [_scrollView addSubview:_contentView.get()];
1023         [_scrollView addSubview:[_contentView unscaledView]];
1024         [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1025
1026         [_customContentFixedOverlayView setFrame:self.bounds];
1027         [self addSubview:_customContentFixedOverlayView.get()];
1028     }
1029
1030     if (self.isFirstResponder && self._currentContentView.canBecomeFirstResponder)
1031         [self._currentContentView becomeFirstResponder];
1032 }
1033
1034 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1035 {
1036     ASSERT(_customContentView);
1037     [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1038
1039     // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1040     // because there's no guarantee that all custom content providers will lay out synchronously.
1041     _page->didLayoutForCustomContentProvider();
1042 }
1043
1044 - (void)_willInvokeUIScrollViewDelegateCallback
1045 {
1046     _delayUpdateVisibleContentRects = YES;
1047 }
1048
1049 - (void)_didInvokeUIScrollViewDelegateCallback
1050 {
1051     _delayUpdateVisibleContentRects = NO;
1052     if (_hadDelayedUpdateVisibleContentRects) {
1053         _hadDelayedUpdateVisibleContentRects = NO;
1054         [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
1055     }
1056 }
1057
1058 static CGFloat contentZoomScale(WKWebView *webView)
1059 {
1060     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1061     ASSERT(scale == [webView->_scrollView zoomScale]);
1062     return scale;
1063 }
1064
1065 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1066 {
1067     if (webView->_customContentView)
1068         return [webView->_customContentView backgroundColor].CGColor;
1069
1070     if (webView->_gestureController) {
1071         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1072         if (color.isValid())
1073             return color;
1074     }
1075
1076     return webView->_page->pageExtendedBackgroundColor();
1077 }
1078
1079 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1080 {
1081     if (!webView.opaque)
1082         return WebCore::Color::transparent;
1083
1084     WebCore::Color color = baseScrollViewBackgroundColor(webView);
1085
1086     if (!color.isValid())
1087         color = WebCore::Color::white;
1088
1089     CGFloat zoomScale = contentZoomScale(webView);
1090     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1091     if (zoomScale < minimumZoomScale) {
1092         CGFloat slope = 12;
1093         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1094         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1095     }
1096
1097     return color;
1098 }
1099
1100 - (void)_updateScrollViewBackground
1101 {
1102     WebCore::Color color = scrollViewBackgroundColor(self);
1103
1104     if (_scrollViewBackgroundColor == color)
1105         return;
1106
1107     _scrollViewBackgroundColor = color;
1108
1109     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1110     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1111
1112     // Update the indicator style based on the lightness/darkness of the background color.
1113     double hue, saturation, lightness;
1114     color.getHSL(hue, saturation, lightness);
1115     if (lightness <= .5 && color.alpha() > 0)
1116         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1117     else
1118         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1119 }
1120
1121 - (CGPoint)_adjustedContentOffset:(CGPoint)point
1122 {
1123     CGPoint result = point;
1124     UIEdgeInsets contentInset = [self _computedContentInset];
1125
1126     result.x -= contentInset.left;
1127     result.y -= contentInset.top;
1128
1129     return result;
1130 }
1131
1132 - (UIEdgeInsets)_computedContentInset
1133 {
1134     if (_haveSetObscuredInsets)
1135         return _obscuredInsets;
1136
1137     return [_scrollView contentInset];
1138 }
1139
1140 - (void)_processDidExit
1141 {
1142     if (!_customContentView && _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1143         NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
1144         [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
1145         [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
1146         [_resizeAnimationView removeFromSuperview];
1147         _resizeAnimationView = nil;
1148
1149         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
1150     }
1151     [_contentView setFrame:self.bounds];
1152     [_scrollView setBackgroundColor:[UIColor whiteColor]];
1153     [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1154     [_scrollView setZoomScale:1];
1155
1156     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1157     _initialScaleFactor = 1;
1158     _hasCommittedLoadForMainFrame = NO;
1159     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1160     _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
1161     [_contentView setHidden:NO];
1162     _needsToRestoreScrollPosition = NO;
1163     _needsToRestoreUnobscuredCenter = NO;
1164     _scrollViewBackgroundColor = WebCore::Color();
1165     _delayUpdateVisibleContentRects = NO;
1166     _hadDelayedUpdateVisibleContentRects = NO;
1167 }
1168
1169 - (void)_didCommitLoadForMainFrame
1170 {
1171     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1172
1173     _hasCommittedLoadForMainFrame = YES;
1174     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1175 }
1176
1177 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1178 {
1179     UIEdgeInsets contentInsets = scrollView.contentInset;
1180     CGSize contentSize = scrollView.contentSize;
1181     CGSize scrollViewSize = scrollView.bounds.size;
1182
1183     CGFloat maxHorizontalOffset = contentSize.width + contentInsets.right - scrollViewSize.width;
1184     contentOffset.x = std::min(maxHorizontalOffset, contentOffset.x);
1185     contentOffset.x = std::max(-contentInsets.left, contentOffset.x);
1186
1187     CGFloat maxVerticalOffset = contentSize.height + contentInsets.bottom - scrollViewSize.height;
1188     contentOffset.y = std::min(maxVerticalOffset, contentOffset.y);
1189     contentOffset.y = std::max(-contentInsets.top, contentOffset.y);
1190     return contentOffset;
1191 }
1192
1193 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1194 {
1195     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1196 }
1197
1198 - (WebCore::FloatRect)visibleRectInViewCoordinates
1199 {
1200     WebCore::FloatRect bounds = self.bounds;
1201     bounds.moveBy([_scrollView contentOffset]);
1202     WebCore::FloatRect contentViewBounds = [_contentView bounds];
1203     bounds.intersect(contentViewBounds);
1204     return bounds;
1205 }
1206
1207 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1208 // we need to ignore differences that are within a small rounding error on floats.
1209 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1210 {
1211     return WTF::areEssentiallyEqual(a, b);
1212 }
1213
1214 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1215 {
1216     if (_customContentView)
1217         return;
1218
1219     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1220         if (layerTreeTransaction.transactionID() >= _resizeAnimationTransformTransactionID) {
1221             [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1222             if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithDocumentHidden) {
1223                 [_contentView setHidden:NO];
1224                 [self _endAnimatedResize];
1225             }
1226         }
1227         return;
1228     }
1229
1230     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1231     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1232
1233     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1234     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1235     [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1236     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom])
1237         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1238
1239     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1240     _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1241     _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1242     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1243     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1244         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1245
1246     [self _updateScrollViewBackground];
1247
1248     if (_gestureController)
1249         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1250
1251     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1252         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1253         [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1254         [self _updateVisibleContentRects];
1255         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1256             _navigationState->didFirstPaint();
1257     }
1258
1259     bool isTransactionAfterPageRestore = layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore;
1260
1261     if (_needsToRestoreScrollPosition && isTransactionAfterPageRestore) {
1262         _needsToRestoreScrollPosition = NO;
1263
1264         if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1265             WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore;
1266             scaledScrollOffset.scale(_scaleToRestore, _scaleToRestore);
1267             WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - _obscuredInsetWhenSaved;
1268
1269             changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1270             _commitDidRestoreScrollPosition = YES;
1271
1272             if (_gestureController)
1273                 _gestureController->didRestoreScrollPosition();
1274         }
1275         [self _updateVisibleContentRects];
1276     }
1277
1278     if (_needsToRestoreUnobscuredCenter && isTransactionAfterPageRestore) {
1279         _needsToRestoreUnobscuredCenter = NO;
1280
1281         if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1282             CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1283             WebCore::FloatSize unobscuredContentSizeAtNewScale(unobscuredRect.size.width / _scaleToRestore, unobscuredRect.size.height / _scaleToRestore);
1284             WebCore::FloatPoint topLeftInDocumentCoordinates(_unobscuredCenterToRestore.x() - unobscuredContentSizeAtNewScale.width() / 2, _unobscuredCenterToRestore.y() - unobscuredContentSizeAtNewScale.height() / 2);
1285
1286             topLeftInDocumentCoordinates.scale(_scaleToRestore, _scaleToRestore);
1287             topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1288
1289             changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1290             if (_gestureController)
1291                 _gestureController->didRestoreScrollPosition();
1292         }
1293         [self _updateVisibleContentRects];
1294     }
1295     
1296     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1297         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1298 }
1299
1300 - (void)_layerTreeCommitComplete
1301 {
1302     _commitDidRestoreScrollPosition = NO;
1303 }
1304
1305 - (void)_dynamicViewportUpdateChangedTargetToScale:(double)newScale position:(CGPoint)newScrollPosition nextValidLayerTreeTransactionID:(uint64_t)nextValidLayerTreeTransactionID
1306 {
1307     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1308         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1309         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1310         double scale = newScale / currentTargetScale;
1311         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1312
1313         CGPoint newContentOffset = [self _adjustedContentOffset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
1314         CGPoint currentContentOffset = [_scrollView contentOffset];
1315
1316         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1317         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1318         _resizeAnimationTransformTransactionID = nextValidLayerTreeTransactionID;
1319     }
1320 }
1321
1322 - (void)_couldNotRestorePageState
1323 {
1324     // The gestureController may be waiting for the scroll position to be restored
1325     // in order to remove the swipe snapshot. Since the scroll position could not be
1326     // restored, tell the gestureController it was restored so that it no longer waits
1327     // for it.
1328     if (_gestureController)
1329         _gestureController->didRestoreScrollPosition();
1330 }
1331
1332 - (void)_restorePageScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatSize)obscuredInset scale:(double)scale
1333 {
1334     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1335         return;
1336
1337     if (_customContentView)
1338         return;
1339
1340     _needsToRestoreUnobscuredCenter = NO;
1341     _needsToRestoreScrollPosition = YES;
1342     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1343     
1344     _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition), WebCore::toFloatSize(scrollOrigin));
1345     _obscuredInsetWhenSaved = obscuredInset;
1346     _scaleToRestore = scale;
1347 }
1348
1349 - (void)_restorePageStateToUnobscuredCenter:(WebCore::FloatPoint)center scale:(double)scale
1350 {
1351     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1352         return;
1353
1354     if (_customContentView)
1355         return;
1356
1357     _needsToRestoreScrollPosition = NO;
1358     _needsToRestoreUnobscuredCenter = YES;
1359     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1360     _unobscuredCenterToRestore = center;
1361     _scaleToRestore = scale;
1362 }
1363
1364 - (PassRefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
1365 {
1366     float deviceScale = WebCore::screenScaleFactor();
1367     WebCore::FloatSize snapshotSize(self.bounds.size);
1368     snapshotSize.scale(deviceScale, deviceScale);
1369
1370     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
1371
1372 #if USE(IOSURFACE)
1373     WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
1374     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::ColorSpaceSRGB, snapshotFormat);
1375     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
1376
1377     WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
1378     if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
1379         RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
1380         WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
1381             viewSnapshot->setSurface(WTFMove(convertedSurface));
1382         });
1383
1384         return viewSnapshot;
1385     }
1386
1387     return WebKit::ViewSnapshot::create(WTFMove(surface));
1388 #else
1389     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
1390
1391     if (!slotID)
1392         return nullptr;
1393
1394     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
1395     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
1396     return WebKit::ViewSnapshot::create(slotID, imageSize, imageSize.width() * imageSize.height() * 4);
1397 #endif
1398 }
1399
1400 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
1401 {
1402     CFTimeInterval duration = 0;
1403     CGFloat zoomScale = contentZoomScale(self);
1404
1405     if (animated) {
1406         const double maximumZoomDuration = 0.4;
1407         const double minimumZoomDuration = 0.1;
1408         const double zoomDurationFactor = 0.3;
1409
1410         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
1411     }
1412
1413     if (scale != zoomScale)
1414         _page->willStartUserTriggeredZooming();
1415
1416     [_scrollView _zoomToCenter:point scale:scale duration:duration];
1417 }
1418
1419 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1420 {
1421     // FIXME: Some of this could be shared with _scrollToRect.
1422     const double visibleRectScaleChange = contentZoomScale(self) / scale;
1423     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
1424     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
1425
1426     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
1427     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
1428
1429     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
1430
1431     // Center to the target rect.
1432     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
1433
1434     // Center to the tap point instead in case the target rect won't fit in a direction.
1435     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
1436         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
1437     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
1438         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
1439
1440     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
1441     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
1442     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
1443     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
1444
1445     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
1446 }
1447
1448 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
1449 {
1450     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
1451     return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
1452 }
1453
1454 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
1455 {
1456     if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1457         return;
1458
1459     WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
1460
1461     WebCore::FloatPoint scaledOffset = contentOffset;
1462     CGFloat zoomScale = contentZoomScale(self);
1463     scaledOffset.scale(zoomScale, zoomScale);
1464
1465     CGPoint contentOffsetInScrollViewCoordinates = [self _adjustedContentOffset:scaledOffset];
1466     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1467
1468     [_scrollView _stopScrollingAndZoomingAnimations];
1469
1470     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
1471         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
1472     else {
1473         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
1474         // The WebProcess would keep the invalid contentOffset as its scroll position.
1475         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
1476         _page->resendLastVisibleContentRects();
1477     }
1478 }
1479
1480 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
1481 {
1482     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
1483     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
1484     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
1485
1486     // Center the target rect in the scroll view.
1487     // If the target doesn't fit in the scroll view, center on the gesture location instead.
1488     WebCore::FloatPoint newUnobscuredContentOffset;
1489     if (targetRect.width() <= unobscuredContentRect.width())
1490         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
1491     else
1492         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1493     if (targetRect.height() <= unobscuredContentRect.height())
1494         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
1495     else
1496         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1497     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1498
1499     if (unobscuredContentOffset == newUnobscuredContentOffset) {
1500         if (targetRect.width() > unobscuredContentRect.width())
1501             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1502         if (targetRect.height() > unobscuredContentRect.height())
1503             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1504         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1505     }
1506
1507     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
1508     scrollViewOffsetDelta.scale(contentZoomScale(self));
1509
1510     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
1511     if (scrollDistance < minimumScrollDistance)
1512         return false;
1513
1514     [_contentView willStartZoomOrScroll];
1515
1516     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
1517     return true;
1518 }
1519
1520 - (void)_scrollByContentOffset:(WebCore::FloatPoint)contentOffsetDelta
1521 {
1522     WebCore::FloatPoint scaledOffsetDelta = contentOffsetDelta;
1523     CGFloat zoomScale = contentZoomScale(self);
1524     scaledOffsetDelta.scale(zoomScale, zoomScale);
1525
1526     CGPoint currentOffset = [_scrollView _isAnimatingScroll] ? [_scrollView _animatedTargetOffset] : [_scrollView contentOffset];
1527     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), currentOffset + scaledOffsetDelta);
1528
1529     if (CGPointEqualToPoint(boundedOffset, currentOffset))
1530         return;
1531     [_contentView willStartZoomOrScroll];
1532     [_scrollView setContentOffset:boundedOffset animated:YES];
1533 }
1534
1535 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1536 {
1537     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
1538 }
1539
1540 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1541 {
1542     ASSERT(_initialScaleFactor > 0);
1543     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
1544 }
1545
1546 // focusedElementRect and selectionRect are both in document coordinates.
1547 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
1548 {
1549     const double WKWebViewStandardFontSize = 16;
1550     const double kMinimumHeightToShowContentAboveKeyboard = 106;
1551     const CFTimeInterval UIWebFormAnimationDuration = 0.25;
1552     const double CaretOffsetFromWindowEdge = 20;
1553
1554     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
1555     double scale = allowScaling ? std::min(std::max(WKWebViewStandardFontSize / fontSize, minimumScale), maximumScale) : contentZoomScale(self);
1556     CGFloat documentWidth = [_contentView bounds].size.width;
1557     scale = CGRound(documentWidth * scale) / documentWidth;
1558
1559     UIWindow *window = [_scrollView window];
1560
1561     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
1562     focusedElementRectInNewScale.scale(scale);
1563     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
1564
1565     // Find the portion of the view that is visible on the screen.
1566     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
1567     UIView *fullScreenView = topViewController.view;
1568     if (!fullScreenView)
1569         fullScreenView = window;
1570
1571     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
1572     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
1573     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
1574     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
1575     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
1576
1577     CGFloat visibleOffsetFromTop = 0;
1578     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
1579         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1580         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
1581
1582         if (heightVisibleAboveFormAssistant >= kMinimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
1583             visibleSize.height = heightVisibleAboveFormAssistant;
1584         else {
1585             visibleSize.height = heightVisibleBelowFormAssistant;
1586             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1587         }
1588     }
1589
1590     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
1591     if (!forceScroll) {
1592         CGRect currentlyVisibleRegionInWebViewCoordinates;
1593         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
1594         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
1595         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
1596
1597         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
1598         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
1599             return;
1600
1601         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
1602         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
1603             return;
1604     }
1605
1606     // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
1607     // can get based on the visible area after zooming (workingFrame).  The spacing in either dimension is half the
1608     // difference between the size of the DOM node and the size of the visible frame.
1609     CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
1610     CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
1611
1612     CGPoint topLeft;
1613     topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
1614     topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
1615
1616     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
1617     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
1618     if (selectionRectIsNotNull) {
1619         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
1620         selectionRectInNewScale.scale(scale);
1621         selectionRectInNewScale.moveBy([_contentView frame].origin);
1622         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.width;
1623         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
1624     }
1625
1626     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
1627     documentBoundsInNewScale.scale(scale);
1628     documentBoundsInNewScale.moveBy([_contentView frame].origin);
1629
1630     // Constrain the left edge in document coordinates so that:
1631     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
1632     //  - it isn't so great that the document's right edge is less than the right edge of the screen
1633     if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
1634         topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
1635     else {
1636         CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
1637         if (topLeft.x > maximumAllowableHorizontalOffset)
1638             topLeft.x = maximumAllowableHorizontalOffset;
1639     }
1640
1641     // Constrain the top edge in document coordinates so that:
1642     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
1643     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
1644     if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
1645         topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
1646     else {
1647         CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
1648         if (topLeft.y > maximumAllowableVerticalOffset)
1649             topLeft.y = maximumAllowableVerticalOffset;
1650     }
1651
1652     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
1653
1654     if (scale != contentZoomScale(self))
1655         _page->willStartUserTriggeredZooming();
1656
1657     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
1658     newCenter.scale(1 / scale, 1 / scale);
1659     [_scrollView _zoomToCenter:newCenter
1660                         scale:scale
1661                      duration:UIWebFormAnimationDuration
1662                         force:YES];
1663 }
1664
1665 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
1666 {
1667     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
1668     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
1669     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
1670
1671     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
1672     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
1673
1674     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
1675 }
1676
1677 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
1678 {
1679     const float maximumScaleFactorDeltaForPanScroll = 0.02;
1680
1681     double currentScale = contentZoomScale(self);
1682     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
1683
1684     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
1685         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
1686             return true;
1687     } else if (targetScale != currentScale) {
1688         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
1689         return true;
1690     }
1691     
1692     return false;
1693 }
1694
1695 - (void)didMoveToWindow
1696 {
1697     _page->viewStateDidChange(WebCore::ViewState::AllFlags);
1698 }
1699
1700 - (void)setOpaque:(BOOL)opaque
1701 {
1702     BOOL oldOpaque = self.opaque;
1703
1704     [super setOpaque:opaque];
1705     [_contentView setOpaque:opaque];
1706
1707     if (oldOpaque == opaque)
1708         return;
1709
1710     _page->setDrawsBackground(opaque);
1711     [self _updateScrollViewBackground];
1712 }
1713
1714 - (void)setBackgroundColor:(UIColor *)backgroundColor
1715 {
1716     [super setBackgroundColor:backgroundColor];
1717     [_contentView setBackgroundColor:backgroundColor];
1718 }
1719
1720 - (BOOL)_allowsDoubleTapGestures
1721 {
1722     if (_fastClickingIsDisabled)
1723         return YES;
1724
1725     // If the page is not user scalable, we don't allow double tap gestures.
1726     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
1727         return NO;
1728
1729     // If the viewport width was not explicit, we allow double tap gestures.
1730     if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
1731         return YES;
1732
1733     // For scalable viewports, only disable double tap gestures if the viewport width is device width.
1734     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
1735         return YES;
1736
1737     return !areEssentiallyEqualAsFloat(contentZoomScale(self), _initialScaleFactor);
1738 }
1739
1740 #pragma mark - UIScrollViewDelegate
1741
1742 - (BOOL)usesStandardContentView
1743 {
1744     return !_customContentView;
1745 }
1746
1747 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
1748 {
1749     return roundScrollViewContentSize(*_page, proposedSize);
1750 }
1751
1752 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
1753 {
1754     ASSERT(_scrollView == scrollView);
1755
1756     if (_customContentView)
1757         return _customContentView.get();
1758
1759     return _contentView.get();
1760 }
1761
1762 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
1763 {
1764     if (![self usesStandardContentView])
1765         return;
1766
1767     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
1768         _page->willStartUserTriggeredZooming();
1769         [_contentView scrollViewWillStartPanOrPinchGesture];
1770     }
1771     [_contentView willStartZoomOrScroll];
1772 }
1773
1774 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
1775 {
1776     if (![self usesStandardContentView])
1777         return;
1778
1779     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
1780         [_contentView scrollViewWillStartPanOrPinchGesture];
1781
1782     [_contentView willStartZoomOrScroll];
1783 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1784     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
1785     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
1786     ASSERT(scrollView == _scrollView.get());
1787     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : [_scrollView preferredScrollDecelerationFactor];
1788     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
1789     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
1790 #endif
1791 }
1792
1793 - (void)_didFinishScrolling
1794 {
1795     if (![self usesStandardContentView])
1796         return;
1797
1798     [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
1799     [_contentView didFinishScrolling];
1800 }
1801
1802 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
1803 {
1804     // Work around <rdar://problem/16374753> by avoiding deceleration while
1805     // zooming. We'll animate to the right place once the zoom finishes.
1806     if ([scrollView isZooming])
1807         *targetContentOffset = [scrollView contentOffset];
1808 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1809     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
1810         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
1811         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
1812         
1813         CGRect fullViewRect = self.bounds;
1814
1815         UIEdgeInsets contentInset;
1816
1817         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
1818         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
1819             contentInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
1820         else
1821             contentInset = [self _computedContentInset];
1822
1823         CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, contentInset);
1824         
1825         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
1826     }
1827 #endif
1828 }
1829
1830 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
1831 {
1832     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
1833     if (!decelerate)
1834         [self _didFinishScrolling];
1835 }
1836
1837 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
1838 {
1839     [self _didFinishScrolling];
1840 }
1841
1842 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
1843 {
1844     [self _didFinishScrolling];
1845 }
1846
1847 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
1848 {
1849     if (![self usesStandardContentView])
1850         [_customContentView scrollViewDidScroll:(UIScrollView *)scrollView];
1851
1852     [self _updateVisibleContentRectAfterScrollInView:scrollView];
1853     
1854     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1855         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
1856 }
1857
1858 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
1859 {
1860     [self _updateScrollViewBackground];
1861     [self _updateVisibleContentRectAfterScrollInView:scrollView];
1862 }
1863
1864 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
1865 {
1866     ASSERT(scrollView == _scrollView);
1867     [self _updateVisibleContentRectAfterScrollInView:scrollView];
1868     [_contentView didZoomToScale:scale];
1869 }
1870
1871 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
1872 {
1873     [self _didFinishScrolling];
1874 }
1875
1876 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
1877 {
1878     if (![self usesStandardContentView])
1879         return;
1880
1881     [_contentView didInterruptScrolling];
1882     [self _updateVisibleContentRectAfterScrollInView:scrollView];
1883 }
1884
1885 - (CGRect)_visibleRectInEnclosingScrollView:(UIScrollView *)enclosingScrollView
1886 {
1887     if (!enclosingScrollView)
1888         return self.bounds;
1889
1890     CGRect exposedRect = [enclosingScrollView convertRect:enclosingScrollView.bounds toView:self];
1891     return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
1892 }
1893
1894 - (CGRect)_visibleContentRect
1895 {
1896     CGRect visibleRectInContentCoordinates = _frozenVisibleContentRect ? _frozenVisibleContentRect.value() : [self convertRect:self.bounds toView:_contentView.get()];
1897     
1898     if (UIScrollView *enclosingScroller = [self _scroller]) {
1899         CGRect viewVisibleRect = [self _visibleRectInEnclosingScrollView:enclosingScroller];
1900         CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
1901         visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
1902     }
1903
1904     return visibleRectInContentCoordinates;
1905 }
1906
1907 // Called when some ancestor UIScrollView scrolls.
1908 - (void)_didScroll
1909 {
1910     [self _updateVisibleContentRectAfterScrollInView:[self _scroller]];
1911
1912     const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
1913     if (!_enclosingScrollViewScrollTimer) {
1914         _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
1915             interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
1916         [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
1917     }
1918     _didScrollSinceLastTimerFire = YES;
1919 }
1920
1921 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
1922 {
1923     if (_didScrollSinceLastTimerFire) {
1924         _didScrollSinceLastTimerFire = NO;
1925         return;
1926     }
1927
1928     [self _updateVisibleContentRects];
1929     [_enclosingScrollViewScrollTimer invalidate];
1930     _enclosingScrollViewScrollTimer = nil;
1931 }
1932
1933 - (void)_frameOrBoundsChanged
1934 {
1935     CGRect bounds = self.bounds;
1936     [_scrollView setFrame:bounds];
1937
1938     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing) {
1939         if (!_overridesMinimumLayoutSize)
1940             _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(bounds.size));
1941         if (!_overridesMaximumUnobscuredSize)
1942             _page->setMaximumUnobscuredSize(WebCore::FloatSize(bounds.size));
1943         if (auto drawingArea = _page->drawingArea())
1944             drawingArea->setSize(WebCore::IntSize(bounds.size), WebCore::IntSize(), WebCore::IntSize());
1945     }
1946
1947     [_customContentView web_setMinimumSize:bounds.size];
1948     [self _updateVisibleContentRects];
1949 }
1950
1951 // Unobscured content rect where the user can interact. When the keyboard is up, this should be the area above or below the keyboard, wherever there is enough space.
1952 - (CGRect)_contentRectForUserInteraction
1953 {
1954     // FIXME: handle split keyboard.
1955     UIEdgeInsets obscuredInsets = _obscuredInsets;
1956     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
1957     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
1958     return [self convertRect:unobscuredRect toView:self._currentContentView];
1959 }
1960
1961 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
1962 - (BOOL)_scrollViewIsRubberBanding
1963 {
1964     float deviceScaleFactor = _page->deviceScaleFactor();
1965
1966     CGPoint contentOffset = [_scrollView contentOffset];
1967     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
1968     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
1969 }
1970
1971 - (void)_updateVisibleContentRects
1972 {
1973     // For visible rect updates not associated with a spefic UIScrollView, just consider our own scroller.
1974     [self _updateVisibleContentRectAfterScrollInView:_scrollView.get()];
1975 }
1976
1977 - (void)_updateVisibleContentRectAfterScrollInView:(UIScrollView *)scrollView
1978 {
1979     BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
1980
1981     if (isStableState && scrollView == _scrollView.get())
1982         isStableState = !_isChangingObscuredInsetsInteractively;
1983     
1984     if (isStableState && scrollView == _scrollView.get())
1985         isStableState = ![self _scrollViewIsRubberBanding];
1986
1987     // FIXME: this can be made static after we stop supporting iOS 8.x.
1988     if (isStableState && [scrollView respondsToSelector:@selector(_isInterruptingDeceleration)])
1989         isStableState = ![scrollView performSelector:@selector(_isInterruptingDeceleration)];
1990
1991     [self _updateContentRectsWithState:isStableState];
1992 }
1993
1994 static bool scrollViewCanScroll(UIScrollView *scrollView)
1995 {
1996     if (!scrollView)
1997         return NO;
1998
1999     UIEdgeInsets contentInset = scrollView.contentInset;
2000     CGSize contentSize = scrollView.contentSize;
2001     CGSize boundsSize = scrollView.bounds.size;
2002
2003     return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2004         || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2005 }
2006
2007 - (void)_updateContentRectsWithState:(BOOL)inStableState
2008 {
2009     if (![self usesStandardContentView]) {
2010         [_customContentView web_computedContentInsetDidChange];
2011         return;
2012     }
2013
2014     if (_delayUpdateVisibleContentRects) {
2015         _hadDelayedUpdateVisibleContentRects = YES;
2016         return;
2017     }
2018
2019     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing
2020         || _needsResetViewStateAfterCommitLoadForMainFrame
2021         || [_scrollView isZoomBouncing]
2022         || _currentlyAdjustingScrollViewInsetsForKeyboard)
2023         return;
2024
2025     CGRect fullViewRect = self.bounds;
2026     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2027
2028     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedContentInset];
2029     if (!_haveSetObscuredInsets)
2030         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2031
2032     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2033     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2034
2035     CGFloat scaleFactor = contentZoomScale(self);
2036
2037 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2038     if (inStableState) {
2039         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2040         if (coordinator && coordinator->hasActiveSnapPoint()) {
2041             CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
2042             
2043             CGPoint currentPoint = [_scrollView contentOffset];
2044             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2045
2046             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2047                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2048                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2049                     [strongScrollView setContentOffset:activePoint animated:NO];
2050                 });
2051             }
2052         }
2053     }
2054 #endif
2055     
2056     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2057         unobscuredRect:unobscuredRectInContentCoordinates
2058         unobscuredRectInScrollViewCoordinates:unobscuredRect
2059         obscuredInset:CGSizeMake(_obscuredInsets.left, _obscuredInsets.top)
2060         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2061         inStableState:inStableState
2062         isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2063         enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2064 }
2065
2066 - (void)_didFinishLoadForMainFrame
2067 {
2068     if (_gestureController)
2069         _gestureController->didFinishLoadForMainFrame();
2070 }
2071
2072 - (void)_didFailLoadForMainFrame
2073 {
2074     if (_gestureController)
2075         _gestureController->didFailLoadForMainFrame();
2076 }
2077
2078 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
2079 {
2080     [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
2081
2082     if (_gestureController)
2083         _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
2084 }
2085
2086 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
2087 {
2088     NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
2089     if (!endFrameValue)
2090         return;
2091
2092     // The keyboard rect is always in screen coordinates. In the view services case the window does not
2093     // have the interface orientation rotation transformation; its host does. So, it makes no sense to
2094     // clip the keyboard rect against its screen.
2095     if ([[self window] _isHostedInAnotherProcess])
2096         _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
2097     else
2098         _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
2099
2100     if (adjustScrollView) {
2101         CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
2102         TemporaryChange<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
2103         [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
2104         CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
2105         if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
2106             _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
2107     }
2108
2109     [self _updateVisibleContentRects];
2110 }
2111
2112 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
2113 {
2114     if ([_contentView isAssistingNode])
2115         return YES;
2116
2117     NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
2118     return isLocalKeyboard && !isLocalKeyboard.boolValue;
2119 }
2120
2121 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
2122 {
2123     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2124         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2125 }
2126
2127 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
2128 {
2129     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
2130 }
2131
2132 - (void)_keyboardWillShow:(NSNotification *)notification
2133 {
2134     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2135         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2136 }
2137
2138 - (void)_keyboardWillHide:(NSNotification *)notification
2139 {
2140     // Ignore keyboard will hide notifications sent during rotation. They're just there for
2141     // backwards compatibility reasons and processing the will hide notification would
2142     // temporarily screw up the the unobscured view area.
2143     if ([[UIPeripheralHost sharedInstance] rotationState])
2144         return;
2145
2146     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2147 }
2148
2149 - (void)_windowDidRotate:(NSNotification *)notification
2150 {
2151     if (!_overridesInterfaceOrientation)
2152         _page->setDeviceOrientation(deviceOrientation());
2153 }
2154
2155 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
2156 {
2157     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
2158 }
2159
2160 - (NSString *)_contentSizeCategory
2161 {
2162     return [[UIApplication sharedApplication] preferredContentSizeCategory];
2163 }
2164
2165 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
2166 {
2167     if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
2168         return;
2169
2170     _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
2171
2172     if (allowsBackForwardNavigationGestures) {
2173         if (!_gestureController) {
2174             _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
2175             _gestureController->installSwipeHandler(self, [self scrollView]);
2176             _gestureController->setAlternateBackForwardListSourceView([_configuration _alternateWebViewForNavigationGestures]);
2177         }
2178     } else
2179         _gestureController = nullptr;
2180
2181     _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
2182 }
2183
2184 - (BOOL)allowsBackForwardNavigationGestures
2185 {
2186     return _allowsBackForwardNavigationGestures;
2187 }
2188
2189 - (void)_navigationGestureDidBegin
2190 {
2191     // During a back/forward swipe, there's a view interposed between this view and the content view that has
2192     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
2193     // frozen rects during swipes.
2194     CGRect fullViewRect = self.bounds;
2195     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedContentInset]);
2196
2197     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
2198     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
2199 }
2200
2201 - (void)_navigationGestureDidEnd
2202 {
2203     _frozenVisibleContentRect = Nullopt;
2204     _frozenUnobscuredContentRect = Nullopt;
2205 }
2206
2207 - (void)_updateForceAlwaysUserScalable
2208 {
2209     _page->updateForceAlwaysUserScalable();
2210 }
2211
2212 #endif // PLATFORM(IOS)
2213
2214 #pragma mark OS X-specific methods
2215
2216 #if PLATFORM(MAC)
2217
2218 - (BOOL)acceptsFirstResponder
2219 {
2220     return _impl->acceptsFirstResponder();
2221 }
2222
2223 - (BOOL)becomeFirstResponder
2224 {
2225     return _impl->becomeFirstResponder();
2226 }
2227
2228 - (BOOL)resignFirstResponder
2229 {
2230     return _impl->resignFirstResponder();
2231 }
2232
2233 - (void)viewWillStartLiveResize
2234 {
2235     _impl->viewWillStartLiveResize();
2236 }
2237
2238 - (void)viewDidEndLiveResize
2239 {
2240     _impl->viewDidEndLiveResize();
2241 }
2242
2243 - (BOOL)isFlipped
2244 {
2245     return YES;
2246 }
2247
2248 - (NSSize)intrinsicContentSize
2249 {
2250     return NSSizeFromCGSize(_impl->intrinsicContentSize());
2251 }
2252
2253 - (void)prepareContentInRect:(NSRect)rect
2254 {
2255     _impl->prepareContentInRect(NSRectToCGRect(rect));
2256 }
2257
2258 - (void)setFrameSize:(NSSize)size
2259 {
2260     [super setFrameSize:size];
2261     _impl->setFrameSize(NSSizeToCGSize(size));
2262 }
2263
2264 - (void)renewGState
2265 {
2266     _impl->renewGState();
2267     [super renewGState];
2268 }
2269
2270 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
2271
2272 WEBCORE_COMMAND(alignCenter)
2273 WEBCORE_COMMAND(alignJustified)
2274 WEBCORE_COMMAND(alignLeft)
2275 WEBCORE_COMMAND(alignRight)
2276 WEBCORE_COMMAND(copy)
2277 WEBCORE_COMMAND(cut)
2278 WEBCORE_COMMAND(delete)
2279 WEBCORE_COMMAND(deleteBackward)
2280 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
2281 WEBCORE_COMMAND(deleteForward)
2282 WEBCORE_COMMAND(deleteToBeginningOfLine)
2283 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
2284 WEBCORE_COMMAND(deleteToEndOfLine)
2285 WEBCORE_COMMAND(deleteToEndOfParagraph)
2286 WEBCORE_COMMAND(deleteToMark)
2287 WEBCORE_COMMAND(deleteWordBackward)
2288 WEBCORE_COMMAND(deleteWordForward)
2289 WEBCORE_COMMAND(ignoreSpelling)
2290 WEBCORE_COMMAND(indent)
2291 WEBCORE_COMMAND(insertBacktab)
2292 WEBCORE_COMMAND(insertLineBreak)
2293 WEBCORE_COMMAND(insertNewline)
2294 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
2295 WEBCORE_COMMAND(insertParagraphSeparator)
2296 WEBCORE_COMMAND(insertTab)
2297 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
2298 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
2299 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
2300 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
2301 WEBCORE_COMMAND(moveBackward)
2302 WEBCORE_COMMAND(moveBackwardAndModifySelection)
2303 WEBCORE_COMMAND(moveDown)
2304 WEBCORE_COMMAND(moveDownAndModifySelection)
2305 WEBCORE_COMMAND(moveForward)
2306 WEBCORE_COMMAND(moveForwardAndModifySelection)
2307 WEBCORE_COMMAND(moveLeft)
2308 WEBCORE_COMMAND(moveLeftAndModifySelection)
2309 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
2310 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
2311 WEBCORE_COMMAND(moveRight)
2312 WEBCORE_COMMAND(moveRightAndModifySelection)
2313 WEBCORE_COMMAND(moveToBeginningOfDocument)
2314 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
2315 WEBCORE_COMMAND(moveToBeginningOfLine)
2316 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
2317 WEBCORE_COMMAND(moveToBeginningOfParagraph)
2318 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
2319 WEBCORE_COMMAND(moveToBeginningOfSentence)
2320 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
2321 WEBCORE_COMMAND(moveToEndOfDocument)
2322 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
2323 WEBCORE_COMMAND(moveToEndOfLine)
2324 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
2325 WEBCORE_COMMAND(moveToEndOfParagraph)
2326 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
2327 WEBCORE_COMMAND(moveToEndOfSentence)
2328 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
2329 WEBCORE_COMMAND(moveToLeftEndOfLine)
2330 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
2331 WEBCORE_COMMAND(moveToRightEndOfLine)
2332 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
2333 WEBCORE_COMMAND(moveUp)
2334 WEBCORE_COMMAND(moveUpAndModifySelection)
2335 WEBCORE_COMMAND(moveWordBackward)
2336 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
2337 WEBCORE_COMMAND(moveWordForward)
2338 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
2339 WEBCORE_COMMAND(moveWordLeft)
2340 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
2341 WEBCORE_COMMAND(moveWordRight)
2342 WEBCORE_COMMAND(moveWordRightAndModifySelection)
2343 WEBCORE_COMMAND(outdent)
2344 WEBCORE_COMMAND(pageDown)
2345 WEBCORE_COMMAND(pageDownAndModifySelection)
2346 WEBCORE_COMMAND(pageUp)
2347 WEBCORE_COMMAND(pageUpAndModifySelection)
2348 WEBCORE_COMMAND(paste)
2349 WEBCORE_COMMAND(pasteAsPlainText)
2350 WEBCORE_COMMAND(scrollPageDown)
2351 WEBCORE_COMMAND(scrollPageUp)
2352 WEBCORE_COMMAND(scrollLineDown)
2353 WEBCORE_COMMAND(scrollLineUp)
2354 WEBCORE_COMMAND(scrollToBeginningOfDocument)
2355 WEBCORE_COMMAND(scrollToEndOfDocument)
2356 WEBCORE_COMMAND(selectAll)
2357 WEBCORE_COMMAND(selectLine)
2358 WEBCORE_COMMAND(selectParagraph)
2359 WEBCORE_COMMAND(selectSentence)
2360 WEBCORE_COMMAND(selectToMark)
2361 WEBCORE_COMMAND(selectWord)
2362 WEBCORE_COMMAND(setMark)
2363 WEBCORE_COMMAND(subscript)
2364 WEBCORE_COMMAND(superscript)
2365 WEBCORE_COMMAND(swapWithMark)
2366 WEBCORE_COMMAND(takeFindStringFromSelection)
2367 WEBCORE_COMMAND(transpose)
2368 WEBCORE_COMMAND(underline)
2369 WEBCORE_COMMAND(unscript)
2370 WEBCORE_COMMAND(yank)
2371 WEBCORE_COMMAND(yankAndSelect)
2372
2373 #undef WEBCORE_COMMAND
2374
2375 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
2376 {
2377     return _impl->writeSelectionToPasteboard(pasteboard, types);
2378 }
2379
2380 - (void)centerSelectionInVisibleArea:(id)sender
2381 {
2382     _impl->centerSelectionInVisibleArea();
2383 }
2384
2385 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
2386 {
2387     return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
2388 }
2389
2390 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
2391 {
2392     return _impl->readSelectionFromPasteboard(pasteboard);
2393 }
2394
2395 - (void)changeFont:(id)sender
2396 {
2397     _impl->changeFontFromFontPanel();
2398 }
2399
2400 - (IBAction)startSpeaking:(id)sender
2401 {
2402     _impl->startSpeaking();
2403 }
2404
2405 - (IBAction)stopSpeaking:(id)sender
2406 {
2407     _impl->stopSpeaking(sender);
2408 }
2409
2410 - (IBAction)showGuessPanel:(id)sender
2411 {
2412     _impl->showGuessPanel(sender);
2413 }
2414
2415 - (IBAction)checkSpelling:(id)sender
2416 {
2417     _impl->checkSpelling();
2418 }
2419
2420 - (void)changeSpelling:(id)sender
2421 {
2422     _impl->changeSpelling(sender);
2423 }
2424
2425 - (IBAction)toggleContinuousSpellChecking:(id)sender
2426 {
2427     _impl->toggleContinuousSpellChecking();
2428 }
2429
2430 - (BOOL)isGrammarCheckingEnabled
2431 {
2432     return _impl->isGrammarCheckingEnabled();
2433 }
2434
2435 - (void)setGrammarCheckingEnabled:(BOOL)flag
2436 {
2437     _impl->setGrammarCheckingEnabled(flag);
2438 }
2439
2440 - (IBAction)toggleGrammarChecking:(id)sender
2441 {
2442     _impl->toggleGrammarChecking();
2443 }
2444
2445 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
2446 {
2447     _impl->toggleAutomaticSpellingCorrection();
2448 }
2449
2450 - (void)orderFrontSubstitutionsPanel:(id)sender
2451 {
2452     _impl->orderFrontSubstitutionsPanel(sender);
2453 }
2454
2455 - (IBAction)toggleSmartInsertDelete:(id)sender
2456 {
2457     _impl->toggleSmartInsertDelete();
2458 }
2459
2460 - (BOOL)isAutomaticQuoteSubstitutionEnabled
2461 {
2462     return _impl->isAutomaticQuoteSubstitutionEnabled();
2463 }
2464
2465 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
2466 {
2467     _impl->setAutomaticQuoteSubstitutionEnabled(flag);
2468 }
2469
2470 - (void)toggleAutomaticQuoteSubstitution:(id)sender
2471 {
2472     _impl->toggleAutomaticQuoteSubstitution();
2473 }
2474
2475 - (BOOL)isAutomaticDashSubstitutionEnabled
2476 {
2477     return _impl->isAutomaticDashSubstitutionEnabled();
2478 }
2479
2480 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
2481 {
2482     _impl->setAutomaticDashSubstitutionEnabled(flag);
2483 }
2484
2485 - (void)toggleAutomaticDashSubstitution:(id)sender
2486 {
2487     _impl->toggleAutomaticDashSubstitution();
2488 }
2489
2490 - (BOOL)isAutomaticLinkDetectionEnabled
2491 {
2492     return _impl->isAutomaticLinkDetectionEnabled();
2493 }
2494
2495 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
2496 {
2497     _impl->setAutomaticLinkDetectionEnabled(flag);
2498 }
2499
2500 - (void)toggleAutomaticLinkDetection:(id)sender
2501 {
2502     _impl->toggleAutomaticLinkDetection();
2503 }
2504
2505 - (BOOL)isAutomaticTextReplacementEnabled
2506 {
2507     return _impl->isAutomaticTextReplacementEnabled();
2508 }
2509
2510 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
2511 {
2512     _impl->setAutomaticTextReplacementEnabled(flag);
2513 }
2514
2515 - (void)toggleAutomaticTextReplacement:(id)sender
2516 {
2517     _impl->toggleAutomaticTextReplacement();
2518 }
2519
2520 - (void)uppercaseWord:(id)sender
2521 {
2522     _impl->uppercaseWord();
2523 }
2524
2525 - (void)lowercaseWord:(id)sender
2526 {
2527     _impl->lowercaseWord();
2528 }
2529
2530 - (void)capitalizeWord:(id)sender
2531 {
2532     _impl->capitalizeWord();
2533 }
2534
2535 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
2536 {
2537     return _impl->wantsKeyDownForEvent(event);
2538 }
2539
2540 - (void)scrollWheel:(NSEvent *)event
2541 {
2542     _impl->scrollWheel(event);
2543 }
2544
2545 - (void)swipeWithEvent:(NSEvent *)event
2546 {
2547     _impl->swipeWithEvent(event);
2548 }
2549
2550 - (void)mouseMoved:(NSEvent *)event
2551 {
2552     _impl->mouseMoved(event);
2553 }
2554
2555 - (void)mouseDown:(NSEvent *)event
2556 {
2557     _impl->mouseDown(event);
2558 }
2559
2560 - (void)mouseUp:(NSEvent *)event
2561 {
2562     _impl->mouseUp(event);
2563 }
2564
2565 - (void)mouseDragged:(NSEvent *)event
2566 {
2567     _impl->mouseDragged(event);
2568 }
2569
2570 - (void)mouseEntered:(NSEvent *)event
2571 {
2572     _impl->mouseEntered(event);
2573 }
2574
2575 - (void)mouseExited:(NSEvent *)event
2576 {
2577     _impl->mouseExited(event);
2578 }
2579
2580 - (void)otherMouseDown:(NSEvent *)event
2581 {
2582     _impl->otherMouseDown(event);
2583 }
2584
2585 - (void)otherMouseDragged:(NSEvent *)event
2586 {
2587     _impl->otherMouseDragged(event);
2588 }
2589
2590 - (void)otherMouseUp:(NSEvent *)event
2591 {
2592     _impl->otherMouseUp(event);
2593 }
2594
2595 - (void)rightMouseDown:(NSEvent *)event
2596 {
2597     _impl->rightMouseDown(event);
2598 }
2599
2600 - (void)rightMouseDragged:(NSEvent *)event
2601 {
2602     _impl->rightMouseDragged(event);
2603 }
2604
2605 - (void)rightMouseUp:(NSEvent *)event
2606 {
2607     _impl->rightMouseUp(event);
2608 }
2609
2610 - (void)pressureChangeWithEvent:(NSEvent *)event
2611 {
2612     _impl->pressureChangeWithEvent(event);
2613 }
2614
2615 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2616 {
2617     return _impl->acceptsFirstMouse(event);
2618 }
2619
2620 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2621 {
2622     return _impl->shouldDelayWindowOrderingForEvent(event);
2623 }
2624
2625 - (void)doCommandBySelector:(SEL)selector
2626 {
2627     _impl->doCommandBySelector(selector);
2628 }
2629
2630 - (void)insertText:(id)string
2631 {
2632     _impl->insertText(string);
2633 }
2634
2635 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
2636 {
2637     _impl->insertText(string, replacementRange);
2638 }
2639
2640 - (NSTextInputContext *)inputContext
2641 {
2642     return _impl->inputContext();
2643 }
2644
2645 - (BOOL)performKeyEquivalent:(NSEvent *)event
2646 {
2647     return _impl->performKeyEquivalent(event);
2648 }
2649
2650 - (void)keyUp:(NSEvent *)theEvent
2651 {
2652     _impl->keyUp(theEvent);
2653 }
2654
2655 - (void)keyDown:(NSEvent *)theEvent
2656 {
2657     _impl->keyDown(theEvent);
2658 }
2659
2660 - (void)flagsChanged:(NSEvent *)theEvent
2661 {
2662     _impl->flagsChanged(theEvent);
2663 }
2664
2665 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
2666 {
2667     _impl->setMarkedText(string, newSelectedRange, replacementRange);
2668 }
2669
2670 - (void)unmarkText
2671 {
2672     _impl->unmarkText();
2673 }
2674
2675 - (NSRange)selectedRange
2676 {
2677     return _impl->selectedRange();
2678 }
2679
2680 - (BOOL)hasMarkedText
2681 {
2682     return _impl->hasMarkedText();
2683 }
2684
2685 - (NSRange)markedRange
2686 {
2687     return _impl->markedRange();
2688 }
2689
2690 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
2691 {
2692     return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
2693 }
2694
2695 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
2696 {
2697     return _impl->characterIndexForPoint(thePoint);
2698 }
2699
2700 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
2701 {
2702     return _impl->firstRectForCharacterRange(theRange, actualRange);
2703 }
2704
2705 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
2706 {
2707     _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
2708 }
2709
2710 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
2711 {
2712     _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
2713 }
2714
2715 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
2716 {
2717     _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
2718 }
2719
2720 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
2721 {
2722     _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
2723 }
2724
2725 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
2726 {
2727     _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
2728 }
2729
2730 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
2731 {
2732     _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
2733 }
2734
2735 - (NSArray *)validAttributesForMarkedText
2736 {
2737     return _impl->validAttributesForMarkedText();
2738 }
2739
2740 #if ENABLE(DRAG_SUPPORT)
2741 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
2742 {
2743     _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
2744 }
2745
2746 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2747 {
2748     return _impl->draggingEntered(draggingInfo);
2749 }
2750
2751 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2752 {
2753     return _impl->draggingUpdated(draggingInfo);
2754 }
2755
2756 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2757 {
2758     _impl->draggingExited(draggingInfo);
2759 }
2760
2761 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2762 {
2763     return _impl->prepareForDragOperation(draggingInfo);
2764 }
2765
2766 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2767 {
2768     return _impl->performDragOperation(draggingInfo);
2769 }
2770
2771 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
2772 {
2773     return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
2774 }
2775 #endif // ENABLE(DRAG_SUPPORT)
2776
2777 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
2778 {
2779     return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
2780 }
2781
2782 - (void)viewWillMoveToWindow:(NSWindow *)window
2783 {
2784     _impl->viewWillMoveToWindow(window);
2785 }
2786
2787 - (void)viewDidMoveToWindow
2788 {
2789     _impl->viewDidMoveToWindow();
2790 }
2791
2792 - (void)drawRect:(NSRect)rect
2793 {
2794     _impl->drawRect(NSRectToCGRect(rect));
2795 }
2796
2797 - (BOOL)isOpaque
2798 {
2799     return _impl->isOpaque();
2800 }
2801
2802 - (BOOL)mouseDownCanMoveWindow
2803 {
2804     return WebKit::WebViewImpl::mouseDownCanMoveWindow();
2805 }
2806
2807 - (void)viewDidHide
2808 {
2809     _impl->viewDidHide();
2810 }
2811
2812 - (void)viewDidUnhide
2813 {
2814     _impl->viewDidUnhide();
2815 }
2816
2817 - (void)viewDidChangeBackingProperties
2818 {
2819     _impl->viewDidChangeBackingProperties();
2820 }
2821
2822 - (void)_activeSpaceDidChange:(NSNotification *)notification
2823 {
2824     _impl->activeSpaceDidChange();
2825 }
2826
2827 - (id)accessibilityFocusedUIElement
2828 {
2829     return _impl->accessibilityFocusedUIElement();
2830 }
2831
2832 - (BOOL)accessibilityIsIgnored
2833 {
2834     return _impl->accessibilityIsIgnored();
2835 }
2836
2837 - (id)accessibilityHitTest:(NSPoint)point
2838 {
2839     return _impl->accessibilityHitTest(NSPointToCGPoint(point));
2840 }
2841
2842 - (id)accessibilityAttributeValue:(NSString *)attribute
2843 {
2844     return _impl->accessibilityAttributeValue(attribute);
2845 }
2846
2847 - (NSView *)hitTest:(NSPoint)point
2848 {
2849     if (!_impl)
2850         return [super hitTest:point];
2851     return _impl->hitTest(NSPointToCGPoint(point));
2852 }
2853
2854 - (NSInteger)conversationIdentifier
2855 {
2856     return (NSInteger)self;
2857 }
2858
2859 - (void)quickLookWithEvent:(NSEvent *)event
2860 {
2861     _impl->quickLookWithEvent(event);
2862 }
2863
2864 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2865 {
2866     return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
2867 }
2868
2869 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2870 {
2871     return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
2872 }
2873
2874 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2875 {
2876     CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
2877     for (int i = 0; i < count; i++)
2878         cgRects[i] = NSRectToCGRect(rects[i]);
2879     _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
2880     free(cgRects);
2881 }
2882
2883 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2884 {
2885     if (!_impl)
2886         return;
2887     _impl->removeTrackingRect(tag);
2888 }
2889
2890 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2891 {
2892     if (!_impl)
2893         return;
2894     _impl->removeTrackingRects(tags, count);
2895 }
2896
2897 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
2898 {
2899     return _impl->stringForToolTip(tag);
2900 }
2901
2902 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
2903 {
2904     _impl->pasteboardChangedOwner(pasteboard);
2905 }
2906
2907 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
2908 {
2909     _impl->provideDataForPasteboard(pasteboard, type);
2910 }
2911
2912 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2913 {
2914     return _impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
2915 }
2916
2917 - (BOOL)wantsUpdateLayer
2918 {
2919     return WebKit::WebViewImpl::wantsUpdateLayer();
2920 }
2921
2922 - (void)updateLayer
2923 {
2924     _impl->updateLayer();
2925 }
2926
2927 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
2928 {
2929     _impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
2930 }
2931
2932 - (BOOL)allowsBackForwardNavigationGestures
2933 {
2934     return _impl->allowsBackForwardNavigationGestures();
2935 }
2936
2937 - (void)smartMagnifyWithEvent:(NSEvent *)event
2938 {
2939     _impl->smartMagnifyWithEvent(event);
2940 }
2941
2942 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
2943 {
2944     _impl->setMagnification(magnification, NSPointToCGPoint(point));
2945 }
2946
2947 - (void)setMagnification:(double)magnification
2948 {
2949     _impl->setMagnification(magnification);
2950 }
2951
2952 - (double)magnification
2953 {
2954     return _impl->magnification();
2955 }
2956
2957 - (void)setAllowsMagnification:(BOOL)allowsMagnification
2958 {
2959     _impl->setAllowsMagnification(allowsMagnification);
2960 }
2961
2962 - (BOOL)allowsMagnification
2963 {
2964     return _impl->allowsMagnification();
2965 }
2966
2967 - (void)magnifyWithEvent:(NSEvent *)event
2968 {
2969     _impl->magnifyWithEvent(event);
2970 }
2971
2972 #if ENABLE(MAC_GESTURE_EVENTS)
2973 - (void)rotateWithEvent:(NSEvent *)event
2974 {
2975     _impl->rotateWithEvent(event);
2976 }
2977 #endif
2978
2979 - (WKTextFinderClient *)_ensureTextFinderClient
2980 {
2981     if (!_textFinderClient)
2982         _textFinderClient = adoptNS([[WKTextFinderClient alloc] initWithPage:*_page view:self]);
2983     return _textFinderClient.get();
2984 }
2985
2986 - (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
2987 {
2988     [[self _ensureTextFinderClient] findMatchesForString:targetString relativeToMatch:relativeMatch findOptions:findOptions maxResults:maxResults resultCollector:resultCollector];
2989 }
2990
2991 - (NSView *)documentContainerView
2992 {
2993     return self;
2994 }
2995
2996 - (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler
2997 {
2998     [[self _ensureTextFinderClient] getSelectedText:completionHandler];
2999 }
3000
3001 - (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler
3002 {
3003     [[self _ensureTextFinderClient] selectFindMatch:findMatch completionHandler:completionHandler];
3004 }
3005
3006 - (NSTextInputContext *)_web_superInputContext
3007 {
3008     return [super inputContext];
3009 }
3010
3011 - (void)_web_superQuickLookWithEvent:(NSEvent *)event
3012 {
3013     [super quickLookWithEvent:event];
3014 }
3015
3016 - (void)_web_superSwipeWithEvent:(NSEvent *)event
3017 {
3018     [super swipeWithEvent:event];
3019 }
3020
3021 - (void)_web_superMagnifyWithEvent:(NSEvent *)event
3022 {
3023     [super magnifyWithEvent:event];
3024 }
3025
3026 - (void)_web_superSmartMagnifyWithEvent:(NSEvent *)event
3027 {
3028     [super smartMagnifyWithEvent:event];
3029 }
3030
3031 - (void)_web_superRemoveTrackingRect:(NSTrackingRectTag)tag
3032 {
3033     [super removeTrackingRect:tag];
3034 }
3035
3036 - (id)_web_superAccessibilityAttributeValue:(NSString *)attribute
3037 {
3038 #pragma clang diagnostic push
3039 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3040     return [super accessibilityAttributeValue:attribute];
3041 #pragma clang diagnostic pop
3042 }
3043
3044 - (void)_web_superDoCommandBySelector:(SEL)selector
3045 {
3046     [super doCommandBySelector:selector];
3047 }
3048
3049 - (BOOL)_web_superPerformKeyEquivalent:(NSEvent *)event
3050 {
3051     return [super performKeyEquivalent:event];
3052 }
3053
3054 - (void)_web_superKeyDown:(NSEvent *)event
3055 {
3056     [super keyDown:event];
3057 }
3058
3059 - (NSView *)_web_superHitTest:(NSPoint)point
3060 {
3061     return [super hitTest:point];
3062 }
3063
3064 - (id)_web_immediateActionAnimationControllerForHitTestResultInternal:(API::HitTestResult*)hitTestResult withType:(uint32_t)type userData:(API::Object*)userData
3065 {
3066     id<NSSecureCoding> data = userData ? static_cast<id<NSSecureCoding>>(userData->wrapper()) : nil;
3067     return [self _immediateActionAnimationControllerForHitTestResult:wrapper(*hitTestResult) withType:(_WKImmediateActionType)type userData:data];
3068 }
3069
3070 // We don't expose these various bits of SPI like WKView does,
3071 // so have these internal methods just do the work (or do nothing):
3072 - (void)_web_prepareForImmediateActionAnimation
3073 {
3074 }
3075
3076 - (void)_web_cancelImmediateActionAnimation
3077 {
3078 }
3079
3080 - (void)_web_completeImmediateActionAnimation
3081 {
3082 }
3083
3084 - (void)_web_didChangeContentSize:(NSSize)newSize
3085 {
3086 }
3087
3088 - (void)_web_dismissContentRelativeChildWindows
3089 {
3090     _impl->dismissContentRelativeChildWindowsFromViewOnly();
3091 }
3092
3093 - (void)_web_dismissContentRelativeChildWindowsWithAnimation:(BOOL)withAnimation
3094 {
3095     _impl->dismissContentRelativeChildWindowsWithAnimationFromViewOnly(withAnimation);
3096 }
3097
3098 - (void)_web_gestureEventWasNotHandledByWebCore:(NSEvent *)event
3099 {
3100     _impl->gestureEventWasNotHandledByWebCoreFromViewOnly(event);
3101 }
3102
3103 #endif // PLATFORM(MAC)
3104
3105 @end
3106
3107 @implementation WKWebView (WKPrivate)
3108
3109 - (BOOL)_isEditable
3110 {
3111     return _page->isEditable();
3112 }
3113
3114 - (void)_setEditable:(BOOL)editable
3115 {
3116     _page->setEditable(editable);
3117 #if PLATFORM(MAC)
3118     _impl->startObservingFontPanel();
3119 #endif
3120 }
3121
3122 - (_WKRemoteObjectRegistry *)_remoteObjectRegistry
3123 {
3124 #if PLATFORM(MAC)
3125     return _impl->remoteObjectRegistry();
3126 #else
3127     if (!_remoteObjectRegistry) {
3128         _remoteObjectRegistry = adoptNS([[_WKRemoteObjectRegistry alloc] _initWithMessageSender:*_page]);
3129         _page->process().processPool().addMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID(), [_remoteObjectRegistry remoteObjectRegistry]);
3130     }
3131
3132     return _remoteObjectRegistry.get();
3133 #endif
3134 }
3135
3136 - (WKBrowsingContextHandle *)_handle
3137 {
3138     return [[[WKBrowsingContextHandle alloc] _initWithPageID:_page->pageID()] autorelease];
3139 }
3140
3141 - (_WKRenderingProgressEvents)_observedRenderingProgressEvents
3142 {
3143     return _observedRenderingProgressEvents;
3144 }
3145
3146 - (id <WKHistoryDelegatePrivate>)_historyDelegate
3147 {
3148     return _navigationState->historyDelegate().autorelease();
3149 }
3150
3151 - (void)_setHistoryDelegate:(id <WKHistoryDelegatePrivate>)historyDelegate
3152 {
3153     _page->setHistoryClient(_navigationState->createHistoryClient());
3154     _navigationState->setHistoryDelegate(historyDelegate);
3155 }
3156
3157 - (NSURL *)_unreachableURL
3158 {
3159     return [NSURL _web_URLWithWTFString:_page->pageLoadState().unreachableURL()];
3160 }
3161
3162 - (void)_loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
3163 {
3164     _page->loadAlternateHTMLString(string, [baseURL _web_originalDataAsWTFString], [unreachableURL _web_originalDataAsWTFString]);
3165 }
3166
3167 - (WKNavigation *)_loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL userData:(id)userData
3168 {
3169     auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString, WebKit::ObjCObjectGraph::create(userData).ptr());
3170     if (!navigation)
3171         return nil;
3172
3173     return [wrapper(*navigation.release().leakRef()) autorelease];
3174 }
3175
3176 - (NSArray *)_certificateChain
3177 {
3178     if (WebKit::WebFrameProxy* mainFrame = _page->mainFrame())
3179         return mainFrame->certificateInfo() ? (NSArray *)mainFrame->certificateInfo()->certificateInfo().certificateChain() : nil;
3180
3181     return nil;
3182 }
3183
3184 - (NSURL *)_committedURL
3185 {
3186     return [NSURL _web_URLWithWTFString:_page->pageLoadState().url()];
3187 }
3188
3189 - (NSString *)_MIMEType
3190 {
3191     if (_page->mainFrame())
3192         return _page->mainFrame()->mimeType();
3193
3194     return nil;
3195 }
3196
3197 - (NSString *)_userAgent
3198 {
3199     return _page->userAgent();
3200 }
3201
3202 - (NSString *)_applicationNameForUserAgent
3203 {
3204     return _page->applicationNameForUserAgent();
3205 }
3206
3207 - (void)_setApplicationNameForUserAgent:(NSString *)applicationNameForUserAgent
3208 {
3209     _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
3210 }
3211
3212 - (NSString *)_customUserAgent
3213 {
3214     return self.customUserAgent;
3215 }
3216
3217 - (void)_setCustomUserAgent:(NSString *)customUserAgent
3218 {
3219     self.customUserAgent = customUserAgent;
3220 }
3221
3222 - (void)_setUserContentExtensionsEnabled:(BOOL)userContentExtensionsEnabled
3223 {
3224     // This is kept for binary compatibility with iOS 9.
3225 }
3226
3227 - (BOOL)_userContentExtensionsEnabled
3228 {
3229     // This is kept for binary compatibility with iOS 9.
3230     return true;
3231 }
3232
3233 - (pid_t)_webProcessIdentifier
3234 {
3235     return _page->isValid() ? _page->processIdentifier() : 0;
3236 }
3237
3238 - (void)_killWebContentProcess
3239 {
3240     if (!_page->isValid())
3241         return;
3242
3243     _page->process().terminate();
3244 }
3245
3246 - (WKNavigation *)_reloadWithoutContentBlockers
3247 {
3248     const bool reloadFromOrigin = false;
3249     const bool contentBlockersEnabled = false;
3250     auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
3251     if (!navigation)
3252         return nil;
3253     
3254     return [wrapper(*navigation.release().leakRef()) autorelease];
3255 }
3256
3257 - (void)_killWebContentProcessAndResetState
3258 {
3259     _page->terminateProcess();
3260 }
3261
3262 #if PLATFORM(IOS)
3263 static WebCore::FloatSize activeMinimumLayoutSize(WKWebView *webView, const CGRect& bounds)
3264 {
3265     return WebCore::FloatSize(webView->_overridesMinimumLayoutSize ? webView->_minimumLayoutSizeOverride : bounds.size);
3266 }
3267
3268 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
3269 {
3270     return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
3271 }
3272
3273 static int32_t activeOrientation(WKWebView *webView)
3274 {
3275     return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
3276 }
3277
3278 - (void (^)(void))_retainActiveFocusedState
3279 {
3280     ++_activeFocusedStateRetainCount;
3281
3282     // FIXME: Use something like CompletionHandlerCallChecker to ensure that the returned block is called before it's released.
3283     return [[[self] {
3284         --_activeFocusedStateRetainCount;
3285     } copy] autorelease];
3286 }
3287
3288 - (void)_becomeFirstResponderWithSelectionMovingForward:(BOOL)selectingForward completionHandler:(void (^)(BOOL didBecomeFirstResponder))completionHandler
3289 {
3290     typeof(completionHandler) completionHandlerCopy = nil;
3291     if (completionHandler)
3292         completionHandlerCopy = Block_copy(completionHandler);
3293
3294     [_contentView _becomeFirstResponderWithSelectionMovingForward:selectingForward completionHandler:[completionHandlerCopy](BOOL didBecomeFirstResponder) {
3295         if (!completionHandlerCopy)
3296             return;
3297
3298         completionHandlerCopy(didBecomeFirstResponder);
3299         Block_release(completionHandlerCopy);
3300     }];
3301 }
3302
3303 - (id)_snapshotLayerContentsForBackForwardListItem:(WKBackForwardListItem *)item
3304 {
3305     if (_page->backForwardList().currentItem() == &item._item)
3306         _page->recordNavigationSnapshot(*_page->backForwardList().currentItem());
3307
3308     if (auto* viewSnapshot = item._item.snapshot())
3309         return viewSnapshot->asLayerContents();
3310
3311     return nil;
3312 }
3313
3314 - (NSArray *)_dataDetectionResults
3315 {
3316     return [_contentView _dataDetectionResults];
3317 }
3318 #endif
3319
3320 - (void)_didRelaunchProcess
3321 {
3322 #if PLATFORM(IOS)
3323     CGRect bounds = self.bounds;
3324     WebCore::FloatSize minimalLayoutSize = activeMinimumLayoutSize(self, bounds);
3325     _page->setViewportConfigurationMinimumLayoutSize(minimalLayoutSize);
3326     _page->setMaximumUnobscuredSize(activeMaximumUnobscuredSize(self, bounds));
3327 #endif
3328 }
3329
3330 - (NSData *)_sessionStateData
3331 {
3332     WebKit::SessionState sessionState = _page->sessionState();
3333
3334     // FIXME: This should not use the legacy session state encoder.
3335     return [wrapper(*WebKit::encodeLegacySessionState(sessionState).release().leakRef()) autorelease];
3336 }
3337
3338 - (_WKSessionState *)_sessionState
3339 {
3340     return adoptNS([[_WKSessionState alloc] _initWithSessionState:_page->sessionState()]).autorelease();
3341 }
3342
3343 - (void)_restoreFromSessionStateData:(NSData *)sessionStateData
3344 {
3345     // FIXME: This should not use the legacy session state decoder.
3346     WebKit::SessionState sessionState;
3347     if (!WebKit::decodeLegacySessionState(static_cast<const uint8_t*>(sessionStateData.bytes), sessionStateData.length, sessionState))
3348         return;
3349
3350     _page->restoreFromSessionState(WTFMove(sessionState), true);
3351 }
3352
3353 - (WKNavigation *)_restoreSessionState:(_WKSessionState *)sessionState andNavigate:(BOOL)navigate
3354 {
3355     auto navigation = _page->restoreFromSessionState(sessionState->_sessionState, navigate);
3356     if (!navigation)
3357         return nil;
3358
3359     return [wrapper(*navigation.release().leakRef()) autorelease];
3360 }
3361
3362 - (void)_close
3363 {
3364     _page->close();
3365 }
3366
3367 - (BOOL)_allowsRemoteInspection
3368 {
3369 #if ENABLE(REMOTE_INSPECTOR)
3370     return _page->allowsRemoteInspection();
3371 #else
3372     return NO;
3373 #endif
3374 }
3375
3376 - (void)_setAllowsRemoteInspection:(BOOL)allow
3377 {
3378 #if ENABLE(REMOTE_INSPECTOR)
3379     _page->setAllowsRemoteInspection(allow);
3380 #endif
3381 }
3382
3383 - (NSString *)_remoteInspectionNameOverride
3384 {
3385 #if ENABLE(REMOTE_INSPECTOR)
3386     return _page->remoteInspectionNameOverride();
3387 #else
3388     return nil;
3389 #endif
3390 }
3391
3392 - (void)_setRemoteInspectionNameOverride:(NSString *)name
3393 {
3394 #if ENABLE(REMOTE_INSPECTOR)
3395     _page->setRemoteInspectionNameOverride(name);
3396 #endif
3397 }
3398
3399 - (BOOL)_addsVisitedLinks
3400 {
3401     return _page->addsVisitedLinks();
3402 }
3403
3404 - (void)_setAddsVisitedLinks:(BOOL)addsVisitedLinks
3405 {
3406     _page->setAddsVisitedLinks(addsVisitedLinks);
3407 }
3408
3409 - (BOOL)_networkRequestsInProgress
3410 {
3411     return _page->pageLoadState().networkRequestsInProgress();
3412 }
3413
3414 static inline WebCore::LayoutMilestones layoutMilestones(_WKRenderingProgressEvents events)
3415 {
3416     WebCore::LayoutMilestones milestones = 0;
3417
3418     if (events & _WKRenderingProgressEventFirstLayout)
3419         milestones |= WebCore::DidFirstLayout;
3420
3421     if (events & _WKRenderingProgressEventFirstVisuallyNonEmptyLayout)
3422         milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
3423
3424     if (events & _WKRenderingProgressEventFirstPaintWithSignificantArea)
3425         milestones |= WebCore::DidHitRelevantRepaintedObjectsAreaThreshold;
3426
3427     if (events & _WKRenderingProgressEventReachedSessionRestorationRenderTreeSizeThreshold)
3428         milestones |= WebCore::ReachedSessionRestorationRenderTreeSizeThreshold;
3429
3430     if (events & _WKRenderingProgressEventFirstLayoutAfterSuppressedIncrementalRendering)
3431         milestones |= WebCore::DidFirstLayoutAfterSuppressedIncrementalRendering;
3432
3433     if (events & _WKRenderingProgressEventFirstPaintAfterSuppressedIncrementalRendering)
3434         milestones |= WebCore::DidFirstPaintAfterSuppressedIncrementalRendering;
3435
3436     return milestones;
3437 }
3438
3439 - (void)_setObservedRenderingProgressEvents:(_WKRenderingProgressEvents)observedRenderingProgressEvents
3440 {
3441     _observedRenderingProgressEvents = observedRenderingProgressEvents;
3442     _page->listenForLayoutMilestones(layoutMilestones(observedRenderingProgressEvents));
3443 }
3444
3445 - (void)_getMainResourceDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
3446 {
3447     auto handler = adoptNS([completionHandler copy]);
3448
3449     _page->getMainResourceDataOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
3450         void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
3451         if (error != WebKit::CallbackBase::Error::None) {
3452             // FIXME: Pipe a proper error in from the WebPageProxy.
3453             RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
3454             completionHandlerBlock(nil, error.get());
3455         } else
3456             completionHandlerBlock(wrapper(*data), nil);
3457     });
3458 }
3459
3460 - (void)_getWebArchiveDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
3461 {
3462     auto handler = adoptNS([completionHandler copy]);
3463
3464     _page->getWebArchiveOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
3465         void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
3466         if (error != WebKit::CallbackBase::Error::None) {
3467             // FIXME: Pipe a proper error in from the WebPageProxy.
3468             RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
3469             completionHandlerBlock(nil, error.get());
3470         } else
3471             completionHandlerBlock(wrapper(*data), nil);
3472     });
3473 }
3474
3475 - (_WKPaginationMode)_paginationMode
3476 {
3477     switch (_page->paginationMode()) {
3478     case WebCore::Pagination::Unpaginated:
3479         return _WKPaginationModeUnpaginated;
3480     case WebCore::Pagination::LeftToRightPaginated:
3481         return _WKPaginationModeLeftToRight;
3482     case WebCore::Pagination::RightToLeftPaginated:
3483         return _WKPaginationModeRightToLeft;
3484     case WebCore::Pagination::TopToBottomPaginated:
3485         return _WKPaginationModeTopToBottom;
3486     case WebCore::Pagination::BottomToTopPaginated:
3487         return _WKPaginationModeBottomToTop;
3488     }
3489
3490     ASSERT_NOT_REACHED();
3491     return _WKPaginationModeUnpaginated;
3492 }
3493
3494 - (void)_setPaginationMode:(_WKPaginationMode)paginationMode
3495 {
3496     WebCore::Pagination::Mode mode;
3497     switch (paginationMode) {
3498     case _WKPaginationModeUnpaginated:
3499         mode = WebCore::Pagination::Unpaginated;
3500         break;
3501     case _WKPaginationModeLeftToRight:
3502         mode = WebCore::Pagination::LeftToRightPaginated;
3503         break;
3504     case _WKPaginationModeRightToLeft:
3505         mode = WebCore::Pagination::RightToLeftPaginated;
3506         break;
3507     case _WKPaginationModeTopToBottom:
3508         mode = WebCore::Pagination::TopToBottomPaginated;
3509         break;
3510     case _WKPaginationModeBottomToTop:
3511         mode = WebCore::Pagination::BottomToTopPaginated;
3512         break;
3513     default:
3514         return;
3515     }
3516
3517     _page->setPaginationMode(mode);
3518 }
3519
3520 - (BOOL)_paginationBehavesLikeColumns
3521 {
3522     return _page->paginationBehavesLikeColumns();
3523 }
3524
3525 - (void)_setPaginationBehavesLikeColumns:(BOOL)behavesLikeColumns
3526 {
3527     _page->setPaginationBehavesLikeColumns(behavesLikeColumns);
3528 }
3529
3530 - (CGFloat)_pageLength
3531 {
3532     return _page->pageLength();
3533 }
3534
3535 - (void)_setPageLength:(CGFloat)pageLength
3536 {
3537     _page->setPageLength(pageLength);
3538 }
3539
3540 - (CGFloat)_gapBetweenPages
3541 {
3542     return _page->gapBetweenPages();
3543 }
3544
3545 - (void)_setGapBetweenPages:(CGFloat)gapBetweenPages
3546 {
3547     _page->setGapBetweenPages(gapBetweenPages);
3548 }
3549
3550 - (BOOL)_paginationLineGridEnabled
3551 {
3552     return _page->paginationLineGridEnabled();
3553 }
3554
3555 - (void)_setPagina