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