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