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