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