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