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