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