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