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