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