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