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