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