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