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