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