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