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