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