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