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