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