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