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