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