[Extra zoom mode] Remove effective font size constraints when determining focus zoom...
[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/MIMETypeRegistry.h>
101 #import <WebCore/PlatformScreen.h>
102 #import <WebCore/RuntimeApplicationChecks.h>
103 #import <WebCore/SQLiteDatabaseTracker.h>
104 #import <WebCore/SchemeRegistry.h>
105 #import <WebCore/Settings.h>
106 #import <WebCore/SharedBuffer.h>
107 #import <WebCore/ValidationBubble.h>
108 #import <WebCore/ViewportArguments.h>
109 #import <WebCore/WritingMode.h>
110 #import <pal/spi/cocoa/NSKeyedArchiverSPI.h>
111 #import <pal/spi/mac/NSTextFinderSPI.h>
112 #import <wtf/BlockPtr.h>
113 #import <wtf/HashMap.h>
114 #import <wtf/MathExtras.h>
115 #import <wtf/NeverDestroyed.h>
116 #import <wtf/Optional.h>
117 #import <wtf/RetainPtr.h>
118 #import <wtf/SetForScope.h>
119 #import <wtf/UUID.h>
120 #import <wtf/spi/darwin/dyldSPI.h>
121 #import <wtf/text/TextStream.h>
122
123 #if ENABLE(APPLICATION_MANIFEST)
124 #import "_WKApplicationManifestInternal.h"
125 #endif
126
127 #if ENABLE(DATA_DETECTION)
128 #import "WKDataDetectorTypesInternal.h"
129 #endif
130
131 #if PLATFORM(IOS)
132 #import "InteractionInformationAtPosition.h"
133 #import "InteractionInformationRequest.h"
134 #import "ProcessThrottler.h"
135 #import "RemoteLayerTreeDrawingAreaProxy.h"
136 #import "RemoteScrollingCoordinatorProxy.h"
137 #import "UIKitSPI.h"
138 #import "VideoFullscreenManagerProxy.h"
139 #import "WKContentViewInteraction.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 ([self _isDisplayingPDF])
1305         return [_customContentView web_isBackground];
1306     return [_contentView isBackground];
1307 }
1308
1309 - (void)setFrame:(CGRect)frame
1310 {
1311     CGRect oldFrame = self.frame;
1312     [super setFrame:frame];
1313
1314     if (!CGSizeEqualToSize(oldFrame.size, frame.size))
1315         [self _frameOrBoundsChanged];
1316 }
1317
1318 - (void)setBounds:(CGRect)bounds
1319 {
1320     CGRect oldBounds = self.bounds;
1321     [super setBounds:bounds];
1322     [_customContentFixedOverlayView setFrame:self.bounds];
1323
1324     if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
1325         [self _frameOrBoundsChanged];
1326 }
1327
1328 - (void)layoutSubviews
1329 {
1330     [super layoutSubviews];
1331     [self _frameOrBoundsChanged];
1332 }
1333
1334 - (UIScrollView *)scrollView
1335 {
1336     return _scrollView.get();
1337 }
1338
1339 - (WKBrowsingContextController *)browsingContextController
1340 {
1341     return [_contentView browsingContextController];
1342 }
1343
1344 - (BOOL)becomeFirstResponder
1345 {
1346     UIView *currentContentView = self._currentContentView;
1347     if (currentContentView == _contentView && [_contentView superview])
1348         return [_contentView becomeFirstResponderForWebView] || [super becomeFirstResponder];
1349
1350     return [currentContentView becomeFirstResponder] || [super becomeFirstResponder];
1351 }
1352
1353 - (BOOL)canBecomeFirstResponder
1354 {
1355     if (self._currentContentView == _contentView)
1356         return [_contentView canBecomeFirstResponderForWebView];
1357
1358     return YES;
1359 }
1360
1361 - (BOOL)resignFirstResponder
1362 {
1363     if ([_contentView isFirstResponder])
1364         return [_contentView resignFirstResponderForWebView];
1365
1366     return [super resignFirstResponder];
1367 }
1368
1369 #define FORWARD_ACTION_TO_WKCONTENTVIEW(_action) \
1370     - (void)_action:(id)sender \
1371     { \
1372         if (self.usesStandardContentView) \
1373             [_contentView _action ## ForWebView:sender]; \
1374     }
1375
1376 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_ACTION_TO_WKCONTENTVIEW)
1377
1378 #undef FORWARD_ACTION_TO_WKCONTENTVIEW
1379
1380 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
1381 {
1382     #define FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_action) \
1383         if (action == @selector(_action:)) \
1384             return self.usesStandardContentView && [_contentView canPerformActionForWebView:action withSender:sender];
1385
1386     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1387
1388     #undef FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW
1389
1390     return [super canPerformAction:action withSender:sender];
1391 }
1392
1393 - (id)targetForAction:(SEL)action withSender:(id)sender
1394 {
1395     #define FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_action) \
1396         if (action == @selector(_action:) && self.usesStandardContentView) \
1397             return [_contentView targetForActionForWebView:action withSender:sender];
1398
1399     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1400
1401     #undef FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW
1402
1403     return [super targetForAction:action withSender:sender];
1404 }
1405
1406 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
1407 {
1408     return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
1409 }
1410
1411 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
1412 {
1413     return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
1414         && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
1415 }
1416
1417 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
1418 {
1419     float deviceScaleFactor = page.deviceScaleFactor();
1420     return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
1421 }
1422
1423 - (UIView *)_currentContentView
1424 {
1425     return _customContentView ? _customContentView.get() : _contentView.get();
1426 }
1427
1428 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1429 {
1430     return [_configuration _contentProviderRegistry];
1431 }
1432
1433 - (WKSelectionGranularity)_selectionGranularity
1434 {
1435     return [_configuration selectionGranularity];
1436 }
1437
1438 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1439 {
1440     if (pageHasCustomContentView) {
1441         [_customContentView removeFromSuperview];
1442         [_customContentFixedOverlayView removeFromSuperview];
1443
1444         Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1445         ASSERT(representationClass);
1446         _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self]);
1447         _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1448         [_customContentFixedOverlayView layer].name = @"CustomContentFixedOverlay";
1449         [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1450
1451         [[_contentView unscaledView] removeFromSuperview];
1452         [_contentView removeFromSuperview];
1453         [_scrollView addSubview:_customContentView.get()];
1454         [self addSubview:_customContentFixedOverlayView.get()];
1455
1456         [_customContentView web_setMinimumSize:self.bounds.size];
1457         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1458
1459         _scrollViewBackgroundColor = WebCore::Color();
1460         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1461
1462         [self _setAvoidsUnsafeArea:NO];
1463     } else if (_customContentView) {
1464         [_customContentView removeFromSuperview];
1465         _customContentView = nullptr;
1466
1467         [_customContentFixedOverlayView removeFromSuperview];
1468         _customContentFixedOverlayView = nullptr;
1469
1470         [_scrollView addSubview:_contentView.get()];
1471         [_scrollView addSubview:[_contentView unscaledView]];
1472         [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1473
1474         [_customContentFixedOverlayView setFrame:self.bounds];
1475         [self addSubview:_customContentFixedOverlayView.get()];
1476     }
1477
1478     if (self.isFirstResponder) {
1479         UIView *currentContentView = self._currentContentView;
1480         if (currentContentView == _contentView ? [_contentView canBecomeFirstResponderForWebView] : currentContentView.canBecomeFirstResponder)
1481             [currentContentView becomeFirstResponder];
1482     }
1483 }
1484
1485 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1486 {
1487     ASSERT(_customContentView);
1488     [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1489
1490     // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1491     // because there's no guarantee that all custom content providers will lay out synchronously.
1492     _page->didLayoutForCustomContentProvider();
1493 }
1494
1495 - (void)_willInvokeUIScrollViewDelegateCallback
1496 {
1497     _delayUpdateVisibleContentRects = YES;
1498 }
1499
1500 - (void)_didInvokeUIScrollViewDelegateCallback
1501 {
1502     _delayUpdateVisibleContentRects = NO;
1503     if (_hadDelayedUpdateVisibleContentRects) {
1504         _hadDelayedUpdateVisibleContentRects = NO;
1505         [self _scheduleVisibleContentRectUpdate];
1506     }
1507 }
1508
1509 static CGFloat contentZoomScale(WKWebView *webView)
1510 {
1511     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1512     ASSERT(scale == [webView->_scrollView zoomScale]);
1513     return scale;
1514 }
1515
1516 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1517 {
1518     if (webView->_customContentView)
1519         return [webView->_customContentView backgroundColor].CGColor;
1520
1521     if (webView->_gestureController) {
1522         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1523         if (color.isValid())
1524             return color;
1525     }
1526
1527     return webView->_page->pageExtendedBackgroundColor();
1528 }
1529
1530 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1531 {
1532     if (!webView.opaque)
1533         return WebCore::Color::transparent;
1534
1535     WebCore::Color color = baseScrollViewBackgroundColor(webView);
1536
1537     if (!color.isValid())
1538         color = WebCore::Color::white;
1539
1540     CGFloat zoomScale = contentZoomScale(webView);
1541     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1542     if (zoomScale < minimumZoomScale) {
1543         CGFloat slope = 12;
1544         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1545         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1546     }
1547
1548     return color;
1549 }
1550
1551 - (void)_updateScrollViewBackground
1552 {
1553     WebCore::Color color = scrollViewBackgroundColor(self);
1554
1555     if (_scrollViewBackgroundColor == color)
1556         return;
1557
1558     _scrollViewBackgroundColor = color;
1559
1560     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1561     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1562
1563     // Update the indicator style based on the lightness/darkness of the background color.
1564     double hue, saturation, lightness;
1565     color.getHSL(hue, saturation, lightness);
1566     if (lightness <= .5 && color.isVisible())
1567         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1568     else
1569         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1570 }
1571
1572 - (void)_videoControlsManagerDidChange
1573 {
1574 #if ENABLE(FULLSCREEN_API)
1575     if (_fullScreenWindowController)
1576         [_fullScreenWindowController videoControlsManagerDidChange];
1577 #endif
1578 }
1579
1580 - (CGPoint)_initialContentOffsetForScrollView
1581 {
1582     auto combinedUnobscuredAndScrollViewInset = [self _computedContentInset];
1583     return CGPointMake(-combinedUnobscuredAndScrollViewInset.left, -combinedUnobscuredAndScrollViewInset.top);
1584 }
1585
1586 - (CGPoint)_contentOffsetAdjustedForObscuredInset:(CGPoint)point
1587 {
1588     CGPoint result = point;
1589     UIEdgeInsets contentInset = [self _computedObscuredInset];
1590
1591     result.x -= contentInset.left;
1592     result.y -= contentInset.top;
1593
1594     return result;
1595 }
1596
1597 - (UIRectEdge)_effectiveObscuredInsetEdgesAffectedBySafeArea
1598 {
1599     if (![self usesStandardContentView])
1600         return UIRectEdgeAll;
1601     return _obscuredInsetEdgesAffectedBySafeArea;
1602 }
1603
1604 - (UIEdgeInsets)_computedObscuredInset
1605 {
1606     if (_haveSetObscuredInsets)
1607         return _obscuredInsets;
1608
1609 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1610     if (self._safeAreaShouldAffectObscuredInsets)
1611         return UIEdgeInsetsAdd(UIEdgeInsetsZero, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1612 #endif
1613
1614     return UIEdgeInsetsZero;
1615 }
1616
1617 - (UIEdgeInsets)_computedContentInset
1618 {
1619     if (_haveSetObscuredInsets)
1620         return _obscuredInsets;
1621
1622     UIEdgeInsets insets = [_scrollView contentInset];
1623
1624 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1625     if (self._safeAreaShouldAffectObscuredInsets)
1626         insets = UIEdgeInsetsAdd(insets, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1627 #endif
1628
1629     return insets;
1630 }
1631
1632 - (UIEdgeInsets)_computedUnobscuredSafeAreaInset
1633 {
1634     if (_haveSetUnobscuredSafeAreaInsets)
1635         return _unobscuredSafeAreaInsets;
1636
1637 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1638     if (!self._safeAreaShouldAffectObscuredInsets)
1639         return self.safeAreaInsets;
1640 #endif
1641
1642     return UIEdgeInsetsZero;
1643 }
1644
1645 - (void)_processDidExit
1646 {
1647     [self _hidePasswordView];
1648     if (!_customContentView && _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1649         NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
1650         [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
1651         [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
1652         [_resizeAnimationView removeFromSuperview];
1653         _resizeAnimationView = nil;
1654
1655         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
1656     }
1657     [_contentView setFrame:self.bounds];
1658     [_scrollView setBackgroundColor:[UIColor whiteColor]];
1659     [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1660     [_scrollView setZoomScale:1];
1661
1662     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1663     _initialScaleFactor = 1;
1664     _hasCommittedLoadForMainFrame = NO;
1665     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1666     _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
1667     [_contentView setHidden:NO];
1668     _scrollOffsetToRestore = std::nullopt;
1669     _unobscuredCenterToRestore = std::nullopt;
1670     _scrollViewBackgroundColor = WebCore::Color();
1671     _delayUpdateVisibleContentRects = NO;
1672     _hadDelayedUpdateVisibleContentRects = NO;
1673     _lastSentMinimumLayoutSize = std::nullopt;
1674     _lastSentMaximumUnobscuredSize = std::nullopt;
1675     _lastSentDeviceOrientation = std::nullopt;
1676
1677     _frozenVisibleContentRect = std::nullopt;
1678     _frozenUnobscuredContentRect = std::nullopt;
1679
1680     _firstPaintAfterCommitLoadTransactionID = 0;
1681     _firstTransactionIDAfterPageRestore = std::nullopt;
1682     _resizeAnimationTransformTransactionID = std::nullopt;
1683
1684     _hasScheduledVisibleRectUpdate = NO;
1685     _commitDidRestoreScrollPosition = NO;
1686
1687     _avoidsUnsafeArea = YES;
1688 }
1689
1690 - (void)_didCommitLoadForMainFrame
1691 {
1692     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1693
1694     _hasCommittedLoadForMainFrame = YES;
1695     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1696
1697     [_scrollView _stopScrollingAndZoomingAnimations];
1698 }
1699
1700 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1701 {
1702 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1703     UIEdgeInsets contentInsets = scrollView.adjustedContentInset;
1704 #else
1705     UIEdgeInsets contentInsets = scrollView.contentInset;
1706 #endif
1707
1708     CGSize contentSize = scrollView.contentSize;
1709     CGSize scrollViewSize = scrollView.bounds.size;
1710
1711     CGPoint minimumContentOffset = CGPointMake(-contentInsets.left, -contentInsets.top);
1712     CGPoint maximumContentOffset = CGPointMake(std::max(minimumContentOffset.x, contentSize.width + contentInsets.right - scrollViewSize.width), std::max(minimumContentOffset.y, contentSize.height + contentInsets.bottom - scrollViewSize.height));
1713
1714     return CGPointMake(std::max(std::min(contentOffset.x, maximumContentOffset.x), minimumContentOffset.x), std::max(std::min(contentOffset.y, maximumContentOffset.y), minimumContentOffset.y));
1715 }
1716
1717 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1718 {
1719     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1720 }
1721
1722 - (WebCore::FloatRect)visibleRectInViewCoordinates
1723 {
1724     WebCore::FloatRect bounds = self.bounds;
1725     bounds.moveBy([_scrollView contentOffset]);
1726     WebCore::FloatRect contentViewBounds = [_contentView bounds];
1727     bounds.intersect(contentViewBounds);
1728     return bounds;
1729 }
1730
1731 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1732 // we need to ignore differences that are within a small rounding error on floats.
1733 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1734 {
1735     return WTF::areEssentiallyEqual(a, b);
1736 }
1737
1738 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1739 {
1740     if (![self usesStandardContentView])
1741         return;
1742
1743     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _didCommitLayerTree:] transactionID " <<  layerTreeTransaction.transactionID() << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
1744
1745     bool needUpdateVisibleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
1746
1747     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1748         if (_resizeAnimationTransformTransactionID && layerTreeTransaction.transactionID() >= _resizeAnimationTransformTransactionID.value()) {
1749             _resizeAnimationTransformTransactionID = std::nullopt;
1750             [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1751             if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithDocumentHidden) {
1752                 [_contentView setHidden:NO];
1753                 [self _endAnimatedResize];
1754             }
1755         }
1756         return;
1757     }
1758
1759     if (_activeAnimatedResizeCount)
1760         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCommitLayerTree:] - %d animated resizes in flight", self, _activeAnimatedResizeCount);
1761
1762     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1763     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1764
1765     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1766     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1767     [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1768     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom] && [_scrollView zoomScale] != layerTreeTransaction.pageScaleFactor()) {
1769         LOG_WITH_STREAM(VisibleRects, stream << " updating scroll view with pageScaleFactor " << layerTreeTransaction.pageScaleFactor());
1770         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1771     }
1772
1773     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1774     _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1775     _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1776     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1777     if (_page->inStableState() && layerTreeTransaction.isInStableState() && [_stableStatePresentationUpdateCallbacks count]) {
1778         for (dispatch_block_t action in _stableStatePresentationUpdateCallbacks.get())
1779             action();
1780
1781         [_stableStatePresentationUpdateCallbacks removeAllObjects];
1782         _stableStatePresentationUpdateCallbacks = nil;
1783     }
1784
1785     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1786         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1787
1788     [self _updateScrollViewBackground];
1789     [self _setAvoidsUnsafeArea:layerTreeTransaction.avoidsUnsafeArea()];
1790
1791     if (_gestureController)
1792         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1793
1794     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1795         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1796         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1797         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1798             _navigationState->didFirstPaint();
1799
1800         needUpdateVisibleContentRects = true;
1801     }
1802
1803     if (_firstTransactionIDAfterPageRestore && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore.value()) {
1804         if (_scrollOffsetToRestore) {
1805             WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore.value();
1806             _scrollOffsetToRestore = std::nullopt;
1807
1808             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1809                 scaledScrollOffset.scale(_scaleToRestore);
1810                 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - WebCore::FloatSize(_obscuredInsetsWhenSaved.left(), _obscuredInsetsWhenSaved.top());
1811
1812                 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1813                 _commitDidRestoreScrollPosition = YES;
1814             }
1815
1816             needUpdateVisibleContentRects = true;
1817         }
1818
1819         if (_unobscuredCenterToRestore) {
1820             WebCore::FloatPoint unobscuredCenterToRestore = _unobscuredCenterToRestore.value();
1821             _unobscuredCenterToRestore = std::nullopt;
1822
1823             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1824                 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1825                 WebCore::FloatSize unobscuredContentSizeAtNewScale = WebCore::FloatSize(unobscuredRect.size) / _scaleToRestore;
1826                 WebCore::FloatPoint topLeftInDocumentCoordinates = unobscuredCenterToRestore - unobscuredContentSizeAtNewScale / 2;
1827
1828                 topLeftInDocumentCoordinates.scale(_scaleToRestore);
1829                 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1830
1831                 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1832             }
1833
1834             needUpdateVisibleContentRects = true;
1835         }
1836
1837         if (_gestureController)
1838             _gestureController->didRestoreScrollPosition();
1839
1840         _firstTransactionIDAfterPageRestore = std::nullopt;
1841     }
1842
1843     if (needUpdateVisibleContentRects)
1844         [self _scheduleVisibleContentRectUpdate];
1845
1846     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1847         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1848 }
1849
1850 - (void)_layerTreeCommitComplete
1851 {
1852     _commitDidRestoreScrollPosition = NO;
1853 }
1854
1855 - (void)_dynamicViewportUpdateChangedTargetToScale:(double)newScale position:(CGPoint)newScrollPosition nextValidLayerTreeTransactionID:(uint64_t)nextValidLayerTreeTransactionID
1856 {
1857     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _dynamicViewportUpdateChangedTargetToScale:] " <<  newScale << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
1858
1859     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1860         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1861         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1862         double scale = newScale / currentTargetScale;
1863         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1864
1865         CGPoint newContentOffset = [self _contentOffsetAdjustedForObscuredInset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
1866         CGPoint currentContentOffset = [_scrollView contentOffset];
1867
1868         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1869         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1870         _resizeAnimationTransformTransactionID = nextValidLayerTreeTransactionID;
1871     }
1872 }
1873
1874 - (void)_couldNotRestorePageState
1875 {
1876     // The gestureController may be waiting for the scroll position to be restored
1877     // in order to remove the swipe snapshot. Since the scroll position could not be
1878     // restored, tell the gestureController it was restored so that it no longer waits
1879     // for it.
1880     if (_gestureController)
1881         _gestureController->didRestoreScrollPosition();
1882 }
1883
1884 - (void)_restorePageScrollPosition:(std::optional<WebCore::FloatPoint>)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatBoxExtent)obscuredInsets scale:(double)scale
1885 {
1886     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1887         return;
1888
1889     if (![self usesStandardContentView])
1890         return;
1891
1892     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1893     if (scrollPosition)
1894         _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition.value()), WebCore::toFloatSize(scrollOrigin));
1895     else
1896         _scrollOffsetToRestore = std::nullopt;
1897
1898     _obscuredInsetsWhenSaved = obscuredInsets;
1899     _scaleToRestore = scale;
1900 }
1901
1902 - (void)_restorePageStateToUnobscuredCenter:(std::optional<WebCore::FloatPoint>)center scale:(double)scale
1903 {
1904     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1905         return;
1906
1907     if (![self usesStandardContentView])
1908         return;
1909
1910     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1911     _unobscuredCenterToRestore = center.value();
1912
1913     _scaleToRestore = scale;
1914 }
1915
1916 - (RefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
1917 {
1918 #if HAVE(CORE_ANIMATION_RENDER_SERVER)
1919     float deviceScale = WebCore::screenScaleFactor();
1920     WebCore::FloatSize snapshotSize(self.bounds.size);
1921     snapshotSize.scale(deviceScale);
1922
1923     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
1924
1925 #if HAVE(IOSURFACE)
1926     WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
1927     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
1928     if (!surface)
1929         return nullptr;
1930     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
1931
1932 #if HAVE(IOSURFACE_ACCELERATOR)
1933     WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
1934     if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
1935         RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
1936         WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
1937             if (convertedSurface)
1938                 viewSnapshot->setSurface(WTFMove(convertedSurface));
1939         });
1940
1941         return viewSnapshot;
1942     }
1943 #endif // HAVE(IOSURFACE_ACCELERATOR)
1944
1945     return WebKit::ViewSnapshot::create(WTFMove(surface));
1946 #else // HAVE(IOSURFACE)
1947     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
1948
1949     if (!slotID)
1950         return nullptr;
1951
1952     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
1953     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
1954     return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
1955 #endif // HAVE(IOSURFACE)
1956 #else // HAVE(CORE_ANIMATION_RENDER_SERVER)
1957     return nullptr;
1958 #endif
1959 }
1960
1961 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
1962 {
1963     CFTimeInterval duration = 0;
1964     CGFloat zoomScale = contentZoomScale(self);
1965
1966     if (animated) {
1967         const double maximumZoomDuration = 0.4;
1968         const double minimumZoomDuration = 0.1;
1969         const double zoomDurationFactor = 0.3;
1970
1971         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
1972     }
1973
1974     if (scale != zoomScale)
1975         _page->willStartUserTriggeredZooming();
1976
1977     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
1978
1979     [_scrollView _zoomToCenter:point scale:scale duration:duration];
1980 }
1981
1982 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1983 {
1984     // FIXME: Some of this could be shared with _scrollToRect.
1985     const double visibleRectScaleChange = contentZoomScale(self) / scale;
1986     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
1987     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
1988
1989     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
1990     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
1991
1992     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
1993
1994     // Center to the target rect.
1995     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
1996
1997     // Center to the tap point instead in case the target rect won't fit in a direction.
1998     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
1999         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
2000     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
2001         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
2002
2003     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
2004     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
2005     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
2006     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
2007
2008     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
2009 }
2010
2011 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
2012 {
2013     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
2014     return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
2015 }
2016
2017 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
2018 {
2019     if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
2020         return;
2021
2022     WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
2023
2024     WebCore::FloatPoint scaledOffset = contentOffset;
2025     CGFloat zoomScale = contentZoomScale(self);
2026     scaledOffset.scale(zoomScale);
2027
2028     CGPoint contentOffsetInScrollViewCoordinates = [self _contentOffsetAdjustedForObscuredInset:scaledOffset];
2029     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2030
2031     [_scrollView _stopScrollingAndZoomingAnimations];
2032
2033     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
2034         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
2035     else {
2036         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
2037         // The WebProcess would keep the invalid contentOffset as its scroll position.
2038         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
2039         _page->resendLastVisibleContentRects();
2040     }
2041 }
2042
2043 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
2044 {
2045     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
2046     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
2047     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
2048
2049     // Center the target rect in the scroll view.
2050     // If the target doesn't fit in the scroll view, center on the gesture location instead.
2051     WebCore::FloatPoint newUnobscuredContentOffset;
2052     if (targetRect.width() <= unobscuredContentRect.width())
2053         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
2054     else
2055         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2056     if (targetRect.height() <= unobscuredContentRect.height())
2057         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
2058     else
2059         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2060     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2061
2062     if (unobscuredContentOffset == newUnobscuredContentOffset) {
2063         if (targetRect.width() > unobscuredContentRect.width())
2064             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2065         if (targetRect.height() > unobscuredContentRect.height())
2066             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2067         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2068     }
2069
2070     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
2071     scrollViewOffsetDelta.scale(contentZoomScale(self));
2072
2073     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
2074     if (scrollDistance < minimumScrollDistance)
2075         return false;
2076
2077     [_contentView willStartZoomOrScroll];
2078
2079     LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
2080
2081     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
2082     return true;
2083 }
2084
2085 - (void)_scrollByContentOffset:(WebCore::FloatPoint)contentOffsetDelta
2086 {
2087     WebCore::FloatPoint scaledOffsetDelta = contentOffsetDelta;
2088     CGFloat zoomScale = contentZoomScale(self);
2089     scaledOffsetDelta.scale(zoomScale);
2090
2091     CGPoint currentOffset = [_scrollView _isAnimatingScroll] ? [_scrollView _animatedTargetOffset] : [_scrollView contentOffset];
2092     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), currentOffset + scaledOffsetDelta);
2093
2094     if (CGPointEqualToPoint(boundedOffset, currentOffset))
2095         return;
2096     [_contentView willStartZoomOrScroll];
2097
2098     LOG_WITH_STREAM(VisibleRects, stream << "_scrollByContentOffset: scrolling to " << WebCore::FloatPoint(boundedOffset));
2099
2100     [_scrollView setContentOffset:boundedOffset animated:YES];
2101 }
2102
2103 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2104 {
2105     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
2106 }
2107
2108 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2109 {
2110     ASSERT(_initialScaleFactor > 0);
2111     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
2112 }
2113
2114 // focusedElementRect and selectionRect are both in document coordinates.
2115 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates insideFixed:(BOOL)insideFixed
2116     fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
2117 {
2118     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect:" << focusedElementRectInDocumentCoordinates << " selectionRect:" << selectionRectInDocumentCoordinates);
2119     UNUSED_PARAM(insideFixed);
2120
2121     const double minimumHeightToShowContentAboveKeyboard = 106;
2122     const CFTimeInterval formControlZoomAnimationDuration = 0.25;
2123     const double caretOffsetFromWindowEdge = 20;
2124
2125     UIWindow *window = [_scrollView window];
2126
2127     // Find the portion of the view that is visible on the screen.
2128     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
2129     UIView *fullScreenView = topViewController.view;
2130     if (!fullScreenView)
2131         fullScreenView = window;
2132
2133     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
2134     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
2135     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
2136     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
2137     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
2138
2139     CGFloat visibleOffsetFromTop = 0;
2140     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
2141         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2142         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
2143
2144         if (heightVisibleAboveFormAssistant >= minimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
2145             visibleSize.height = heightVisibleAboveFormAssistant;
2146         else {
2147             visibleSize.height = heightVisibleBelowFormAssistant;
2148             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2149         }
2150     }
2151
2152     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
2153     double currentScale = contentZoomScale(self);
2154     double scale = currentScale;
2155     if (allowScaling) {
2156 #if ENABLE(EXTRA_ZOOM_MODE)
2157         const CGFloat minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 10;
2158         const CGFloat maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 35;
2159
2160         CGRect minimumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2161         CGRect maximumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2162
2163         double clampedMaximumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(minimumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(minimumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2164         double clampedMinimumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(maximumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(maximumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2165         scale = clampTo<double>(currentScale, clampedMinimumTargetScale, clampedMaximumTargetScale);
2166 #else
2167         const double webViewStandardFontSize = 16;
2168         scale = clampTo<double>(webViewStandardFontSize / fontSize, minimumScale, maximumScale);
2169 #endif
2170     }
2171
2172     CGFloat documentWidth = [_contentView bounds].size.width;
2173     scale = CGRound(documentWidth * scale) / documentWidth;
2174
2175     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
2176     focusedElementRectInNewScale.scale(scale);
2177     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
2178
2179     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
2180     if (!forceScroll) {
2181         CGRect currentlyVisibleRegionInWebViewCoordinates;
2182         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
2183         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
2184         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
2185
2186         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
2187         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
2188             return;
2189
2190         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
2191         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
2192             return;
2193     }
2194
2195     // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
2196     // can get based on the visible area after zooming (workingFrame).  The spacing in either dimension is half the
2197     // difference between the size of the DOM node and the size of the visible frame.
2198     CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
2199     CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
2200
2201     CGPoint topLeft;
2202     topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
2203     topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
2204
2205     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
2206     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
2207     if (selectionRectIsNotNull) {
2208         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
2209         selectionRectInNewScale.scale(scale);
2210         selectionRectInNewScale.moveBy([_contentView frame].origin);
2211         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.width;
2212         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
2213     }
2214
2215     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
2216     documentBoundsInNewScale.scale(scale);
2217     documentBoundsInNewScale.moveBy([_contentView frame].origin);
2218
2219     // Constrain the left edge in document coordinates so that:
2220     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2221     //  - it isn't so great that the document's right edge is less than the right edge of the screen
2222     if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
2223         topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
2224     else {
2225         CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
2226         if (topLeft.x > maximumAllowableHorizontalOffset)
2227             topLeft.x = maximumAllowableHorizontalOffset;
2228     }
2229
2230     // Constrain the top edge in document coordinates so that:
2231     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2232     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
2233     if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
2234         topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
2235     else {
2236         CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
2237         if (topLeft.y > maximumAllowableVerticalOffset)
2238             topLeft.y = maximumAllowableVerticalOffset;
2239     }
2240
2241     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
2242
2243     if (scale != currentScale)
2244         _page->willStartUserTriggeredZooming();
2245
2246     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
2247
2248     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
2249     newCenter.scale(1 / scale);
2250     [_scrollView _zoomToCenter:newCenter scale:scale duration:formControlZoomAnimationDuration force:YES];
2251 }
2252
2253 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
2254 {
2255     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
2256     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
2257     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
2258
2259     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
2260     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
2261
2262     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
2263 }
2264
2265 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
2266 {
2267     const float maximumScaleFactorDeltaForPanScroll = 0.02;
2268
2269     double currentScale = contentZoomScale(self);
2270     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
2271
2272     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
2273         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
2274             return true;
2275     } else if (targetScale != currentScale) {
2276         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
2277         return true;
2278     }
2279
2280     return false;
2281 }
2282
2283 - (void)didMoveToWindow
2284 {
2285     _page->activityStateDidChange(WebCore::ActivityState::AllFlags);
2286 }
2287
2288 - (void)setOpaque:(BOOL)opaque
2289 {
2290     BOOL oldOpaque = self.opaque;
2291
2292     [super setOpaque:opaque];
2293     [_contentView setOpaque:opaque];
2294
2295     if (oldOpaque == opaque)
2296         return;
2297
2298     if (!_page)
2299         return;
2300
2301     _page->setDrawsBackground(opaque);
2302     [self _updateScrollViewBackground];
2303 }
2304
2305 - (void)setBackgroundColor:(UIColor *)backgroundColor
2306 {
2307     [super setBackgroundColor:backgroundColor];
2308     [_contentView setBackgroundColor:backgroundColor];
2309 }
2310
2311 - (BOOL)_allowsDoubleTapGestures
2312 {
2313     if (_fastClickingIsDisabled)
2314         return YES;
2315
2316     // If the page is not user scalable, we don't allow double tap gestures.
2317     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
2318         return NO;
2319
2320     // If the viewport width was not explicit, we allow double tap gestures.
2321     if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
2322         return YES;
2323
2324     // If the page set a viewport width that wasn't the device width, then it was
2325     // scaled and thus will probably need to zoom.
2326     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
2327         return YES;
2328
2329     // At this point, we have a page that asked for width = device-width. However,
2330     // if the content's width and height were large, we might have had to shrink it.
2331     // Since we'll enable double tap zoom whenever we're not at the actual
2332     // initial scale, this simply becomes a test of the current scale against 1.
2333     return !areEssentiallyEqualAsFloat(contentZoomScale(self), 1);
2334 }
2335
2336 #pragma mark - UIScrollViewDelegate
2337
2338 - (BOOL)usesStandardContentView
2339 {
2340     return !_customContentView && !_passwordView;
2341 }
2342
2343 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
2344 {
2345     return roundScrollViewContentSize(*_page, proposedSize);
2346 }
2347
2348 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
2349 {
2350     ASSERT(_scrollView == scrollView);
2351
2352     if (_customContentView)
2353         return _customContentView.get();
2354
2355     return _contentView.get();
2356 }
2357
2358 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
2359 {
2360     if (![self usesStandardContentView])
2361         return;
2362
2363     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
2364         _page->willStartUserTriggeredZooming();
2365         [_contentView scrollViewWillStartPanOrPinchGesture];
2366     }
2367     [_contentView willStartZoomOrScroll];
2368 }
2369
2370 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2371 {
2372     if (![self usesStandardContentView])
2373         return;
2374
2375     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2376         [_contentView scrollViewWillStartPanOrPinchGesture];
2377
2378     [_contentView willStartZoomOrScroll];
2379 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2380     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2381     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2382     ASSERT(scrollView == _scrollView.get());
2383     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2384     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2385     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2386 #endif
2387 }
2388
2389 - (void)_didFinishScrolling
2390 {
2391     if (![self usesStandardContentView])
2392         return;
2393
2394     [self _scheduleVisibleContentRectUpdate];
2395     [_contentView didFinishScrolling];
2396 }
2397
2398 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2399 {
2400     // Work around <rdar://problem/16374753> by avoiding deceleration while
2401     // zooming. We'll animate to the right place once the zoom finishes.
2402     if ([scrollView isZooming])
2403         *targetContentOffset = [scrollView contentOffset];
2404 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2405     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2406         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2407         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2408
2409         UIEdgeInsets obscuredInset;
2410
2411         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2412         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2413             obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2414         else
2415             obscuredInset = [self _computedObscuredInset];
2416
2417         CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
2418
2419         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2420     }
2421 #endif
2422 }
2423
2424 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2425 {
2426     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2427     if (!decelerate)
2428         [self _didFinishScrolling];
2429 }
2430
2431 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2432 {
2433     [self _didFinishScrolling];
2434 }
2435
2436 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2437 {
2438     [self _didFinishScrolling];
2439 }
2440
2441 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2442 {
2443     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidScroll:)])
2444         [_customContentView web_scrollViewDidScroll:(UIScrollView *)scrollView];
2445
2446     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2447
2448     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2449         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2450 }
2451
2452 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2453 {
2454     [self _updateScrollViewBackground];
2455     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2456 }
2457
2458 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2459 {
2460     ASSERT(scrollView == _scrollView);
2461     // FIXME: remove when rdar://problem/36065495 is fixed.
2462     // When rotating with two fingers down, UIScrollView can set a bogus content view position.
2463     // "Center" is top left because we set the anchorPoint to 0,0.
2464     [_contentView setCenter:self.bounds.origin];
2465
2466     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2467     [_contentView didZoomToScale:scale];
2468 }
2469
2470 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2471 {
2472     [self _didFinishScrolling];
2473 }
2474
2475 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2476 {
2477     if (![self usesStandardContentView])
2478         return;
2479
2480     [_contentView didInterruptScrolling];
2481     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2482 }
2483
2484 - (UIView *)_enclosingViewForExposedRectComputation
2485 {
2486     return [self _scroller];
2487 }
2488
2489 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2490 {
2491     if (!enclosingView)
2492         return self.bounds;
2493
2494     CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2495     return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2496 }
2497
2498 - (CGRect)_visibleContentRect
2499 {
2500     if (_frozenVisibleContentRect)
2501         return _frozenVisibleContentRect.value();
2502
2503     CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2504
2505     if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2506         CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2507         CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2508         visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2509     }
2510
2511     return visibleRectInContentCoordinates;
2512 }
2513
2514 // Called when some ancestor UIScrollView scrolls.
2515 - (void)_didScroll
2516 {
2517     [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2518
2519     const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2520     if (!_enclosingScrollViewScrollTimer) {
2521         _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2522             interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2523         [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2524     }
2525     _didScrollSinceLastTimerFire = YES;
2526 }
2527
2528 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2529 {
2530     if (_didScrollSinceLastTimerFire) {
2531         _didScrollSinceLastTimerFire = NO;
2532         return;
2533     }
2534
2535     [self _scheduleVisibleContentRectUpdate];
2536     [_enclosingScrollViewScrollTimer invalidate];
2537     _enclosingScrollViewScrollTimer = nil;
2538 }
2539
2540 - (UIEdgeInsets)_scrollViewSystemContentInset
2541 {
2542     // It's not safe to access the scroll view's safeAreaInsets or _systemContentInset from
2543     // inside our layoutSubviews implementation, because they aren't updated until afterwards.
2544     // Instead, depend on the fact that the UIScrollView and WKWebView are in the same coordinate
2545     // space, and map the WKWebView's own insets into the scroll view manually.
2546     return UIEdgeInsetsAdd([_scrollView _contentScrollInset], self.safeAreaInsets, [_scrollView _edgesApplyingSafeAreaInsetsToContentInset]);
2547 }
2548
2549 - (CGFloat)_minimumAllowedLayoutWidth
2550 {
2551     return _minimumAllowedLayoutWidth;
2552 }
2553
2554 - (void)_setMinimumAllowedLayoutWidth:(CGFloat)minimumAllowedLayoutWidth
2555 {
2556     if (_minimumAllowedLayoutWidth == minimumAllowedLayoutWidth)
2557         return;
2558
2559     _minimumAllowedLayoutWidth = minimumAllowedLayoutWidth;
2560
2561     auto sizes = [self activeMinimumLayoutSizes:self.bounds];
2562     [self _dispatchSetMinimumLayoutSize:sizes.minimumLayoutSize viewSize:sizes.viewSize];
2563 }
2564
2565 - (ActiveViewportLayoutSizes)activeMinimumLayoutSizes:(const CGRect&)bounds
2566 {
2567     if (_overridesMinimumLayoutSize)
2568         return { WebCore::FloatSize(_minimumLayoutSizeOverride), WebCore::FloatSize(_minimumLayoutSizeOverride) };
2569
2570     ActiveViewportLayoutSizes sizes;
2571 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2572     sizes.viewSize = WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), self._scrollViewSystemContentInset).size);
2573 #else
2574     sizes.viewSize = WebCore::FloatSize { bounds.size };
2575 #endif
2576
2577     sizes.minimumLayoutSize = { std::max<float>(sizes.viewSize.width(), self._minimumAllowedLayoutWidth), sizes.viewSize.height() };
2578     return sizes;
2579 }
2580
2581 - (void)_dispatchSetMinimumLayoutSize:(WebCore::FloatSize)minimumLayoutSize viewSize:(WebCore::FloatSize)viewSize
2582 {
2583     if (_lastSentMinimumLayoutSize && CGSizeEqualToSize(_lastSentMinimumLayoutSize.value(), minimumLayoutSize))
2584         return;
2585
2586     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _dispatchSetMinimumLayoutSize:] " << minimumLayoutSize << " viewSize " << viewSize << " contentZoomScale " << contentZoomScale(self));
2587     _page->setViewportConfigurationMinimumLayoutSize(minimumLayoutSize, viewSize);
2588     _lastSentMinimumLayoutSize = minimumLayoutSize;
2589 }
2590
2591 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2592 {
2593     if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2594         return;
2595
2596     _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2597     _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2598 }
2599
2600 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2601 {
2602     if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2603         return;
2604
2605     _page->setDeviceOrientation(deviceOrientation);
2606     _lastSentDeviceOrientation = deviceOrientation;
2607 }
2608
2609 - (void)_frameOrBoundsChanged
2610 {
2611     CGRect bounds = self.bounds;
2612     [_scrollView setFrame:bounds];
2613
2614     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing) {
2615         if (!_overridesMinimumLayoutSize) {
2616             auto sizes = [self activeMinimumLayoutSizes:self.bounds];
2617             [self _dispatchSetMinimumLayoutSize:sizes.minimumLayoutSize viewSize:sizes.viewSize];
2618         }
2619         if (!_overridesMaximumUnobscuredSize)
2620             [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
2621
2622         BOOL sizeChanged = NO;
2623         if (auto drawingArea = _page->drawingArea())
2624             sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size));
2625
2626         if (sizeChanged & [self usesStandardContentView])
2627             [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
2628     }
2629
2630     [_customContentView web_setMinimumSize:bounds.size];
2631     [self _scheduleVisibleContentRectUpdate];
2632 }
2633
2634 // 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.
2635 - (CGRect)_contentRectForUserInteraction
2636 {
2637     // FIXME: handle split keyboard.
2638     UIEdgeInsets obscuredInsets = _obscuredInsets;
2639     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2640     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2641     return [self convertRect:unobscuredRect toView:self._currentContentView];
2642 }
2643
2644 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2645 - (BOOL)_scrollViewIsRubberBanding
2646 {
2647     float deviceScaleFactor = _page->deviceScaleFactor();
2648
2649     CGPoint contentOffset = [_scrollView contentOffset];
2650     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2651     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2652 }
2653
2654 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2655 - (void)safeAreaInsetsDidChange
2656 {
2657     [super safeAreaInsetsDidChange];
2658
2659     [self _scheduleVisibleContentRectUpdate];
2660 }
2661 #endif
2662
2663 - (void)_scheduleVisibleContentRectUpdate
2664 {
2665     // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
2666     [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
2667 }
2668
2669 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
2670 {
2671     BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2672
2673     if (isStableState && scrollView == _scrollView.get())
2674         isStableState = !_isChangingObscuredInsetsInteractively;
2675
2676     if (isStableState && scrollView == _scrollView.get())
2677         isStableState = ![self _scrollViewIsRubberBanding];
2678
2679     if (isStableState)
2680         isStableState = !scrollView._isInterruptingDeceleration;
2681
2682     if (NSNumber *stableOverride = self._stableStateOverride)
2683         isStableState = stableOverride.boolValue;
2684
2685     return isStableState;
2686 }
2687
2688 - (void)_addUpdateVisibleContentRectPreCommitHandler
2689 {
2690     auto retainedSelf = retainPtr(self);
2691     [CATransaction addCommitHandler:[retainedSelf] {
2692         WKWebView *webView = retainedSelf.get();
2693         if (![webView _isValid])
2694             return;
2695         [webView _updateVisibleContentRects];
2696         webView->_hasScheduledVisibleRectUpdate = NO;
2697     } forPhase:kCATransactionPhasePreCommit];
2698 }
2699
2700 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
2701 {
2702     _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
2703
2704     if (_hasScheduledVisibleRectUpdate)
2705         return;
2706
2707     _hasScheduledVisibleRectUpdate = YES;
2708
2709 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2710     CATransactionPhase transactionPhase = [CATransaction currentPhase];
2711     if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
2712         [self _addUpdateVisibleContentRectPreCommitHandler];
2713         return;
2714     }
2715 #endif
2716
2717     dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
2718         WKWebView *webView = retainedSelf.get();
2719         if (![webView _isValid])
2720             return;
2721         [webView _addUpdateVisibleContentRectPreCommitHandler];
2722     });
2723 }
2724
2725 static bool scrollViewCanScroll(UIScrollView *scrollView)
2726 {
2727     if (!scrollView)
2728         return NO;
2729
2730     UIEdgeInsets contentInset = scrollView.contentInset;
2731     CGSize contentSize = scrollView.contentSize;
2732     CGSize boundsSize = scrollView.bounds.size;
2733
2734     return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2735         || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2736 }
2737
2738 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
2739 {
2740     CGPoint contentOffset = [_scrollView contentOffset];
2741     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2742
2743     CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
2744     CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
2745
2746     CGRect extendedBounds = [_contentView bounds];
2747
2748     if (horiontalRubberbandAmountInContentCoordinates < 0) {
2749         extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
2750         extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
2751     } else if (horiontalRubberbandAmountInContentCoordinates > 0)
2752         extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
2753
2754     if (verticalRubberbandAmountInContentCoordinates < 0) {
2755         extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
2756         extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
2757     } else if (verticalRubberbandAmountInContentCoordinates > 0)
2758         extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
2759
2760     return extendedBounds;
2761 }
2762
2763 - (void)_updateVisibleContentRects
2764 {
2765     BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
2766
2767     if (![self usesStandardContentView]) {
2768         [_passwordView setFrame:self.bounds];
2769         [_customContentView web_computedContentInsetDidChange];
2770         return;
2771     }
2772
2773     if (_delayUpdateVisibleContentRects) {
2774         _hadDelayedUpdateVisibleContentRects = YES;
2775         return;
2776     }
2777
2778     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing
2779         || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
2780         || [_scrollView isZoomBouncing]
2781         || _currentlyAdjustingScrollViewInsetsForKeyboard)
2782         return;
2783
2784     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2785
2786     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
2787     if (!_haveSetObscuredInsets)
2788         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2789
2790     CGFloat scaleFactor = contentZoomScale(self);
2791
2792     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
2793     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2794     unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
2795
2796 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2797     if (inStableState) {
2798         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2799         if (coordinator && coordinator->hasActiveSnapPoint()) {
2800             CGPoint currentPoint = [_scrollView contentOffset];
2801             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2802
2803             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2804                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2805                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2806                     [strongScrollView setContentOffset:activePoint animated:NO];
2807                 });
2808             }
2809         }
2810     }
2811 #endif
2812
2813     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2814         unobscuredRect:unobscuredRectInContentCoordinates
2815         unobscuredRectInScrollViewCoordinates:unobscuredRect
2816         obscuredInsets:_obscuredInsets
2817         unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
2818         inputViewBounds:_inputViewBounds
2819         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2820         inStableState:inStableState
2821         isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2822         enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2823
2824     while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
2825         auto callback = _visibleContentRectUpdateCallbacks.takeLast();
2826         callback();
2827     }
2828 }
2829
2830 - (void)_didFinishLoadForMainFrame
2831 {
2832     if (_gestureController)
2833         _gestureController->didFinishLoadForMainFrame();
2834 }
2835
2836 - (void)_didFailLoadForMainFrame
2837 {
2838     if (_gestureController)
2839         _gestureController->didFailLoadForMainFrame();
2840 }
2841
2842 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
2843 {
2844     [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
2845
2846     if (_gestureController)
2847         _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
2848 }
2849
2850 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
2851 {
2852     NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
2853     if (!endFrameValue)
2854         return;
2855
2856     // The keyboard rect is always in screen coordinates. In the view services case the window does not
2857     // have the interface orientation rotation transformation; its host does. So, it makes no sense to
2858     // clip the keyboard rect against its screen.
2859     if ([[self window] _isHostedInAnotherProcess])
2860         _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
2861     else
2862         _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
2863
2864     if (adjustScrollView) {
2865         CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
2866         SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
2867         [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
2868         CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
2869         if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
2870             _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
2871     }
2872
2873     [self _scheduleVisibleContentRectUpdate];
2874 }
2875
2876 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
2877 {
2878     if ([_contentView isAssistingNode])
2879         return YES;
2880
2881     NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
2882     return isLocalKeyboard && !isLocalKeyboard.boolValue;
2883 }
2884
2885 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
2886 {
2887     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2888         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2889 }
2890
2891 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
2892 {
2893     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
2894 }
2895
2896 - (void)_keyboardWillShow:(NSNotification *)notification
2897 {
2898     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
2899         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2900
2901     _page->setIsKeyboardAnimatingIn(true);
2902 }
2903
2904 - (void)_keyboardDidShow:(NSNotification *)notification
2905 {
2906     _page->setIsKeyboardAnimatingIn(false);
2907 }
2908
2909 - (void)_keyboardWillHide:(NSNotification *)notification
2910 {
2911     // Ignore keyboard will hide notifications sent during rotation. They're just there for
2912     // backwards compatibility reasons and processing the will hide notification would
2913     // temporarily screw up the unobscured view area.
2914     if ([[UIPeripheralHost sharedInstance] rotationState])
2915         return;
2916
2917     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
2918 }
2919
2920 - (void)_windowDidRotate:(NSNotification *)notification
2921 {
2922     if (!_overridesInterfaceOrientation)
2923         [self _dispatchSetDeviceOrientation:deviceOrientation()];
2924 }
2925
2926 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
2927 {
2928     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
2929 }
2930
2931 - (NSString *)_contentSizeCategory
2932 {
2933     return [[UIApplication sharedApplication] preferredContentSizeCategory];
2934 }
2935
2936 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
2937 {
2938     _page->accessibilitySettingsDidChange();
2939 }
2940
2941 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
2942 {
2943     if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
2944         return;
2945
2946     _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
2947
2948     if (allowsBackForwardNavigationGestures) {
2949         if (!_gestureController) {
2950             _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
2951             _gestureController->installSwipeHandler(self, [self scrollView]);
2952             if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
2953                 _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
2954         }
2955     } else
2956         _gestureController = nullptr;
2957
2958     _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
2959 }
2960
2961 - (BOOL)allowsBackForwardNavigationGestures
2962 {
2963     return _allowsBackForwardNavigationGestures;
2964 }
2965
2966 - (BOOL)_isNavigationSwipeGestureRecognizer:(UIGestureRecognizer *)recognizer
2967 {
2968     if (!_gestureController)
2969         return NO;
2970     return _gestureController->isNavigationSwipeGestureRecognizer(recognizer);
2971 }
2972
2973 - (void)_navigationGestureDidBegin
2974 {
2975     // During a back/forward swipe, there's a view interposed between this view and the content view that has
2976     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
2977     // frozen rects during swipes.
2978     CGRect fullViewRect = self.bounds;
2979     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedObscuredInset]);
2980
2981     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
2982     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
2983
2984     LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << WebCore::FloatRect(_frozenVisibleContentRect.value()) << " UnobscuredContentRect " << WebCore::FloatRect(_frozenUnobscuredContentRect.value()));
2985 }
2986
2987 - (void)_navigationGestureDidEnd
2988 {
2989     _frozenVisibleContentRect = std::nullopt;
2990     _frozenUnobscuredContentRect = std::nullopt;
2991 }
2992
2993 - (void)_showPasswordViewWithDocumentName:(NSString *)documentName passwordHandler:(void (^)(NSString *))passwordHandler
2994 {
2995     ASSERT(!_passwordView);
2996     _passwordView = adoptNS([[WKPasswordView alloc] initWithFrame:self.bounds documentName:documentName]);
2997     [_passwordView setUserDidEnterPassword:passwordHandler];
2998     [_passwordView showInScrollView:_scrollView.get()];
2999     self._currentContentView.hidden = YES;
3000 }
3001
3002 - (void)_hidePasswordView
3003 {
3004     if (!_passwordView)
3005         return;
3006
3007     self._currentContentView.hidden = NO;
3008     [_passwordView hide];
3009     _passwordView = nil;
3010 }
3011
3012 - (WKPasswordView *)_passwordView
3013 {
3014     return _passwordView.get();
3015 }
3016
3017 - (void)_updateScrollViewInsetAdjustmentBehavior
3018 {
3019 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
3020     if (![_scrollView _contentInsetAdjustmentBehaviorWasExternallyOverridden])
3021         [_scrollView _setContentInsetAdjustmentBehaviorInternal:self._safeAreaShouldAffectObscuredInsets ? UIScrollViewContentInsetAdjustmentAlways : UIScrollViewContentInsetAdjustmentNever];
3022 #endif
3023 }
3024
3025 - (void)_setAvoidsUnsafeArea:(BOOL)avoidsUnsafeArea
3026 {
3027     if (_avoidsUnsafeArea == avoidsUnsafeArea)
3028         return;
3029
3030     _avoidsUnsafeArea = avoidsUnsafeArea;
3031
3032     [self _updateScrollViewInsetAdjustmentBehavior];
3033     [self _scheduleVisibleContentRectUpdate];
3034
3035     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
3036     if ([uiDelegate respondsToSelector:@selector(_webView:didChangeSafeAreaShouldAffectObscuredInsets:)])
3037         [uiDelegate _webView:self didChangeSafeAreaShouldAffectObscuredInsets:avoidsUnsafeArea];
3038 }
3039
3040 #endif // PLATFORM(IOS)
3041
3042 #pragma mark OS X-specific methods
3043
3044 #if PLATFORM(MAC)
3045
3046 - (BOOL)acceptsFirstResponder
3047 {
3048     return _impl->acceptsFirstResponder();
3049 }
3050
3051 - (BOOL)becomeFirstResponder
3052 {
3053     return _impl->becomeFirstResponder();
3054 }
3055
3056 - (BOOL)resignFirstResponder
3057 {
3058     return _impl->resignFirstResponder();
3059 }
3060
3061 - (void)viewWillStartLiveResize
3062 {
3063     _impl->viewWillStartLiveResize();
3064 }
3065
3066 - (void)viewDidEndLiveResize
3067 {
3068     _impl->viewDidEndLiveResize();
3069 }
3070
3071 - (BOOL)isFlipped
3072 {
3073     return YES;
3074 }
3075
3076 - (NSSize)intrinsicContentSize
3077 {
3078     return NSSizeFromCGSize(_impl->intrinsicContentSize());
3079 }
3080
3081 - (void)prepareContentInRect:(NSRect)rect
3082 {
3083     _impl->prepareContentInRect(NSRectToCGRect(rect));
3084 }
3085
3086 - (void)setFrameSize:(NSSize)size
3087 {
3088     [super setFrameSize:size];
3089     _impl->setFrameSize(NSSizeToCGSize(size));
3090 }
3091
3092 - (void)renewGState
3093 {
3094     _impl->renewGState();
3095     [super renewGState];
3096 }
3097
3098 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
3099
3100 WEBCORE_COMMAND(alignCenter)
3101 WEBCORE_COMMAND(alignJustified)
3102 WEBCORE_COMMAND(alignLeft)
3103 WEBCORE_COMMAND(alignRight)
3104 WEBCORE_COMMAND(copy)
3105 WEBCORE_COMMAND(cut)
3106 WEBCORE_COMMAND(delete)
3107 WEBCORE_COMMAND(deleteBackward)
3108 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
3109 WEBCORE_COMMAND(deleteForward)
3110 WEBCORE_COMMAND(deleteToBeginningOfLine)
3111 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
3112 WEBCORE_COMMAND(deleteToEndOfLine)
3113 WEBCORE_COMMAND(deleteToEndOfParagraph)
3114 WEBCORE_COMMAND(deleteToMark)
3115 WEBCORE_COMMAND(deleteWordBackward)
3116 WEBCORE_COMMAND(deleteWordForward)
3117 WEBCORE_COMMAND(ignoreSpelling)
3118 WEBCORE_COMMAND(indent)
3119 WEBCORE_COMMAND(insertBacktab)
3120 WEBCORE_COMMAND(insertLineBreak)
3121 WEBCORE_COMMAND(insertNewline)
3122 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
3123 WEBCORE_COMMAND(insertParagraphSeparator)
3124 WEBCORE_COMMAND(insertTab)
3125 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
3126 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
3127 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
3128 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
3129 WEBCORE_COMMAND(moveBackward)
3130 WEBCORE_COMMAND(moveBackwardAndModifySelection)
3131 WEBCORE_COMMAND(moveDown)
3132 WEBCORE_COMMAND(moveDownAndModifySelection)
3133 WEBCORE_COMMAND(moveForward)
3134 WEBCORE_COMMAND(moveForwardAndModifySelection)
3135 WEBCORE_COMMAND(moveLeft)
3136 WEBCORE_COMMAND(moveLeftAndModifySelection)
3137 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
3138 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
3139 WEBCORE_COMMAND(moveRight)
3140 WEBCORE_COMMAND(moveRightAndModifySelection)
3141 WEBCORE_COMMAND(moveToBeginningOfDocument)
3142 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
3143 WEBCORE_COMMAND(moveToBeginningOfLine)
3144 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
3145 WEBCORE_COMMAND(moveToBeginningOfParagraph)
3146 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
3147 WEBCORE_COMMAND(moveToBeginningOfSentence)
3148 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
3149 WEBCORE_COMMAND(moveToEndOfDocument)
3150 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
3151 WEBCORE_COMMAND(moveToEndOfLine)
3152 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
3153 WEBCORE_COMMAND(moveToEndOfParagraph)
3154 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
3155 WEBCORE_COMMAND(moveToEndOfSentence)
3156 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
3157 WEBCORE_COMMAND(moveToLeftEndOfLine)
3158 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
3159 WEBCORE_COMMAND(moveToRightEndOfLine)
3160 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
3161 WEBCORE_COMMAND(moveUp)
3162 WEBCORE_COMMAND(moveUpAndModifySelection)
3163 WEBCORE_COMMAND(moveWordBackward)
3164 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
3165 WEBCORE_COMMAND(moveWordForward)
3166 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
3167 WEBCORE_COMMAND(moveWordLeft)
3168 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
3169 WEBCORE_COMMAND(moveWordRight)
3170 WEBCORE_COMMAND(moveWordRightAndModifySelection)
3171 WEBCORE_COMMAND(outdent)
3172 WEBCORE_COMMAND(pageDown)
3173 WEBCORE_COMMAND(pageDownAndModifySelection)
3174 WEBCORE_COMMAND(pageUp)
3175 WEBCORE_COMMAND(pageUpAndModifySelection)
3176 WEBCORE_COMMAND(paste)
3177 WEBCORE_COMMAND(pasteAsPlainText)
3178 WEBCORE_COMMAND(scrollPageDown)
3179 WEBCORE_COMMAND(scrollPageUp)
3180 WEBCORE_COMMAND(scrollLineDown)
3181 WEBCORE_COMMAND(scrollLineUp)
3182 WEBCORE_COMMAND(scrollToBeginningOfDocument)
3183 WEBCORE_COMMAND(scrollToEndOfDocument)
3184 WEBCORE_COMMAND(selectAll)
3185 WEBCORE_COMMAND(selectLine)
3186 WEBCORE_COMMAND(selectParagraph)
3187 WEBCORE_COMMAND(selectSentence)
3188 WEBCORE_COMMAND(selectToMark)
3189 WEBCORE_COMMAND(selectWord)
3190 WEBCORE_COMMAND(setMark)
3191 WEBCORE_COMMAND(subscript)
3192 WEBCORE_COMMAND(superscript)
3193 WEBCORE_COMMAND(swapWithMark)
3194 WEBCORE_COMMAND(takeFindStringFromSelection)
3195 WEBCORE_COMMAND(transpose)
3196 WEBCORE_COMMAND(underline)
3197 WEBCORE_COMMAND(unscript)
3198 WEBCORE_COMMAND(yank)
3199 WEBCORE_COMMAND(yankAndSelect)
3200
3201 #undef WEBCORE_COMMAND
3202
3203 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
3204 {
3205     return _impl->writeSelectionToPasteboard(pasteboard, types);
3206 }
3207
3208 - (void)centerSelectionInVisibleArea:(id)sender
3209 {
3210     _impl->centerSelectionInVisibleArea();
3211 }
3212
3213 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
3214 {
3215     return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
3216 }
3217
3218 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
3219 {
3220     return _impl->readSelectionFromPasteboard(pasteboard);
3221 }
3222
3223 - (void)changeFont:(id)sender
3224 {
3225     _impl->changeFontFromFontPanel();
3226 }
3227
3228 - (IBAction)startSpeaking:(id)sender
3229 {
3230     _impl->startSpeaking();
3231 }
3232
3233 - (IBAction)stopSpeaking:(id)sender
3234 {
3235     _impl->stopSpeaking(sender);
3236 }
3237
3238 - (IBAction)showGuessPanel:(id)sender
3239 {
3240     _impl->showGuessPanel(sender);
3241 }
3242
3243 - (IBAction)checkSpelling:(id)sender
3244 {
3245     _impl->checkSpelling();
3246 }
3247
3248 - (void)changeSpelling:(id)sender
3249 {
3250     _impl->changeSpelling(sender);
3251 }
3252
3253 - (IBAction)toggleContinuousSpellChecking:(id)sender
3254 {
3255     _impl->toggleContinuousSpellChecking();
3256 }
3257
3258 - (BOOL)isGrammarCheckingEnabled
3259 {
3260     return _impl->isGrammarCheckingEnabled();
3261 }
3262
3263 - (void)setGrammarCheckingEnabled:(BOOL)flag
3264 {
3265     _impl->setGrammarCheckingEnabled(flag);
3266 }
3267
3268 - (IBAction)toggleGrammarChecking:(id)sender
3269 {
3270     _impl->toggleGrammarChecking();
3271 }
3272
3273 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
3274 {
3275     _impl->toggleAutomaticSpellingCorrection();
3276 }
3277
3278 - (void)orderFrontSubstitutionsPanel:(id)sender
3279 {
3280     _impl->orderFrontSubstitutionsPanel(sender);
3281 }
3282
3283 - (IBAction)toggleSmartInsertDelete:(id)sender
3284 {
3285     _impl->toggleSmartInsertDelete();
3286 }
3287
3288 - (BOOL)isAutomaticQuoteSubstitutionEnabled
3289 {
3290     return _impl->isAutomaticQuoteSubstitutionEnabled();
3291 }
3292
3293 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
3294 {
3295     _impl->setAutomaticQuoteSubstitutionEnabled(flag);
3296 }
3297
3298 - (void)toggleAutomaticQuoteSubstitution:(id)sender
3299 {
3300     _impl->toggleAutomaticQuoteSubstitution();
3301 }
3302
3303 - (BOOL)isAutomaticDashSubstitutionEnabled
3304 {
3305     return _impl->isAutomaticDashSubstitutionEnabled();
3306 }
3307
3308 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
3309 {
3310     _impl->setAutomaticDashSubstitutionEnabled(flag);
3311 }
3312
3313 - (void)toggleAutomaticDashSubstitution:(id)sender
3314 {
3315     _impl->toggleAutomaticDashSubstitution();
3316 }
3317
3318 - (BOOL)isAutomaticLinkDetectionEnabled
3319 {
3320     return _impl->isAutomaticLinkDetectionEnabled();
3321 }
3322
3323 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
3324 {
3325     _impl->setAutomaticLinkDetectionEnabled(flag);
3326 }
3327
3328 - (void)toggleAutomaticLinkDetection:(id)sender
3329 {
3330     _impl->toggleAutomaticLinkDetection();
3331 }
3332
3333 - (BOOL)isAutomaticTextReplacementEnabled
3334 {
3335     return _impl->isAutomaticTextReplacementEnabled();
3336 }
3337
3338 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
3339 {
3340     _impl->setAutomaticTextReplacementEnabled(flag);
3341 }
3342
3343 - (void)toggleAutomaticTextReplacement:(id)sender
3344 {
3345     _impl->toggleAutomaticTextReplacement();
3346 }
3347
3348 - (void)uppercaseWord:(id)sender
3349 {
3350     _impl->uppercaseWord();
3351 }
3352
3353 - (void)lowercaseWord:(id)sender
3354 {
3355     _impl->lowercaseWord();
3356 }
3357
3358 - (void)capitalizeWord:(id)sender
3359 {
3360     _impl->capitalizeWord();
3361 }
3362
3363 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
3364 {
3365     return _impl->wantsKeyDownForEvent(event);
3366 }
3367
3368 - (void)scrollWheel:(NSEvent *)event
3369 {
3370     _impl->scrollWheel(event);
3371 }
3372
3373 - (void)swipeWithEvent:(NSEvent *)event
3374 {
3375     _impl->swipeWithEvent(event);
3376 }
3377
3378 - (void)mouseMoved:(NSEvent *)event
3379 {
3380     _impl->mouseMoved(event);
3381 }
3382
3383 - (void)mouseDown:(NSEvent *)event
3384 {
3385     _impl->mouseDown(event);
3386 }
3387
3388 - (void)mouseUp:(NSEvent *)event
3389 {
3390     _impl->mouseUp(event);
3391 }
3392
3393 - (void)mouseDragged:(NSEvent *)event
3394 {
3395     _impl->mouseDragged(event);
3396 }
3397
3398 - (void)mouseEntered:(NSEvent *)event
3399 {
3400     _impl->mouseEntered(event);
3401 }
3402
3403 - (void)mouseExited:(NSEvent *)event
3404 {
3405     _impl->mouseExited(event);
3406 }
3407
3408 - (void)otherMouseDown:(NSEvent *)event
3409 {
3410     _impl->otherMouseDown(event);
3411 }
3412
3413 - (void)otherMouseDragged:(NSEvent *)event
3414 {
3415     _impl->otherMouseDragged(event);
3416 }
3417
3418 - (void)otherMouseUp:(NSEvent *)event
3419 {
3420     _impl->otherMouseUp(event);
3421 }
3422
3423 - (void)rightMouseDown:(NSEvent *)event
3424 {
3425     _impl->rightMouseDown(event);
3426 }
3427
3428 - (void)rightMouseDragged:(NSEvent *)event
3429 {
3430     _impl->rightMouseDragged(event);
3431 }
3432
3433 - (void)rightMouseUp:(NSEvent *)event
3434 {
3435     _impl->rightMouseUp(event);
3436 }
3437
3438 - (void)pressureChangeWithEvent:(NSEvent *)event
3439 {
3440     _impl->pressureChangeWithEvent(event);
3441 }
3442
3443 - (BOOL)acceptsFirstMouse:(NSEvent *)event
3444 {
3445     return _impl->acceptsFirstMouse(event);
3446 }
3447
3448 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
3449 {
3450     return _impl->shouldDelayWindowOrderingForEvent(event);
3451 }
3452
3453 - (void)doCommandBySelector:(SEL)selector
3454 {
3455     _impl->doCommandBySelector(selector);
3456 }
3457
3458 - (void)insertText:(id)string
3459 {
3460     _impl->insertText(string);
3461 }
3462
3463 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
3464 {
3465     _impl->insertText(string, replacementRange);
3466 }
3467
3468 - (NSTextInputContext *)inputContext
3469 {
3470     if (!_impl)
3471         return nil;
3472     return _impl->inputContext();
3473 }
3474
3475 - (BOOL)performKeyEquivalent:(NSEvent *)event
3476 {
3477     return _impl->performKeyEquivalent(event);
3478 }
3479
3480 - (void)keyUp:(NSEvent *)theEvent
3481 {
3482     _impl->keyUp(theEvent);
3483 }
3484
3485 - (void)keyDown:(NSEvent *)theEvent
3486 {
3487     _impl->keyDown(theEvent);
3488 }
3489
3490 - (void)flagsChanged:(NSEvent *)theEvent
3491 {
3492     _impl->flagsChanged(theEvent);
3493 }
3494
3495 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange