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