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