[macOS] [WK2] Support changing foreground colors via color panel
[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 - (WKBrowsingContextController *)browsingContextController
1342 {
1343     return [_contentView browsingContextController];
1344 }
1345
1346 - (BOOL)becomeFirstResponder
1347 {
1348     UIView *currentContentView = self._currentContentView;
1349     if (currentContentView == _contentView && [_contentView superview])
1350         return [_contentView becomeFirstResponderForWebView] || [super becomeFirstResponder];
1351
1352     return [currentContentView becomeFirstResponder] || [super becomeFirstResponder];
1353 }
1354
1355 - (BOOL)canBecomeFirstResponder
1356 {
1357     if (self._currentContentView == _contentView)
1358         return [_contentView canBecomeFirstResponderForWebView];
1359
1360     return YES;
1361 }
1362
1363 - (BOOL)resignFirstResponder
1364 {
1365     if ([_contentView isFirstResponder])
1366         return [_contentView resignFirstResponderForWebView];
1367
1368     return [super resignFirstResponder];
1369 }
1370
1371 #define FORWARD_ACTION_TO_WKCONTENTVIEW(_action) \
1372     - (void)_action:(id)sender \
1373     { \
1374         if (self.usesStandardContentView) \
1375             [_contentView _action ## ForWebView:sender]; \
1376     }
1377
1378 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_ACTION_TO_WKCONTENTVIEW)
1379
1380 #undef FORWARD_ACTION_TO_WKCONTENTVIEW
1381
1382 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
1383 {
1384     #define FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW(_action) \
1385         if (action == @selector(_action:)) \
1386             return self.usesStandardContentView && [_contentView canPerformActionForWebView:action withSender:sender];
1387
1388     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW)
1389
1390     #undef FORWARD_CANPERFORMACTION_TO_WKCONTENTVIEW
1391
1392     return [super canPerformAction:action withSender:sender];
1393 }
1394
1395 - (id)targetForAction:(SEL)action withSender:(id)sender
1396 {
1397     #define FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW(_action) \
1398         if (action == @selector(_action:) && self.usesStandardContentView) \
1399             return [_contentView targetForActionForWebView:action withSender:sender];
1400
1401     FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW)
1402
1403     #undef FORWARD_TARGETFORACTION_TO_WKCONTENTVIEW
1404
1405     return [super targetForAction:action withSender:sender];
1406 }
1407
1408 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
1409 {
1410     return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
1411 }
1412
1413 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
1414 {
1415     return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
1416         && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
1417 }
1418
1419 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
1420 {
1421     float deviceScaleFactor = page.deviceScaleFactor();
1422     return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
1423 }
1424
1425 - (UIView *)_currentContentView
1426 {
1427     return _customContentView ? [_customContentView web_contentView] : _contentView.get();
1428 }
1429
1430 - (WKWebViewContentProviderRegistry *)_contentProviderRegistry
1431 {
1432     return [_configuration _contentProviderRegistry];
1433 }
1434
1435 - (WKSelectionGranularity)_selectionGranularity
1436 {
1437     return [_configuration selectionGranularity];
1438 }
1439
1440 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
1441 {
1442     if (pageHasCustomContentView) {
1443         [_customContentView removeFromSuperview];
1444         [_customContentFixedOverlayView removeFromSuperview];
1445
1446         Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
1447         ASSERT(representationClass);
1448         _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self mimeType:mimeType]);
1449         _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
1450         [_customContentFixedOverlayView layer].name = @"CustomContentFixedOverlay";
1451         [_customContentFixedOverlayView setUserInteractionEnabled:NO];
1452
1453         [[_contentView unscaledView] removeFromSuperview];
1454         [_contentView removeFromSuperview];
1455         [_scrollView addSubview:_customContentView.get()];
1456         [self addSubview:_customContentFixedOverlayView.get()];
1457
1458         [_customContentView web_setMinimumSize:self.bounds.size];
1459         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
1460
1461         _scrollViewBackgroundColor = WebCore::Color();
1462         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1463
1464         [self _setAvoidsUnsafeArea:NO];
1465     } else if (_customContentView) {
1466         [_customContentView removeFromSuperview];
1467         _customContentView = nullptr;
1468
1469         [_customContentFixedOverlayView removeFromSuperview];
1470         _customContentFixedOverlayView = nullptr;
1471
1472         [_scrollView addSubview:_contentView.get()];
1473         [_scrollView addSubview:[_contentView unscaledView]];
1474         [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
1475
1476         [_customContentFixedOverlayView setFrame:self.bounds];
1477         [self addSubview:_customContentFixedOverlayView.get()];
1478     }
1479
1480     if (self.isFirstResponder) {
1481         UIView *currentContentView = self._currentContentView;
1482         if (currentContentView == _contentView ? [_contentView canBecomeFirstResponderForWebView] : currentContentView.canBecomeFirstResponder)
1483             [currentContentView becomeFirstResponder];
1484     }
1485 }
1486
1487 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
1488 {
1489     ASSERT(_customContentView);
1490     [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
1491
1492     // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
1493     // because there's no guarantee that all custom content providers will lay out synchronously.
1494     _page->didLayoutForCustomContentProvider();
1495 }
1496
1497 - (void)_willInvokeUIScrollViewDelegateCallback
1498 {
1499     _delayUpdateVisibleContentRects = YES;
1500 }
1501
1502 - (void)_didInvokeUIScrollViewDelegateCallback
1503 {
1504     _delayUpdateVisibleContentRects = NO;
1505     if (_hadDelayedUpdateVisibleContentRects) {
1506         _hadDelayedUpdateVisibleContentRects = NO;
1507         [self _scheduleVisibleContentRectUpdate];
1508     }
1509 }
1510
1511 static CGFloat contentZoomScale(WKWebView *webView)
1512 {
1513     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
1514     ASSERT(scale == [webView->_scrollView zoomScale]);
1515     return scale;
1516 }
1517
1518 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
1519 {
1520     if (webView->_customContentView)
1521         return [webView->_customContentView backgroundColor].CGColor;
1522
1523     if (webView->_gestureController) {
1524         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
1525         if (color.isValid())
1526             return color;
1527     }
1528
1529     return webView->_page->pageExtendedBackgroundColor();
1530 }
1531
1532 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
1533 {
1534     if (!webView.opaque)
1535         return WebCore::Color::transparent;
1536
1537     WebCore::Color color = baseScrollViewBackgroundColor(webView);
1538
1539     if (!color.isValid())
1540         color = WebCore::Color::white;
1541
1542     CGFloat zoomScale = contentZoomScale(webView);
1543     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
1544     if (zoomScale < minimumZoomScale) {
1545         CGFloat slope = 12;
1546         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
1547         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
1548     }
1549
1550     return color;
1551 }
1552
1553 - (void)_updateScrollViewBackground
1554 {
1555     WebCore::Color color = scrollViewBackgroundColor(self);
1556
1557     if (_scrollViewBackgroundColor == color)
1558         return;
1559
1560     _scrollViewBackgroundColor = color;
1561
1562     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color)]);
1563     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
1564
1565     // Update the indicator style based on the lightness/darkness of the background color.
1566     double hue, saturation, lightness;
1567     color.getHSL(hue, saturation, lightness);
1568     if (lightness <= .5 && color.isVisible())
1569         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
1570     else
1571         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
1572 }
1573
1574 - (void)_videoControlsManagerDidChange
1575 {
1576 #if ENABLE(FULLSCREEN_API)
1577     if (_fullScreenWindowController)
1578         [_fullScreenWindowController videoControlsManagerDidChange];
1579 #endif
1580 }
1581
1582 - (CGPoint)_initialContentOffsetForScrollView
1583 {
1584     auto combinedUnobscuredAndScrollViewInset = [self _computedContentInset];
1585     return CGPointMake(-combinedUnobscuredAndScrollViewInset.left, -combinedUnobscuredAndScrollViewInset.top);
1586 }
1587
1588 - (CGPoint)_contentOffsetAdjustedForObscuredInset:(CGPoint)point
1589 {
1590     CGPoint result = point;
1591     UIEdgeInsets contentInset = [self _computedObscuredInset];
1592
1593     result.x -= contentInset.left;
1594     result.y -= contentInset.top;
1595
1596     return result;
1597 }
1598
1599 - (UIRectEdge)_effectiveObscuredInsetEdgesAffectedBySafeArea
1600 {
1601     if (![self usesStandardContentView])
1602         return UIRectEdgeAll;
1603     return _obscuredInsetEdgesAffectedBySafeArea;
1604 }
1605
1606 - (UIEdgeInsets)_computedObscuredInset
1607 {
1608     if (!linkedOnOrAfter(WebKit::SDKVersion::FirstWhereScrollViewContentInsetsAreNotObscuringInsets)) {
1609         // For binary compability with third party apps, treat scroll view content insets as obscuring insets when the app is compiled
1610         // against a WebKit version without the fix in r229641.
1611         return [self _computedContentInset];
1612     }
1613
1614     if (_haveSetObscuredInsets)
1615         return _obscuredInsets;
1616
1617 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1618     if (self._safeAreaShouldAffectObscuredInsets)
1619         return UIEdgeInsetsAdd(UIEdgeInsetsZero, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1620 #endif
1621
1622     return UIEdgeInsetsZero;
1623 }
1624
1625 - (UIEdgeInsets)_computedContentInset
1626 {
1627     if (_haveSetObscuredInsets)
1628         return _obscuredInsets;
1629
1630     UIEdgeInsets insets = [_scrollView contentInset];
1631
1632 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1633     if (self._safeAreaShouldAffectObscuredInsets)
1634         insets = UIEdgeInsetsAdd(insets, self._scrollViewSystemContentInset, self._effectiveObscuredInsetEdgesAffectedBySafeArea);
1635 #endif
1636
1637     return insets;
1638 }
1639
1640 - (UIEdgeInsets)_computedUnobscuredSafeAreaInset
1641 {
1642     if (_haveSetUnobscuredSafeAreaInsets)
1643         return _unobscuredSafeAreaInsets;
1644
1645 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1646     if (!self._safeAreaShouldAffectObscuredInsets)
1647         return self.safeAreaInsets;
1648 #endif
1649
1650     return UIEdgeInsetsZero;
1651 }
1652
1653 - (void)_processDidExit
1654 {
1655     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _processDidExit]", self);
1656     [self _hidePasswordView];
1657     [self _cancelAnimatedResize];
1658     [_contentView setFrame:self.bounds];
1659     [_scrollView setBackgroundColor:[UIColor whiteColor]];
1660     [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1661     [_scrollView setZoomScale:1];
1662
1663     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
1664     _initialScaleFactor = 1;
1665     _hasCommittedLoadForMainFrame = NO;
1666     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1667     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
1668     _waitingForEndAnimatedResize = NO;
1669     _waitingForCommitAfterAnimatedResize = NO;
1670     _animatedResizeOriginalContentWidth = 0;
1671     [_contentView setHidden:NO];
1672     _scrollOffsetToRestore = std::nullopt;
1673     _unobscuredCenterToRestore = std::nullopt;
1674     _scrollViewBackgroundColor = WebCore::Color();
1675     _delayUpdateVisibleContentRects = NO;
1676     _hadDelayedUpdateVisibleContentRects = NO;
1677     _currentlyAdjustingScrollViewInsetsForKeyboard = NO;
1678     _lastSentViewLayoutSize = std::nullopt;
1679     _lastSentMaximumUnobscuredSize = std::nullopt;
1680     _lastSentDeviceOrientation = std::nullopt;
1681
1682     _frozenVisibleContentRect = std::nullopt;
1683     _frozenUnobscuredContentRect = std::nullopt;
1684
1685     _firstPaintAfterCommitLoadTransactionID = 0;
1686     _firstTransactionIDAfterPageRestore = std::nullopt;
1687
1688     _hasScheduledVisibleRectUpdate = NO;
1689     _commitDidRestoreScrollPosition = NO;
1690
1691     _avoidsUnsafeArea = YES;
1692 }
1693
1694 - (void)_didRelaunchProcess
1695 {
1696     RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didRelaunchProcess]", self);
1697     _hasScheduledVisibleRectUpdate = NO;
1698     _visibleContentRectUpdateScheduledFromScrollViewInStableState = YES;
1699 }
1700
1701 - (void)_didCommitLoadForMainFrame
1702 {
1703     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1704
1705     _hasCommittedLoadForMainFrame = YES;
1706     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
1707
1708     [_scrollView _stopScrollingAndZoomingAnimations];
1709 }
1710
1711 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
1712 {
1713 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1714     UIEdgeInsets contentInsets = scrollView.adjustedContentInset;
1715 #else
1716     UIEdgeInsets contentInsets = scrollView.contentInset;
1717 #endif
1718
1719     CGSize contentSize = scrollView.contentSize;
1720     CGSize scrollViewSize = scrollView.bounds.size;
1721
1722     CGPoint minimumContentOffset = CGPointMake(-contentInsets.left, -contentInsets.top);
1723     CGPoint maximumContentOffset = CGPointMake(std::max(minimumContentOffset.x, contentSize.width + contentInsets.right - scrollViewSize.width), std::max(minimumContentOffset.y, contentSize.height + contentInsets.bottom - scrollViewSize.height));
1724
1725     return CGPointMake(std::max(std::min(contentOffset.x, maximumContentOffset.x), minimumContentOffset.x), std::max(std::min(contentOffset.y, maximumContentOffset.y), minimumContentOffset.y));
1726 }
1727
1728 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
1729 {
1730     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
1731 }
1732
1733 - (WebCore::FloatRect)visibleRectInViewCoordinates
1734 {
1735     WebCore::FloatRect bounds = self.bounds;
1736     bounds.moveBy([_scrollView contentOffset]);
1737     WebCore::FloatRect contentViewBounds = [_contentView bounds];
1738     bounds.intersect(contentViewBounds);
1739     return bounds;
1740 }
1741
1742 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
1743 // we need to ignore differences that are within a small rounding error on floats.
1744 static inline bool areEssentiallyEqualAsFloat(float a, float b)
1745 {
1746     return WTF::areEssentiallyEqual(a, b);
1747 }
1748
1749 - (void)_didCommitLayerTreeDuringAnimatedResize:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1750 {
1751     auto updateID = layerTreeTransaction.dynamicViewportSizeUpdateID();
1752     if (updateID && *updateID == _currentDynamicViewportSizeUpdateID) {
1753         double pageScale = layerTreeTransaction.pageScaleFactor();
1754         WebCore::IntPoint scrollPosition = layerTreeTransaction.scrollPosition();
1755
1756         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1757         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1758         double scale = pageScale / currentTargetScale;
1759         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1760
1761         CGPoint newContentOffset = [self _contentOffsetAdjustedForObscuredInset:CGPointMake(scrollPosition.x() * pageScale, scrollPosition.y() * pageScale)];
1762         CGPoint currentContentOffset = [_scrollView contentOffset];
1763
1764         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1765         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1766
1767         [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1768
1769         // If we've already passed endAnimatedResize, immediately complete
1770         // the resize when we have an up-to-date layer tree. Otherwise,
1771         // we will defer completion until endAnimatedResize.
1772         _waitingForCommitAfterAnimatedResize = NO;
1773         if (!_waitingForEndAnimatedResize)
1774             [self _didCompleteAnimatedResize];
1775
1776         return;
1777     }
1778
1779     // If a commit arrives during the live part of a resize but before the
1780     // layer tree takes the current resize into account, it could change the
1781     // WKContentView's size. Update the resizeAnimationView's scale to ensure
1782     // we continue to fill the width of the resize target.
1783
1784     if (_waitingForEndAnimatedResize)
1785         return;
1786
1787     auto newViewLayoutSize = [self activeViewLayoutSize:self.bounds];
1788     CGFloat resizeAnimationViewScale = _animatedResizeOriginalContentWidth / newViewLayoutSize.width();
1789     [[_resizeAnimationView layer] setSublayerTransform:CATransform3DMakeScale(resizeAnimationViewScale, resizeAnimationViewScale, 1)];
1790 }
1791
1792 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1793 {
1794     if (![self usesStandardContentView])
1795         return;
1796
1797     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _didCommitLayerTree:] transactionID " <<  layerTreeTransaction.transactionID() << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
1798
1799     bool needUpdateVisibleContentRects = _page->updateLayoutViewportParameters(layerTreeTransaction);
1800
1801     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing) {
1802         [self _didCommitLayerTreeDuringAnimatedResize:layerTreeTransaction];
1803         return;
1804     }
1805
1806     if (_resizeAnimationView)
1807         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCommitLayerTree:] - dynamicViewportUpdateMode is NotResizing, but still have a live resizeAnimationView (unpaired begin/endAnimatedResize?)", self);
1808
1809     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1810     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1811
1812     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1813     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1814     [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1815     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom] && [_scrollView zoomScale] != layerTreeTransaction.pageScaleFactor()) {
1816         LOG_WITH_STREAM(VisibleRects, stream << " updating scroll view with pageScaleFactor " << layerTreeTransaction.pageScaleFactor());
1817         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1818     }
1819
1820     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1821     _viewportMetaTagWidthWasExplicit = layerTreeTransaction.viewportMetaTagWidthWasExplicit();
1822     _viewportMetaTagCameFromImageDocument = layerTreeTransaction.viewportMetaTagCameFromImageDocument();
1823     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1824     if (_page->inStableState() && layerTreeTransaction.isInStableState() && [_stableStatePresentationUpdateCallbacks count]) {
1825         for (dispatch_block_t action in _stableStatePresentationUpdateCallbacks.get())
1826             action();
1827
1828         [_stableStatePresentationUpdateCallbacks removeAllObjects];
1829         _stableStatePresentationUpdateCallbacks = nil;
1830     }
1831
1832     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1833         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1834
1835     [self _updateScrollViewBackground];
1836     [self _setAvoidsUnsafeArea:layerTreeTransaction.avoidsUnsafeArea()];
1837
1838     if (_gestureController)
1839         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1840
1841     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1842         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1843         [_scrollView setContentOffset:[self _initialContentOffsetForScrollView]];
1844         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1845             _navigationState->didFirstPaint();
1846
1847         needUpdateVisibleContentRects = true;
1848     }
1849
1850     if (_firstTransactionIDAfterPageRestore && layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore.value()) {
1851         if (_scrollOffsetToRestore) {
1852             WebCore::FloatPoint scaledScrollOffset = _scrollOffsetToRestore.value();
1853             _scrollOffsetToRestore = std::nullopt;
1854
1855             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1856                 scaledScrollOffset.scale(_scaleToRestore);
1857                 WebCore::FloatPoint contentOffsetInScrollViewCoordinates = scaledScrollOffset - WebCore::FloatSize(_obscuredInsetsWhenSaved.left(), _obscuredInsetsWhenSaved.top());
1858
1859                 changeContentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1860                 _commitDidRestoreScrollPosition = YES;
1861             }
1862
1863             needUpdateVisibleContentRects = true;
1864         }
1865
1866         if (_unobscuredCenterToRestore) {
1867             WebCore::FloatPoint unobscuredCenterToRestore = _unobscuredCenterToRestore.value();
1868             _unobscuredCenterToRestore = std::nullopt;
1869
1870             if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1871                 CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1872                 WebCore::FloatSize unobscuredContentSizeAtNewScale = WebCore::FloatSize(unobscuredRect.size) / _scaleToRestore;
1873                 WebCore::FloatPoint topLeftInDocumentCoordinates = unobscuredCenterToRestore - unobscuredContentSizeAtNewScale / 2;
1874
1875                 topLeftInDocumentCoordinates.scale(_scaleToRestore);
1876                 topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1877
1878                 changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1879             }
1880
1881             needUpdateVisibleContentRects = true;
1882         }
1883
1884         if (_gestureController)
1885             _gestureController->didRestoreScrollPosition();
1886
1887         _firstTransactionIDAfterPageRestore = std::nullopt;
1888     }
1889
1890     if (needUpdateVisibleContentRects)
1891         [self _scheduleVisibleContentRectUpdate];
1892
1893     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1894         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1895 }
1896
1897 - (void)_layerTreeCommitComplete
1898 {
1899     _commitDidRestoreScrollPosition = NO;
1900 }
1901
1902 - (void)_couldNotRestorePageState
1903 {
1904     // The gestureController may be waiting for the scroll position to be restored
1905     // in order to remove the swipe snapshot. Since the scroll position could not be
1906     // restored, tell the gestureController it was restored so that it no longer waits
1907     // for it.
1908     if (_gestureController)
1909         _gestureController->didRestoreScrollPosition();
1910 }
1911
1912 - (void)_restorePageScrollPosition:(std::optional<WebCore::FloatPoint>)scrollPosition scrollOrigin:(WebCore::FloatPoint)scrollOrigin previousObscuredInset:(WebCore::FloatBoxExtent)obscuredInsets scale:(double)scale
1913 {
1914     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
1915         return;
1916
1917     if (![self usesStandardContentView])
1918         return;
1919
1920     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1921     if (scrollPosition)
1922         _scrollOffsetToRestore = WebCore::ScrollableArea::scrollOffsetFromPosition(WebCore::FloatPoint(scrollPosition.value()), WebCore::toFloatSize(scrollOrigin));
1923     else
1924         _scrollOffsetToRestore = std::nullopt;
1925
1926     _obscuredInsetsWhenSaved = obscuredInsets;
1927     _scaleToRestore = scale;
1928 }
1929
1930 - (void)_restorePageStateToUnobscuredCenter:(std::optional<WebCore::FloatPoint>)center scale:(double)scale
1931 {
1932     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
1933         return;
1934
1935     if (![self usesStandardContentView])
1936         return;
1937
1938     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1939     _unobscuredCenterToRestore = center.value();
1940
1941     _scaleToRestore = scale;
1942 }
1943
1944 - (RefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
1945 {
1946 #if HAVE(CORE_ANIMATION_RENDER_SERVER)
1947     float deviceScale = WebCore::screenScaleFactor();
1948     WebCore::FloatSize snapshotSize(self.bounds.size);
1949     snapshotSize.scale(deviceScale);
1950
1951     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
1952
1953 #if HAVE(IOSURFACE)
1954     WebCore::IOSurface::Format snapshotFormat = WebCore::screenSupportsExtendedColor() ? WebCore::IOSurface::Format::RGB10 : WebCore::IOSurface::Format::RGBA;
1955     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::sRGBColorSpaceRef(), snapshotFormat);
1956     if (!surface)
1957         return nullptr;
1958     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
1959
1960 #if HAVE(IOSURFACE_ACCELERATOR)
1961     WebCore::IOSurface::Format compressedFormat = WebCore::IOSurface::Format::YUV422;
1962     if (WebCore::IOSurface::allowConversionFromFormatToFormat(snapshotFormat, compressedFormat)) {
1963         RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
1964         WebCore::IOSurface::convertToFormat(WTFMove(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
1965             if (convertedSurface)
1966                 viewSnapshot->setSurface(WTFMove(convertedSurface));
1967         });
1968
1969         return viewSnapshot;
1970     }
1971 #endif // HAVE(IOSURFACE_ACCELERATOR)
1972
1973     return WebKit::ViewSnapshot::create(WTFMove(surface));
1974 #else // HAVE(IOSURFACE)
1975     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
1976
1977     if (!slotID)
1978         return nullptr;
1979
1980     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
1981     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
1982     return WebKit::ViewSnapshot::create(slotID, imageSize, (imageSize.area() * 4).unsafeGet());
1983 #endif // HAVE(IOSURFACE)
1984 #else // HAVE(CORE_ANIMATION_RENDER_SERVER)
1985     return nullptr;
1986 #endif
1987 }
1988
1989 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
1990 {
1991     CFTimeInterval duration = 0;
1992     CGFloat zoomScale = contentZoomScale(self);
1993
1994     if (animated) {
1995         const double maximumZoomDuration = 0.4;
1996         const double minimumZoomDuration = 0.1;
1997         const double zoomDurationFactor = 0.3;
1998
1999         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
2000     }
2001
2002     if (scale != zoomScale)
2003         _page->willStartUserTriggeredZooming();
2004
2005     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToPoint:" << point << " scale: " << scale << " duration:" << duration);
2006
2007     [_scrollView _zoomToCenter:point scale:scale duration:duration];
2008 }
2009
2010 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2011 {
2012     // FIXME: Some of this could be shared with _scrollToRect.
2013     const double visibleRectScaleChange = contentZoomScale(self) / scale;
2014     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
2015     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
2016
2017     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
2018     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
2019
2020     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
2021
2022     // Center to the target rect.
2023     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
2024
2025     // Center to the tap point instead in case the target rect won't fit in a direction.
2026     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
2027         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
2028     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
2029         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
2030
2031     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
2032     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
2033     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
2034     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
2035
2036     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
2037 }
2038
2039 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
2040 {
2041     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
2042     return contentOffset.constrainedBetween(WebCore::FloatPoint(), WebCore::FloatPoint(maximumContentOffset));
2043 }
2044
2045 - (void)_scrollToContentScrollPosition:(WebCore::FloatPoint)scrollPosition scrollOrigin:(WebCore::IntPoint)scrollOrigin
2046 {
2047     if (_commitDidRestoreScrollPosition || _dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing)
2048         return;
2049
2050     WebCore::FloatPoint contentOffset = WebCore::ScrollableArea::scrollOffsetFromPosition(scrollPosition, toFloatSize(scrollOrigin));
2051
2052     WebCore::FloatPoint scaledOffset = contentOffset;
2053     CGFloat zoomScale = contentZoomScale(self);
2054     scaledOffset.scale(zoomScale);
2055
2056     CGPoint contentOffsetInScrollViewCoordinates = [self _contentOffsetAdjustedForObscuredInset:scaledOffset];
2057     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
2058
2059     [_scrollView _stopScrollingAndZoomingAnimations];
2060
2061     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
2062         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
2063     else {
2064         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
2065         // The WebProcess would keep the invalid contentOffset as its scroll position.
2066         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
2067         _page->resendLastVisibleContentRects();
2068     }
2069 }
2070
2071 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
2072 {
2073     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
2074     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
2075     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
2076
2077     // Center the target rect in the scroll view.
2078     // If the target doesn't fit in the scroll view, center on the gesture location instead.
2079     WebCore::FloatPoint newUnobscuredContentOffset;
2080     if (targetRect.width() <= unobscuredContentRect.width())
2081         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
2082     else
2083         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2084     if (targetRect.height() <= unobscuredContentRect.height())
2085         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
2086     else
2087         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2088     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2089
2090     if (unobscuredContentOffset == newUnobscuredContentOffset) {
2091         if (targetRect.width() > unobscuredContentRect.width())
2092             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
2093         if (targetRect.height() > unobscuredContentRect.height())
2094             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
2095         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
2096     }
2097
2098     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
2099     scrollViewOffsetDelta.scale(contentZoomScale(self));
2100
2101     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
2102     if (scrollDistance < minimumScrollDistance)
2103         return false;
2104
2105     [_contentView willStartZoomOrScroll];
2106
2107     LOG_WITH_STREAM(VisibleRects, stream << "_scrollToRect: scrolling to " << [_scrollView contentOffset] + scrollViewOffsetDelta);
2108
2109     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
2110     return true;
2111 }
2112
2113 - (void)_scrollByContentOffset:(WebCore::FloatPoint)contentOffsetDelta animated:(BOOL)animated
2114 {
2115     WebCore::FloatPoint scaledOffsetDelta = contentOffsetDelta;
2116     CGFloat zoomScale = contentZoomScale(self);
2117     scaledOffsetDelta.scale(zoomScale);
2118
2119     CGPoint currentOffset = [_scrollView _isAnimatingScroll] ? [_scrollView _animatedTargetOffset] : [_scrollView contentOffset];
2120     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), currentOffset + scaledOffsetDelta);
2121
2122     if (CGPointEqualToPoint(boundedOffset, currentOffset))
2123         return;
2124     [_contentView willStartZoomOrScroll];
2125
2126     LOG_WITH_STREAM(VisibleRects, stream << "_scrollByContentOffset: scrolling to " << WebCore::FloatPoint(boundedOffset));
2127
2128     [_scrollView setContentOffset:boundedOffset animated:animated];
2129 }
2130
2131 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2132 {
2133     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
2134 }
2135
2136 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
2137 {
2138     ASSERT(_initialScaleFactor > 0);
2139     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
2140 }
2141
2142 // focusedElementRect and selectionRect are both in document coordinates.
2143 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates insideFixed:(BOOL)insideFixed
2144     fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
2145 {
2146     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect:" << focusedElementRectInDocumentCoordinates << " selectionRect:" << selectionRectInDocumentCoordinates);
2147     UNUSED_PARAM(insideFixed);
2148
2149     const double minimumHeightToShowContentAboveKeyboard = 106;
2150     const CFTimeInterval formControlZoomAnimationDuration = 0.25;
2151     const double caretOffsetFromWindowEdge = 20;
2152
2153     UIWindow *window = [_scrollView window];
2154
2155     // Find the portion of the view that is visible on the screen.
2156     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
2157     UIView *fullScreenView = topViewController.view;
2158     if (!fullScreenView)
2159         fullScreenView = window;
2160
2161     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
2162     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
2163     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
2164     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
2165     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
2166
2167     CGFloat visibleOffsetFromTop = 0;
2168     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
2169         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2170         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
2171
2172         if (heightVisibleAboveFormAssistant >= minimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
2173             visibleSize.height = heightVisibleAboveFormAssistant;
2174         else {
2175             visibleSize.height = heightVisibleBelowFormAssistant;
2176             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
2177         }
2178     }
2179
2180     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
2181     double currentScale = contentZoomScale(self);
2182     double scale = currentScale;
2183     if (allowScaling) {
2184 #if PLATFORM(WATCHOS)
2185         const CGFloat minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 10;
2186         const CGFloat maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates = 35;
2187
2188         CGRect minimumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -minimumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2189         CGRect maximumTargetRectInDocumentCoordinates = UIRectInsetEdges(focusedElementRectInDocumentCoordinates, UIRectEdgeAll, -maximumMarginForZoomingToEntireFocusRectInWebViewCoordinates / currentScale);
2190
2191         double clampedMaximumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(minimumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(minimumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2192         double clampedMinimumTargetScale = clampTo<double>(std::min(visibleSize.width / CGRectGetWidth(maximumTargetRectInDocumentCoordinates), visibleSize.height / CGRectGetHeight(maximumTargetRectInDocumentCoordinates)), minimumScale, maximumScale);
2193         scale = clampTo<double>(currentScale, clampedMinimumTargetScale, clampedMaximumTargetScale);
2194 #else
2195         const double webViewStandardFontSize = 16;
2196         scale = clampTo<double>(webViewStandardFontSize / fontSize, minimumScale, maximumScale);
2197 #endif
2198     }
2199
2200     CGFloat documentWidth = [_contentView bounds].size.width;
2201     scale = CGRound(documentWidth * scale) / documentWidth;
2202
2203     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
2204     focusedElementRectInNewScale.scale(scale);
2205     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
2206
2207     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
2208     if (!forceScroll) {
2209         CGRect currentlyVisibleRegionInWebViewCoordinates;
2210         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
2211         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
2212         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
2213
2214         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
2215         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
2216             return;
2217
2218         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
2219         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
2220             return;
2221     }
2222
2223     // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
2224     // can get based on the visible area after zooming (workingFrame).  The spacing in either dimension is half the
2225     // difference between the size of the DOM node and the size of the visible frame.
2226     CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
2227     CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
2228
2229     CGPoint topLeft;
2230     topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
2231     topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
2232
2233     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
2234     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
2235     if (selectionRectIsNotNull) {
2236         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
2237         selectionRectInNewScale.scale(scale);
2238         selectionRectInNewScale.moveBy([_contentView frame].origin);
2239         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.width;
2240         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + caretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
2241     }
2242
2243     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
2244     documentBoundsInNewScale.scale(scale);
2245     documentBoundsInNewScale.moveBy([_contentView frame].origin);
2246
2247     // Constrain the left edge in document coordinates so that:
2248     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2249     //  - it isn't so great that the document's right edge is less than the right edge of the screen
2250     if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
2251         topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
2252     else {
2253         CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
2254         if (topLeft.x > maximumAllowableHorizontalOffset)
2255             topLeft.x = maximumAllowableHorizontalOffset;
2256     }
2257
2258     // Constrain the top edge in document coordinates so that:
2259     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
2260     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
2261     if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
2262         topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
2263     else {
2264         CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
2265         if (topLeft.y > maximumAllowableVerticalOffset)
2266             topLeft.y = maximumAllowableVerticalOffset;
2267     }
2268
2269     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
2270
2271     if (scale != currentScale)
2272         _page->willStartUserTriggeredZooming();
2273
2274     LOG_WITH_STREAM(VisibleRects, stream << "_zoomToFocusRect: zooming to " << newCenter << " scale:" << scale);
2275
2276     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
2277     newCenter.scale(1 / scale);
2278     [_scrollView _zoomToCenter:newCenter scale:scale duration:formControlZoomAnimationDuration force:YES];
2279 }
2280
2281 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
2282 {
2283     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
2284     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
2285     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
2286
2287     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
2288     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
2289
2290     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
2291 }
2292
2293 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
2294 {
2295     const float maximumScaleFactorDeltaForPanScroll = 0.02;
2296
2297     double currentScale = contentZoomScale(self);
2298     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
2299
2300     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
2301         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
2302             return true;
2303     } else if (targetScale != currentScale) {
2304         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
2305         return true;
2306     }
2307
2308     return false;
2309 }
2310
2311 - (void)didMoveToWindow
2312 {
2313     _page->activityStateDidChange(WebCore::ActivityState::allFlags());
2314 }
2315
2316 - (void)setOpaque:(BOOL)opaque
2317 {
2318     BOOL oldOpaque = self.opaque;
2319
2320     [super setOpaque:opaque];
2321     [_contentView setOpaque:opaque];
2322
2323     if (oldOpaque == opaque)
2324         return;
2325
2326     if (!_page)
2327         return;
2328
2329     _page->setDrawsBackground(opaque);
2330     [self _updateScrollViewBackground];
2331 }
2332
2333 - (void)setBackgroundColor:(UIColor *)backgroundColor
2334 {
2335     [super setBackgroundColor:backgroundColor];
2336     [_contentView setBackgroundColor:backgroundColor];
2337 }
2338
2339 - (BOOL)_allowsDoubleTapGestures
2340 {
2341     if (_fastClickingIsDisabled)
2342         return YES;
2343
2344     // If the page is not user scalable, we don't allow double tap gestures.
2345     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
2346         return NO;
2347
2348     // If the viewport width was not explicit, we allow double tap gestures.
2349     if (!_viewportMetaTagWidthWasExplicit || _viewportMetaTagCameFromImageDocument)
2350         return YES;
2351
2352     // If the page set a viewport width that wasn't the device width, then it was
2353     // scaled and thus will probably need to zoom.
2354     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
2355         return YES;
2356
2357     // At this point, we have a page that asked for width = device-width. However,
2358     // if the content's width and height were large, we might have had to shrink it.
2359     // Since we'll enable double tap zoom whenever we're not at the actual
2360     // initial scale, this simply becomes a test of the current scale against 1.
2361     return !areEssentiallyEqualAsFloat(contentZoomScale(self), 1);
2362 }
2363
2364 #pragma mark - UIScrollViewDelegate
2365
2366 - (BOOL)usesStandardContentView
2367 {
2368     return !_customContentView && !_passwordView;
2369 }
2370
2371 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
2372 {
2373     return roundScrollViewContentSize(*_page, proposedSize);
2374 }
2375
2376 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
2377 {
2378     ASSERT(_scrollView == scrollView);
2379     return self._currentContentView;
2380 }
2381
2382 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
2383 {
2384     if (![self usesStandardContentView]) {
2385         if ([_customContentView respondsToSelector:@selector(web_scrollViewWillBeginZooming:withView:)])
2386             [_customContentView web_scrollViewWillBeginZooming:scrollView withView:view];
2387         return;
2388     }
2389
2390     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
2391         _page->willStartUserTriggeredZooming();
2392         [_contentView scrollViewWillStartPanOrPinchGesture];
2393     }
2394     [_contentView willStartZoomOrScroll];
2395 }
2396
2397 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
2398 {
2399     if (![self usesStandardContentView])
2400         return;
2401
2402     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
2403         [_contentView scrollViewWillStartPanOrPinchGesture];
2404
2405     [_contentView willStartZoomOrScroll];
2406 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2407     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
2408     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2409     ASSERT(scrollView == _scrollView.get());
2410     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : UIScrollViewDecelerationRateNormal;
2411     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
2412     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
2413 #endif
2414 }
2415
2416 - (void)_didFinishScrolling
2417 {
2418     if (![self usesStandardContentView])
2419         return;
2420
2421     [self _scheduleVisibleContentRectUpdate];
2422     [_contentView didFinishScrolling];
2423 }
2424
2425 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
2426 {
2427     // Work around <rdar://problem/16374753> by avoiding deceleration while
2428     // zooming. We'll animate to the right place once the zoom finishes.
2429     if ([scrollView isZooming])
2430         *targetContentOffset = [scrollView contentOffset];
2431 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2432     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
2433         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
2434         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
2435
2436         UIEdgeInsets obscuredInset;
2437
2438         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
2439         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
2440             obscuredInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
2441         else
2442             obscuredInset = [self _computedObscuredInset];
2443
2444         CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInset);
2445
2446         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
2447     }
2448 #endif
2449 }
2450
2451 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
2452 {
2453     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
2454     if (!decelerate)
2455         [self _didFinishScrolling];
2456 }
2457
2458 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
2459 {
2460     [self _didFinishScrolling];
2461 }
2462
2463 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
2464 {
2465     [self _didFinishScrolling];
2466 }
2467
2468 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
2469 {
2470     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidScroll:)])
2471         [_customContentView web_scrollViewDidScroll:(UIScrollView *)scrollView];
2472
2473     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2474
2475     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2476         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
2477 }
2478
2479 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
2480 {
2481     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidZoom:)])
2482         [_customContentView web_scrollViewDidZoom:scrollView];
2483
2484     [self _updateScrollViewBackground];
2485     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2486 }
2487
2488 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
2489 {
2490     if (![self usesStandardContentView] && [_customContentView respondsToSelector:@selector(web_scrollViewDidEndZooming:withView:atScale:)])
2491         [_customContentView web_scrollViewDidEndZooming:scrollView withView:view atScale:scale];
2492
2493     ASSERT(scrollView == _scrollView);
2494     // FIXME: remove when rdar://problem/36065495 is fixed.
2495     // When rotating with two fingers down, UIScrollView can set a bogus content view position.
2496     // "Center" is top left because we set the anchorPoint to 0,0.
2497     [_contentView setCenter:self.bounds.origin];
2498
2499     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2500     [_contentView didZoomToScale:scale];
2501 }
2502
2503 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
2504 {
2505     [self _didFinishScrolling];
2506 }
2507
2508 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
2509 {
2510     if (![self usesStandardContentView])
2511         return;
2512
2513     [_contentView didInterruptScrolling];
2514     [self _scheduleVisibleContentRectUpdateAfterScrollInView:scrollView];
2515 }
2516
2517 - (UIView *)_enclosingViewForExposedRectComputation
2518 {
2519     return [self _scroller];
2520 }
2521
2522 - (CGRect)_visibleRectInEnclosingView:(UIView *)enclosingView
2523 {
2524     if (!enclosingView)
2525         return self.bounds;
2526
2527     CGRect exposedRect = [enclosingView convertRect:enclosingView.bounds toView:self];
2528     return CGRectIntersectsRect(exposedRect, self.bounds) ? CGRectIntersection(exposedRect, self.bounds) : CGRectZero;
2529 }
2530
2531 - (CGRect)_visibleContentRect
2532 {
2533     if (_frozenVisibleContentRect)
2534         return _frozenVisibleContentRect.value();
2535
2536     CGRect visibleRectInContentCoordinates = [self convertRect:self.bounds toView:_contentView.get()];
2537
2538     if (UIView *enclosingView = [self _enclosingViewForExposedRectComputation]) {
2539         CGRect viewVisibleRect = [self _visibleRectInEnclosingView:enclosingView];
2540         CGRect viewVisibleContentRect = [self convertRect:viewVisibleRect toView:_contentView.get()];
2541         visibleRectInContentCoordinates = CGRectIntersection(visibleRectInContentCoordinates, viewVisibleContentRect);
2542     }
2543
2544     return visibleRectInContentCoordinates;
2545 }
2546
2547 // Called when some ancestor UIScrollView scrolls.
2548 - (void)_didScroll
2549 {
2550     [self _scheduleVisibleContentRectUpdateAfterScrollInView:[self _scroller]];
2551
2552     const NSTimeInterval ScrollingEndedTimerInterval = 0.032;
2553     if (!_enclosingScrollViewScrollTimer) {
2554         _enclosingScrollViewScrollTimer = adoptNS([[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:ScrollingEndedTimerInterval]
2555             interval:0 target:self selector:@selector(_enclosingScrollerScrollingEnded:) userInfo:nil repeats:YES]);
2556         [[NSRunLoop mainRunLoop] addTimer:_enclosingScrollViewScrollTimer.get() forMode:NSDefaultRunLoopMode];
2557     }
2558     _didScrollSinceLastTimerFire = YES;
2559 }
2560
2561 - (void)_enclosingScrollerScrollingEnded:(NSTimer *)timer
2562 {
2563     if (_didScrollSinceLastTimerFire) {
2564         _didScrollSinceLastTimerFire = NO;
2565         return;
2566     }
2567
2568     [self _scheduleVisibleContentRectUpdate];
2569     [_enclosingScrollViewScrollTimer invalidate];
2570     _enclosingScrollViewScrollTimer = nil;
2571 }
2572
2573 - (UIEdgeInsets)_scrollViewSystemContentInset
2574 {
2575     // It's not safe to access the scroll view's safeAreaInsets or _systemContentInset from
2576     // inside our layoutSubviews implementation, because they aren't updated until afterwards.
2577     // Instead, depend on the fact that the UIScrollView and WKWebView are in the same coordinate
2578     // space, and map the WKWebView's own insets into the scroll view manually.
2579     return UIEdgeInsetsAdd([_scrollView _contentScrollInset], self.safeAreaInsets, [_scrollView _edgesApplyingSafeAreaInsetsToContentInset]);
2580 }
2581
2582 - (WebCore::FloatSize)activeViewLayoutSize:(const CGRect&)bounds
2583 {
2584     if (_overridesViewLayoutSize)
2585         return WebCore::FloatSize(_viewLayoutSizeOverride);
2586
2587 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2588     return WebCore::FloatSize(UIEdgeInsetsInsetRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), self._scrollViewSystemContentInset).size);
2589 #else
2590     return WebCore::FloatSize { bounds.size };
2591 #endif
2592 }
2593
2594 - (void)_dispatchSetViewLayoutSize:(WebCore::FloatSize)viewLayoutSize
2595 {
2596     if (_lastSentViewLayoutSize && CGSizeEqualToSize(_lastSentViewLayoutSize.value(), viewLayoutSize))
2597         return;
2598
2599     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _dispatchSetViewLayoutSize:] " << viewLayoutSize << " contentZoomScale " << contentZoomScale(self));
2600     _page->setViewportConfigurationViewLayoutSize(viewLayoutSize);
2601     _lastSentViewLayoutSize = viewLayoutSize;
2602 }
2603
2604 - (void)_dispatchSetMaximumUnobscuredSize:(WebCore::FloatSize)maximumUnobscuredSize
2605 {
2606     if (_lastSentMaximumUnobscuredSize && CGSizeEqualToSize(_lastSentMaximumUnobscuredSize.value(), maximumUnobscuredSize))
2607         return;
2608
2609     _page->setMaximumUnobscuredSize(maximumUnobscuredSize);
2610     _lastSentMaximumUnobscuredSize = maximumUnobscuredSize;
2611 }
2612
2613 - (void)_dispatchSetDeviceOrientation:(int32_t)deviceOrientation
2614 {
2615     if (_lastSentDeviceOrientation && _lastSentDeviceOrientation.value() == deviceOrientation)
2616         return;
2617
2618     _page->setDeviceOrientation(deviceOrientation);
2619     _lastSentDeviceOrientation = deviceOrientation;
2620 }
2621
2622 - (void)_frameOrBoundsChanged
2623 {
2624     CGRect bounds = self.bounds;
2625     [_scrollView setFrame:bounds];
2626
2627     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing) {
2628         if (!_overridesViewLayoutSize)
2629             [self _dispatchSetViewLayoutSize:[self activeViewLayoutSize:self.bounds]];
2630         if (!_overridesMaximumUnobscuredSize)
2631             [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(bounds.size)];
2632
2633         BOOL sizeChanged = NO;
2634         if (auto drawingArea = _page->drawingArea())
2635             sizeChanged = drawingArea->setSize(WebCore::IntSize(bounds.size));
2636
2637         if (sizeChanged & [self usesStandardContentView])
2638             [_contentView setSizeChangedSinceLastVisibleContentRectUpdate:YES];
2639     }
2640
2641     [_customContentView web_setMinimumSize:bounds.size];
2642     [self _scheduleVisibleContentRectUpdate];
2643 }
2644
2645 // 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.
2646 - (CGRect)_contentRectForUserInteraction
2647 {
2648     // FIXME: handle split keyboard.
2649     UIEdgeInsets obscuredInsets = _obscuredInsets;
2650     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
2651     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
2652     return [self convertRect:unobscuredRect toView:self._currentContentView];
2653 }
2654
2655 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
2656 - (BOOL)_scrollViewIsRubberBanding
2657 {
2658     float deviceScaleFactor = _page->deviceScaleFactor();
2659
2660     CGPoint contentOffset = [_scrollView contentOffset];
2661     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2662     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
2663 }
2664
2665 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
2666 - (void)safeAreaInsetsDidChange
2667 {
2668     [super safeAreaInsetsDidChange];
2669
2670     [self _scheduleVisibleContentRectUpdate];
2671 }
2672 #endif
2673
2674 - (void)_scheduleVisibleContentRectUpdate
2675 {
2676     // For visible rect updates not associated with a specific UIScrollView, just consider our own scroller.
2677     [self _scheduleVisibleContentRectUpdateAfterScrollInView:_scrollView.get()];
2678 }
2679
2680 - (BOOL)_scrollViewIsInStableState:(UIScrollView *)scrollView
2681 {
2682     BOOL isStableState = !([scrollView isDragging] || [scrollView isDecelerating] || [scrollView isZooming] || [scrollView _isAnimatingZoom] || [scrollView _isScrollingToTop]);
2683
2684     if (isStableState && scrollView == _scrollView.get())
2685         isStableState = !_isChangingObscuredInsetsInteractively;
2686
2687     if (isStableState && scrollView == _scrollView.get())
2688         isStableState = ![self _scrollViewIsRubberBanding];
2689
2690     if (isStableState)
2691         isStableState = !scrollView._isInterruptingDeceleration;
2692
2693     if (NSNumber *stableOverride = self._stableStateOverride)
2694         isStableState = stableOverride.boolValue;
2695
2696     return isStableState;
2697 }
2698
2699 - (void)_addUpdateVisibleContentRectPreCommitHandler
2700 {
2701     auto retainedSelf = retainPtr(self);
2702     [CATransaction addCommitHandler:[retainedSelf] {
2703         WKWebView *webView = retainedSelf.get();
2704         if (![webView _isValid]) {
2705             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, WKWebView %p is invalid", webView);
2706             return;
2707         }
2708
2709         @try {
2710             [webView _updateVisibleContentRects];
2711         } @catch (NSException *exception) {
2712             RELEASE_LOG_IF(webView._page && webView._page->isAlwaysOnLoggingAllowed(), ViewState, "In CATransaction preCommitHandler, -[WKWebView %p _updateVisibleContentRects] threw an exception", webView);
2713         }
2714         webView->_hasScheduledVisibleRectUpdate = NO;
2715     } forPhase:kCATransactionPhasePreCommit];
2716 }
2717
2718 - (void)_scheduleVisibleContentRectUpdateAfterScrollInView:(UIScrollView *)scrollView
2719 {
2720     _visibleContentRectUpdateScheduledFromScrollViewInStableState = [self _scrollViewIsInStableState:scrollView];
2721
2722     if (_hasScheduledVisibleRectUpdate) {
2723         auto timeNow = MonotonicTime::now();
2724         if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging) {
2725             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",
2726                 self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value(), (timeNow - _timeOfLastVisibleContentRectUpdate).value(), [self _isValid]);
2727         }
2728         return;
2729     }
2730
2731     _hasScheduledVisibleRectUpdate = YES;
2732     _timeOfRequestForVisibleContentRectUpdate = MonotonicTime::now();
2733
2734     CATransactionPhase transactionPhase = [CATransaction currentPhase];
2735     if (transactionPhase == kCATransactionPhaseNull || transactionPhase == kCATransactionPhasePreLayout) {
2736         [self _addUpdateVisibleContentRectPreCommitHandler];
2737         return;
2738     }
2739
2740     dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
2741         WKWebView *webView = retainedSelf.get();
2742         if (![webView _isValid])
2743             return;
2744         [webView _addUpdateVisibleContentRectPreCommitHandler];
2745     });
2746 }
2747
2748 static bool scrollViewCanScroll(UIScrollView *scrollView)
2749 {
2750     if (!scrollView)
2751         return NO;
2752
2753     UIEdgeInsets contentInset = scrollView.contentInset;
2754     CGSize contentSize = scrollView.contentSize;
2755     CGSize boundsSize = scrollView.bounds.size;
2756
2757     return (contentSize.width + contentInset.left + contentInset.right) > boundsSize.width
2758         || (contentSize.height + contentInset.top + contentInset.bottom) > boundsSize.height;
2759 }
2760
2761 - (CGRect)_contentBoundsExtendedForRubberbandingWithScale:(CGFloat)scaleFactor
2762 {
2763     CGPoint contentOffset = [_scrollView contentOffset];
2764     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
2765
2766     CGFloat horiontalRubberbandAmountInContentCoordinates = (contentOffset.x - boundedOffset.x) / scaleFactor;
2767     CGFloat verticalRubberbandAmountInContentCoordinates = (contentOffset.y - boundedOffset.y) / scaleFactor;
2768
2769     CGRect extendedBounds = [_contentView bounds];
2770
2771     if (horiontalRubberbandAmountInContentCoordinates < 0) {
2772         extendedBounds.origin.x += horiontalRubberbandAmountInContentCoordinates;
2773         extendedBounds.size.width -= horiontalRubberbandAmountInContentCoordinates;
2774     } else if (horiontalRubberbandAmountInContentCoordinates > 0)
2775         extendedBounds.size.width += horiontalRubberbandAmountInContentCoordinates;
2776
2777     if (verticalRubberbandAmountInContentCoordinates < 0) {
2778         extendedBounds.origin.y += verticalRubberbandAmountInContentCoordinates;
2779         extendedBounds.size.height -= verticalRubberbandAmountInContentCoordinates;
2780     } else if (verticalRubberbandAmountInContentCoordinates > 0)
2781         extendedBounds.size.height += verticalRubberbandAmountInContentCoordinates;
2782
2783     return extendedBounds;
2784 }
2785
2786 - (void)_updateVisibleContentRects
2787 {
2788     BOOL inStableState = _visibleContentRectUpdateScheduledFromScrollViewInStableState;
2789
2790     if (![self usesStandardContentView]) {
2791         [_passwordView setFrame:self.bounds];
2792         [_customContentView web_computedContentInsetDidChange];
2793         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - usesStandardContentView is NO, bailing", self);
2794         return;
2795     }
2796
2797     if (_delayUpdateVisibleContentRects) {
2798         _hadDelayedUpdateVisibleContentRects = YES;
2799         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] - _delayUpdateVisibleContentRects is YES, bailing", self);
2800         return;
2801     }
2802
2803     if (_dynamicViewportUpdateMode != WebKit::DynamicViewportUpdateMode::NotResizing
2804         || (_needsResetViewStateAfterCommitLoadForMainFrame && ![_contentView sizeChangedSinceLastVisibleContentRectUpdate])
2805         || [_scrollView isZoomBouncing]
2806         || _currentlyAdjustingScrollViewInsetsForKeyboard) {
2807         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)",
2808             self, _dynamicViewportUpdateMode, _needsResetViewStateAfterCommitLoadForMainFrame, [_contentView sizeChangedSinceLastVisibleContentRectUpdate], [_scrollView isZoomBouncing], _currentlyAdjustingScrollViewInsetsForKeyboard);
2809         return;
2810     }
2811
2812     CGRect visibleRectInContentCoordinates = [self _visibleContentRect];
2813
2814     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedObscuredInset];
2815     if (!_haveSetObscuredInsets)
2816         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
2817
2818     CGFloat scaleFactor = contentZoomScale(self);
2819
2820     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, computedContentInsetUnadjustedForKeyboard);
2821     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
2822     unobscuredRectInContentCoordinates = CGRectIntersection(unobscuredRectInContentCoordinates, [self _contentBoundsExtendedForRubberbandingWithScale:scaleFactor]);
2823
2824 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
2825     if (inStableState) {
2826         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
2827         if (coordinator && coordinator->hasActiveSnapPoint()) {
2828             CGPoint currentPoint = [_scrollView contentOffset];
2829             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
2830
2831             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
2832                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
2833                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
2834                     [strongScrollView setContentOffset:activePoint animated:NO];
2835                 });
2836             }
2837         }
2838     }
2839 #endif
2840
2841     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
2842         unobscuredRect:unobscuredRectInContentCoordinates
2843         unobscuredRectInScrollViewCoordinates:unobscuredRect
2844         obscuredInsets:_obscuredInsets
2845         unobscuredSafeAreaInsets:[self _computedUnobscuredSafeAreaInset]
2846         inputViewBounds:_inputViewBounds
2847         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
2848         inStableState:inStableState
2849         isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively
2850         enclosedInScrollableAncestorView:scrollViewCanScroll([self _scroller])];
2851
2852     while (!_visibleContentRectUpdateCallbacks.isEmpty()) {
2853         auto callback = _visibleContentRectUpdateCallbacks.takeLast();
2854         callback();
2855     }
2856     
2857     auto timeNow = MonotonicTime::now();
2858     if ((timeNow - _timeOfRequestForVisibleContentRectUpdate) > delayBeforeNoVisibleContentsRectsLogging)
2859         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _updateVisibleContentRects:] finally ran %.2fs after being scheduled", self, (timeNow - _timeOfRequestForVisibleContentRectUpdate).value());
2860
2861     _timeOfLastVisibleContentRectUpdate = timeNow;
2862 }
2863
2864 - (void)_didStartProvisionalLoadForMainFrame
2865 {
2866     if (_gestureController)
2867         _gestureController->didStartProvisionalLoadForMainFrame();
2868 }
2869
2870 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
2871 {
2872     return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
2873 }
2874
2875 static int32_t activeOrientation(WKWebView *webView)
2876 {
2877     return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
2878 }
2879
2880 - (void)_cancelAnimatedResize
2881 {
2882     LOG_WITH_STREAM(VisibleRects, stream << "-[WKWebView " << _page->pageID() << " _cancelAnimatedResize:] " << " _dynamicViewportUpdateMode " << (int)_dynamicViewportUpdateMode);
2883     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
2884         return;
2885
2886     if (!_customContentView) {
2887         if (_resizeAnimationView) {
2888             NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
2889             [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
2890             [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
2891             [_resizeAnimationView removeFromSuperview];
2892             _resizeAnimationView = nil;
2893         }
2894
2895         [_contentView setHidden:NO];
2896         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2897     }
2898
2899     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
2900     [self _scheduleVisibleContentRectUpdate];
2901 }
2902
2903 - (void)_didCompleteAnimatedResize
2904 {
2905     if (_dynamicViewportUpdateMode == WebKit::DynamicViewportUpdateMode::NotResizing)
2906         return;
2907
2908     [_contentView setHidden:NO];
2909
2910     if (!_resizeAnimationView) {
2911         // Paranoia. If _resizeAnimationView is null we'll end up setting a zero scale on the content view.
2912         RELEASE_LOG_IF_ALLOWED("%p -[WKWebView _didCompleteAnimatedResize:] - _resizeAnimationView is nil", self);
2913         [self _cancelAnimatedResize];
2914         return;
2915     }
2916
2917     NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
2918     [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
2919     [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
2920
2921     CALayer *contentLayer = [_contentView layer];
2922     CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
2923     contentLayer.sublayerTransform = CATransform3DIdentity;
2924
2925     CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
2926     CATransform3D contentLayerTransform = contentLayer.transform;
2927     CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
2928
2929     // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
2930     // an invalid contentOffset. The real content offset is only set below.
2931     // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
2932     // on the zoom layer and then only change the contentOffset.
2933     CGFloat adjustedScale = adjustmentScale * currentScale;
2934     contentLayerTransform.m11 = adjustedScale;
2935     contentLayerTransform.m22 = adjustedScale;
2936     contentLayer.transform = contentLayerTransform;
2937
2938     CGPoint currentScrollOffset = [_scrollView contentOffset];
2939     double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
2940     double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
2941
2942     [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
2943     [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
2944
2945     [_resizeAnimationView removeFromSuperview];
2946     _resizeAnimationView = nil;
2947     _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2948
2949     _dynamicViewportUpdateMode = WebKit::DynamicViewportUpdateMode::NotResizing;
2950     [self _scheduleVisibleContentRectUpdate];
2951
2952     CGRect newBounds = self.bounds;
2953     auto newViewLayoutSize = [self activeViewLayoutSize:newBounds];
2954     auto newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
2955     int32_t newOrientation = activeOrientation(self);
2956
2957     if (!_lastSentViewLayoutSize || newViewLayoutSize != _lastSentViewLayoutSize.value())
2958         [self _dispatchSetViewLayoutSize:newViewLayoutSize];
2959
2960     if (!_lastSentMaximumUnobscuredSize || newMaximumUnobscuredSize != _lastSentMaximumUnobscuredSize.value())
2961         [self _dispatchSetMaximumUnobscuredSize:WebCore::FloatSize(newMaximumUnobscuredSize)];
2962
2963     if (!_lastSentDeviceOrientation || newOrientation != _lastSentDeviceOrientation.value())
2964         [self _dispatchSetDeviceOrientation:newOrientation];
2965
2966     while (!_callbacksDeferredDuringResize.isEmpty())
2967         _callbacksDeferredDuringResize.takeLast()();
2968 }
2969
2970 - (void)_didFinishLoadForMainFrame
2971 {
2972     if (_gestureController)
2973         _gestureController->didFinishLoadForMainFrame();
2974 }
2975
2976 - (void)_didFailLoadForMainFrame
2977 {
2978     if (_gestureController)
2979         _gestureController->didFailLoadForMainFrame();
2980 }
2981
2982 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
2983 {
2984     [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
2985
2986     if (_gestureController)
2987         _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
2988 }
2989
2990 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
2991 {
2992     NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
2993     if (!endFrameValue)
2994         return;
2995
2996     // The keyboard rect is always in screen coordinates. In the view services case the window does not
2997     // have the interface orientation rotation transformation; its host does. So, it makes no sense to
2998     // clip the keyboard rect against its screen.
2999     if ([[self window] _isHostedInAnotherProcess])
3000         _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
3001     else
3002         _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
3003
3004     if (adjustScrollView) {
3005         CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
3006         SetForScope<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
3007         [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
3008         CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
3009         if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
3010             _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
3011     }
3012
3013     [self _scheduleVisibleContentRectUpdate];
3014 }
3015
3016 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
3017 {
3018     if ([_contentView isAssistingNode])
3019         return YES;
3020
3021     NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
3022     return isLocalKeyboard && !isLocalKeyboard.boolValue;
3023 }
3024
3025 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
3026 {
3027     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3028         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3029 }
3030
3031 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
3032 {
3033     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
3034 }
3035
3036 - (void)_keyboardWillShow:(NSNotification *)notification
3037 {
3038     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
3039         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3040
3041     _page->setIsKeyboardAnimatingIn(true);
3042 }
3043
3044 - (void)_keyboardDidShow:(NSNotification *)notification
3045 {
3046     _page->setIsKeyboardAnimatingIn(false);
3047 }
3048
3049 - (void)_keyboardWillHide:(NSNotification *)notification
3050 {
3051     // Ignore keyboard will hide notifications sent during rotation. They're just there for
3052     // backwards compatibility reasons and processing the will hide notification would
3053     // temporarily screw up the unobscured view area.
3054     if ([[UIPeripheralHost sharedInstance] rotationState])
3055         return;
3056
3057     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
3058 }
3059
3060 - (void)_windowDidRotate:(NSNotification *)notification
3061 {
3062     if (!_overridesInterfaceOrientation)
3063         [self _dispatchSetDeviceOrientation:deviceOrientation()];
3064 }
3065
3066 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
3067 {
3068     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
3069 }
3070
3071 - (NSString *)_contentSizeCategory
3072 {
3073     return [[UIApplication sharedApplication] preferredContentSizeCategory];
3074 }
3075
3076 - (void)_accessibilitySettingsDidChange:(NSNotification *)notification
3077 {
3078     _page->accessibilitySettingsDidChange();
3079 }
3080
3081 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3082 {
3083     if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
3084         return;
3085
3086     _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
3087
3088     if (allowsBackForwardNavigationGestures) {
3089         if (!_gestureController) {
3090             _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
3091             _gestureController->installSwipeHandler(self, [self scrollView]);
3092             if (WKWebView *alternateWebView = [_configuration _alternateWebViewForNavigationGestures])
3093                 _gestureController->setAlternateBackForwardListSourcePage(alternateWebView->_page.get());
3094         }
3095     } else
3096         _gestureController = nullptr;
3097
3098     _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
3099 }
3100
3101 - (BOOL)allowsBackForwardNavigationGestures
3102 {
3103     return _allowsBackForwardNavigationGestures;
3104 }
3105
3106 - (BOOL)_isNavigationSwipeGestureRecognizer:(UIGestureRecognizer *)recognizer
3107 {
3108     if (!_gestureController)
3109         return NO;
3110     return _gestureController->isNavigationSwipeGestureRecognizer(recognizer);
3111 }
3112
3113 - (void)_navigationGestureDidBegin
3114 {
3115     // During a back/forward swipe, there's a view interposed between this view and the content view that has
3116     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
3117     // frozen rects during swipes.
3118     CGRect fullViewRect = self.bounds;
3119     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedObscuredInset]);
3120
3121     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
3122     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
3123
3124     LOG_WITH_STREAM(VisibleRects, stream << "_navigationGestureDidBegin: freezing visibleContentRect " << WebCore::FloatRect(_frozenVisibleContentRect.value()) << " UnobscuredContentRect " << WebCore::FloatRect(_frozenUnobscuredContentRect.value()));
3125 }
3126
3127 - (void)_navigationGestureDidEnd
3128 {
3129     _frozenVisibleContentRect = std::nullopt;
3130     _frozenUnobscuredContentRect = std::nullopt;
3131 }
3132
3133 - (void)_showPasswordViewWithDocumentName:(NSString *)documentName passwordHandler:(void (^)(NSString *))passwordHandler
3134 {
3135     ASSERT(!_passwordView);
3136     _passwordView = adoptNS([[WKPasswordView alloc] initWithFrame:self.bounds documentName:documentName]);
3137     [_passwordView setUserDidEnterPassword:passwordHandler];
3138     [_passwordView showInScrollView:_scrollView.get()];
3139     self._currentContentView.hidden = YES;
3140 }
3141
3142 - (void)_hidePasswordView
3143 {
3144     if (!_passwordView)
3145         return;
3146
3147     self._currentContentView.hidden = NO;
3148     [_passwordView hide];
3149     _passwordView = nil;
3150 }
3151
3152 - (WKPasswordView *)_passwordView
3153 {
3154     return _passwordView.get();
3155 }
3156
3157 - (void)_updateScrollViewInsetAdjustmentBehavior
3158 {
3159 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
3160     if (![_scrollView _contentInsetAdjustmentBehaviorWasExternallyOverridden])
3161         [_scrollView _setContentInsetAdjustmentBehaviorInternal:self._safeAreaShouldAffectObscuredInsets ? UIScrollViewContentInsetAdjustmentAlways : UIScrollViewContentInsetAdjustmentNever];
3162 #endif
3163 }
3164
3165 - (void)_setAvoidsUnsafeArea:(BOOL)avoidsUnsafeArea
3166 {
3167     if (_avoidsUnsafeArea == avoidsUnsafeArea)
3168         return;
3169
3170     _avoidsUnsafeArea = avoidsUnsafeArea;
3171
3172     [self _updateScrollViewInsetAdjustmentBehavior];
3173     [self _scheduleVisibleContentRectUpdate];
3174
3175     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
3176     if ([uiDelegate respondsToSelector:@selector(_webView:didChangeSafeAreaShouldAffectObscuredInsets:)])
3177         [uiDelegate _webView:self didChangeSafeAreaShouldAffectObscuredInsets:avoidsUnsafeArea];
3178 }
3179
3180 - (BOOL)_haveSetObscuredInsets
3181 {
3182     return _haveSetObscuredInsets;
3183 }
3184
3185 #endif // PLATFORM(IOS)
3186
3187 #if ENABLE(ACCESSIBILITY_EVENTS)
3188
3189 static void accessibilityEventsEnabledChangedCallback(CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef)
3190 {
3191     ASSERT(observer);
3192     WKWebView *webview = (__bridge WKWebView *)observer;
3193     [webview _updateAccessibilityEventsEnabled];
3194 }
3195
3196 - (void)_updateAccessibilityEventsEnabled
3197 {
3198     if (!isNullFunctionPointer(_AXSWebAccessibilityEventsEnabled))
3199         _page->updateAccessibilityEventsEnabled(_AXSWebAccessibilityEventsEnabled());
3200 }
3201
3202 #endif
3203
3204 #pragma mark OS X-specific methods
3205
3206 #if PLATFORM(MAC)
3207
3208 - (BOOL)acceptsFirstResponder
3209 {
3210     return _impl->acceptsFirstResponder();
3211 }
3212
3213 - (BOOL)becomeFirstResponder
3214 {
3215     return _impl->becomeFirstResponder();
3216 }
3217
3218 - (BOOL)resignFirstResponder
3219 {
3220     return _impl->resignFirstResponder();
3221 }
3222
3223 - (void)viewWillStartLiveResize
3224 {
3225     _impl->viewWillStartLiveResize();
3226 }
3227
3228 - (void)viewDidEndLiveResize
3229 {
3230     _impl->viewDidEndLiveResize();
3231 }
3232
3233 - (BOOL)isFlipped
3234 {
3235     return YES;
3236 }
3237
3238 - (NSSize)intrinsicContentSize
3239 {
3240     return NSSizeFromCGSize(_impl->intrinsicContentSize());
3241 }
3242
3243 - (void)prepareContentInRect:(NSRect)rect
3244 {
3245     _impl->prepareContentInRect(NSRectToCGRect(rect));
3246 }
3247
3248 - (void)setFrameSize:(NSSize)size
3249 {
3250     [super setFrameSize:size];
3251     _impl->setFrameSize(NSSizeToCGSize(size));
3252 }
3253
3254 - (void)renewGState
3255 {
3256     _impl->renewGState();
3257     [super renewGState];
3258 }
3259
3260 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _impl->executeEditCommandForSelector(_cmd); }
3261
3262 WEBCORE_COMMAND(alignCenter)
3263 WEBCORE_COMMAND(alignJustified)
3264 WEBCORE_COMMAND(alignLeft)
3265 WEBCORE_COMMAND(alignRight)
3266 WEBCORE_COMMAND(copy)
3267 WEBCORE_COMMAND(cut)
3268 WEBCORE_COMMAND(delete)
3269 WEBCORE_COMMAND(deleteBackward)
3270 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
3271 WEBCORE_COMMAND(deleteForward)
3272 WEBCORE_COMMAND(deleteToBeginningOfLine)
3273 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
3274 WEBCORE_COMMAND(deleteToEndOfLine)
3275 WEBCORE_COMMAND(deleteToEndOfParagraph)
3276 WEBCORE_COMMAND(deleteToMark)
3277 WEBCORE_COMMAND(deleteWordBackward)
3278 WEBCORE_COMMAND(deleteWordForward)
3279 WEBCORE_COMMAND(ignoreSpelling)
3280 WEBCORE_COMMAND(indent)
3281 WEBCORE_COMMAND(insertBacktab)
3282 WEBCORE_COMMAND(insertLineBreak)
3283 WEBCORE_COMMAND(insertNewline)
3284 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
3285 WEBCORE_COMMAND(insertParagraphSeparator)
3286 WEBCORE_COMMAND(insertTab)
3287 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
3288 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
3289 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
3290 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
3291 WEBCORE_COMMAND(moveBackward)
3292 WEBCORE_COMMAND(moveBackwardAndModifySelection)
3293 WEBCORE_COMMAND(moveDown)
3294 WEBCORE_COMMAND(moveDownAndModifySelection)
3295 WEBCORE_COMMAND(moveForward)
3296 WEBCORE_COMMAND(moveForwardAndModifySelection)
3297 WEBCORE_COMMAND(moveLeft)
3298 WEBCORE_COMMAND(moveLeftAndModifySelection)
3299 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
3300 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
3301 WEBCORE_COMMAND(moveRight)
3302 WEBCORE_COMMAND(moveRightAndModifySelection)
3303 WEBCORE_COMMAND(moveToBeginningOfDocument)
3304 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
3305 WEBCORE_COMMAND(moveToBeginningOfLine)
3306 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
3307 WEBCORE_COMMAND(moveToBeginningOfParagraph)
3308 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
3309 WEBCORE_COMMAND(moveToBeginningOfSentence)
3310 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
3311 WEBCORE_COMMAND(moveToEndOfDocument)
3312 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
3313 WEBCORE_COMMAND(moveToEndOfLine)
3314 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
3315 WEBCORE_COMMAND(moveToEndOfParagraph)
3316 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
3317 WEBCORE_COMMAND(moveToEndOfSentence)
3318 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
3319 WEBCORE_COMMAND(moveToLeftEndOfLine)
3320 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
3321 WEBCORE_COMMAND(moveToRightEndOfLine)
3322 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
3323 WEBCORE_COMMAND(moveUp)
3324 WEBCORE_COMMAND(moveUpAndModifySelection)
3325 WEBCORE_COMMAND(moveWordBackward)
3326 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
3327 WEBCORE_COMMAND(moveWordForward)
3328 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
3329 WEBCORE_COMMAND(moveWordLeft)
3330 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
3331 WEBCORE_COMMAND(moveWordRight)
3332 WEBCORE_COMMAND(moveWordRightAndModifySelection)
3333 WEBCORE_COMMAND(outdent)
3334 WEBCORE_COMMAND(pageDown)
3335 WEBCORE_COMMAND(pageDownAndModifySelection)
3336 WEBCORE_COMMAND(pageUp)
3337 WEBCORE_COMMAND(pageUpAndModifySelection)
3338 WEBCORE_COMMAND(paste)
3339 WEBCORE_COMMAND(pasteAsPlainText)
3340 WEBCORE_COMMAND(scrollPageDown)
3341 WEBCORE_COMMAND(scrollPageUp)
3342 WEBCORE_COMMAND(scrollLineDown)
3343 WEBCORE_COMMAND(scrollLineUp)
3344 WEBCORE_COMMAND(scrollToBeginningOfDocument)
3345 WEBCORE_COMMAND(scrollToEndOfDocument)
3346 WEBCORE_COMMAND(selectAll)
3347 WEBCORE_COMMAND(selectLine)
3348 WEBCORE_COMMAND(selectParagraph)
3349 WEBCORE_COMMAND(selectSentence)
3350 WEBCORE_COMMAND(selectToMark)
3351 WEBCORE_COMMAND(selectWord)
3352 WEBCORE_COMMAND(setMark)
3353 WEBCORE_COMMAND(subscript)
3354 WEBCORE_COMMAND(superscript)
3355 WEBCORE_COMMAND(swapWithMark)
3356 WEBCORE_COMMAND(takeFindStringFromSelection)
3357 WEBCORE_COMMAND(transpose)
3358 WEBCORE_COMMAND(underline)
3359 WEBCORE_COMMAND(unscript)
3360 WEBCORE_COMMAND(yank)
3361 WEBCORE_COMMAND(yankAndSelect)
3362
3363 #undef WEBCORE_COMMAND
3364
3365 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
3366 {
3367     return _impl->writeSelectionToPasteboard(pasteboard, types);
3368 }
3369
3370 - (void)centerSelectionInVisibleArea:(id)sender
3371 {
3372     _impl->centerSelectionInVisibleArea();
3373 }
3374
3375 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
3376 {
3377     return _impl->validRequestorForSendAndReturnTypes(sendType, returnType);
3378 }
3379
3380 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
3381 {
3382     return _impl->readSelectionFromPasteboard(pasteboard);
3383 }
3384
3385 - (void)changeFont:(id)sender
3386 {
3387     _impl->changeFontFromFontManager();
3388 }
3389
3390 - (void)changeColor:(id)sender
3391 {
3392     _impl->changeFontColorFromSender(sender);
3393 }
3394
3395 - (void)changeAttributes:(id)sender
3396 {
3397     _impl->changeFontAttributesFromSender(sender);
3398 }
3399
3400 - (IBAction)startSpeaking:(id)sender
3401 {
3402     _impl->startSpeaking();
3403 }
3404
3405 - (IBAction)stopSpeaking:(id)sender
3406 {
3407     _impl->stopSpeaking(sender);
3408 }
3409
3410 - (IBAction)showGuessPanel:(id)sender
3411 {
3412     _impl->showGuessPanel(sender);
3413 }
3414
3415 - (IBAction)checkSpelling:(id)sender
3416 {
3417     _impl->checkSpelling();
3418 }
3419
3420 - (void)changeSpelling:(id)sender
3421 {
3422     _impl->changeSpelling(sender);
3423 }
3424
3425 - (IBAction)toggleContinuousSpellChecking:(id)sender
3426 {
3427     _impl->toggleContinuousSpellChecking();
3428 }
3429
3430 - (BOOL)isGrammarCheckingEnabled
3431 {
3432     return _impl->isGrammarCheckingEnabled();
3433 }
3434
3435 - (void)setGrammarCheckingEnabled:(BOOL)flag
3436 {
3437     _impl->setGrammarCheckingEnabled(flag);
3438 }
3439
3440 - (IBAction)toggleGrammarChecking:(id)sender
3441 {
3442     _impl->toggleGrammarChecking();
3443 }
3444
3445 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
3446 {
3447     _impl->toggleAutomaticSpellingCorrection();
3448 }
3449
3450 - (void)orderFrontSubstitutionsPanel:(id)sender
3451 {
3452     _impl->orderFrontSubstitutionsPanel(sender);
3453 }
3454
3455 - (IBAction)toggleSmartInsertDelete:(id)sender
3456 {
3457     _impl->toggleSmartInsertDelete();
3458 }
3459
3460 - (BOOL)isAutomaticQuoteSubstitutionEnabled
3461 {
3462     return _impl->isAutomaticQuoteSubstitutionEnabled();
3463 }
3464
3465 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
3466 {
3467     _impl->setAutomaticQuoteSubstitutionEnabled(flag);
3468 }
3469
3470 - (void)toggleAutomaticQuoteSubstitution:(id)sender
3471 {
3472     _impl->toggleAutomaticQuoteSubstitution();
3473 }
3474
3475 - (BOOL)isAutomaticDashSubstitutionEnabled
3476 {
3477     return _impl->isAutomaticDashSubstitutionEnabled();
3478 }
3479
3480 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
3481 {
3482     _impl->setAutomaticDashSubstitutionEnabled(flag);
3483 }
3484
3485 - (void)toggleAutomaticDashSubstitution:(id)sender
3486 {
3487     _impl->toggleAutomaticDashSubstitution();
3488 }
3489
3490 - (BOOL)isAutomaticLinkDetectionEnabled
3491 {
3492     return _impl->isAutomaticLinkDetectionEnabled();
3493 }
3494
3495 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
3496 {
3497     _impl->setAutomaticLinkDetectionEnabled(flag);
3498 }
3499
3500 - (void)toggleAutomaticLinkDetection:(id)sender
3501 {
3502     _impl->toggleAutomaticLinkDetection();
3503 }
3504
3505 - (BOOL)isAutomaticTextReplacementEnabled
3506 {
3507     return _impl->isAutomaticTextReplacementEnabled();
3508 }
3509
3510 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
3511 {
3512     _impl->setAutomaticTextReplacementEnabled(flag);
3513 }
3514
3515 - (void)toggleAutomaticTextReplacement:(id)sender
3516 {
3517     _impl->toggleAutomaticTextReplacement();
3518 }
3519
3520 - (void)uppercaseWord:(id)sender
3521 {
3522     _impl->uppercaseWord();
3523 }
3524
3525 - (void)lowercaseWord:(id)sender
3526 {
3527     _impl->lowercaseWord();
3528 }
3529
3530 - (void)capitalizeWord:(id)sender
3531 {
3532     _impl->capitalizeWord();
3533 }
3534
3535 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
3536 {
3537     return _impl->wantsKeyDownForEvent(event);
3538 }
3539
3540 - (void)scrollWheel:(NSEvent *)event
3541 {
3542     _impl->scrollWheel(event);
3543 }
3544
3545 - (void)swipeWithEvent:(NSEvent *)event
3546 {
3547     _impl->swipeWithEvent(event);
3548 }
3549
3550 - (void)mouseMoved:(NSEvent *)event
3551 {
3552     _impl->mouseMoved(event);
3553 }
3554
3555 - (void)mouseDown:(NSEvent *)event
3556 {
3557     _impl->mouseDown(event);
3558 }
3559
3560 - (void)mouseUp:(NSEvent *)event
3561 {
3562     _impl->mouseUp(event);
3563 }
3564
3565 - (void)mouseDragged:(NSEvent *)event
3566 {
3567     _impl->mouseDragged(event);
3568 }
3569
3570 - (void)mouseEntered:(NSEvent *)event
3571 {
3572     _impl->mouseEntered(event);
3573 }
3574
3575 - (void)mouseExited:(NSEvent *)event
3576 {
3577     _impl->mouseExited(event);
3578 }
3579
3580 - (void)otherMouseDown:(NSEvent *)event
3581 {
3582     _impl->otherMouseDown(event);
3583 }
3584
3585 - (void)otherMouseDragged:(NSEvent *)event
3586 {
3587     _impl->otherMouseDragged(event);
3588 }
3589
3590 - (void)otherMouseUp:(NSEvent *)event
3591 {
3592     _impl->otherMouseUp(event);
3593 }
3594
3595 - (void)rightMouseDown:(NSEvent *)event
3596 {
3597     _impl->rightMouseDown(event);
3598 }
3599
3600 - (void)rightMouseDragged:(NSEvent *)event
3601 {
3602     _impl->rightMouseDragged(event);
3603 }
3604
3605 - (void)rightMouseUp:(NSEvent *)event
3606 {
3607     _impl->rightMouseUp(event);
3608 }
3609
3610 - (void)pressureChangeWithEvent:(NSEvent *)event
3611 {
3612     _impl->pressureChangeWithEvent(event);
3613 }
3614
3615 - (BOOL)acceptsFirstMouse:(NSEvent *)event
3616 {
3617     return _impl->acceptsFirstMouse(event);
3618 }
3619
3620 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
3621 {
3622     return _impl->shouldDelayWindowOrderingForEvent(event);
3623 }
3624
3625 - (void)doCommandBySelector:(SEL)selector
3626 {
3627     _impl->doCommandBySelector(selector);
3628 }
3629
3630 - (void)insertText:(id)string
3631 {
3632     _impl->insertText(string);
3633 }
3634
3635 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
3636 {
3637     _impl->insertText(string, replacementRange);
3638 }
3639
3640 - (NSTextInputContext *)inputContext
3641 {
3642     if (!_impl)
3643         return nil;
3644     return _impl->inputContext();
3645 }
3646
3647 - (BOOL)performKeyEquivalent:(NSEvent *)event
3648 {
3649     return _impl->performKeyEquivalent(event);
3650 }
3651
3652 - (void)keyUp:(NSEvent *)theEvent
3653 {
3654     _impl->keyUp(theEvent);
3655 }
3656
3657 - (void)keyDown:(NSEvent *)theEvent
3658 {
3659     _impl->keyDown(theEvent);
3660 }
3661
3662 - (void)flagsChanged:(NSEvent *)theEvent
3663 {
3664     _impl->flagsChanged(theEvent);
3665 }
3666
3667 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
3668 {
3669     _impl->setMarkedText(string, newSelectedRange, replacementRange);
3670 }
3671
3672 - (void)unmarkText
3673 {
3674     _impl->unmarkText();
3675 }
3676
3677 - (NSRange)selectedRange
3678 {
3679     return _impl->selectedRange();
3680 }
3681
3682 - (BOOL)hasMarkedText
3683 {
3684     return _impl->hasMarkedText();
3685 }
3686
3687 - (NSRange)markedRange
3688 {
3689     return _impl->markedRange();
3690 }
3691
3692 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
3693 {
3694     return _impl->attributedSubstringForProposedRange(nsRange, actualRange);
3695 }
3696
3697 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
3698 {
3699     return _impl->characterIndexForPoint(thePoint);
3700 }
3701
3702 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
3703 {
3704     return _impl->firstRectForCharacterRange(theRange, actualRange);
3705 }
3706
3707 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
3708 {
3709     _impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
3710 }
3711
3712 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
3713 {
3714     _impl->markedRangeWithCompletionHandler(completionHandlerPtr);
3715 }
3716
3717 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
3718 {
3719     _impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
3720 }
3721
3722 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
3723 {
3724     _impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
3725 }
3726
3727 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
3728 {
3729     _impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
3730 }
3731
3732 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
3733 {
3734     _impl->characterIndexForPoint(thePoint, completionHandlerPtr);
3735 }
3736
3737 - (NSArray *)validAttributesForMarkedText
3738 {
3739     return _impl->validAttributesForMarkedText();
3740 }
3741
3742 #if ENABLE(DRAG_SUPPORT)
3743 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
3744 {
3745     _impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
3746 }
3747
3748 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
3749 {
3750     return _impl->draggingEntered(draggingInfo);
3751 }
3752
3753 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
3754 {
3755     return _impl->draggingUpdated(draggingInfo);
3756 }
3757
3758 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
3759 {
3760     _impl->draggingExited(draggingInfo);
3761 }
3762
3763 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
3764 {
3765     return _impl->prepareForDragOperation(draggingInfo);
3766 }
3767
3768 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
3769 {
3770     return _impl->performDragOperation(draggingInfo);
3771 }
3772
3773 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
3774 {
3775     return _impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
3776 }
3777 #endif // ENABLE(DRAG_SUPPORT)
3778
3779 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)point
3780 {
3781     return _impl->windowResizeMouseLocationIsInVisibleScrollerThumb(NSPointToCGPoint(point));
3782 }
3783
3784 - (void)viewWillMoveToWindow:(NSWindow *)window
3785 {
3786     _impl->viewWillMoveToWindow(window);
3787 }
3788
3789 - (void)viewDidMoveToWindow
3790 {
3791     _impl->viewDidMoveToWindow();
3792 }
3793
3794 - (void)drawRect:(NSRect)rect
3795 {
3796     _impl->drawRect(NSRectToCGRect(rect));
3797 }
3798
3799 - (BOOL)isOpaque
3800 {
3801     return _impl->isOpaque();
3802 }
3803
3804 - (BOOL)mouseDownCanMoveWindow
3805 {
3806     return WebKit::WebViewImpl::mouseDownCanMoveWindow();
3807 }
3808
3809 - (void)viewDidHide
3810 {
3811     _impl->viewDidHide();
3812 }
3813
3814 - (void)viewDidUnhide
3815 {
3816     _impl->viewDidUnhide();
3817 }
3818
3819 - (void)viewDidChangeBackingProperties
3820 {
3821     _impl->viewDidChangeBackingProperties();
3822 }
3823
3824 - (void)_activeSpaceDidChange:(NSNotification *)notification
3825 {
3826     _impl->activeSpaceDidChange();
3827 }
3828
3829 - (id)accessibilityFocusedUIElement
3830 {
3831     return _impl->accessibilityFocusedUIElement();
3832 }
3833
3834 - (BOOL)accessibilityIsIgnored
3835 {
3836     return _impl->accessibilityIsIgnored();
3837 }
3838
3839 - (id)accessibilityHitTest:(NSPoint)point
3840 {
3841     return _impl->accessibilityHitTest(NSPointToCGPoint(point));
3842 }
3843
3844 - (id)accessibilityAttributeValue:(NSString *)attribute
3845 {
3846     return _impl->accessibilityAttributeValue(attribute);
3847 }
3848
3849 - (NSView *)hitTest:(NSPoint)point
3850 {
3851     if (!_impl)
3852         return [super hitTest:point];
3853     return _impl->hitTest(NSPointToCGPoint(point));
3854 }
3855
3856 - (NSInteger)conversationIdentifier
3857 {
3858     return (NSInteger)self;
3859 }
3860
3861 - (void)quickLookWithEvent:(NSEvent *)event
3862 {
3863     _impl->quickLookWithEvent(event);
3864 }
3865
3866 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
3867 {
3868     return _impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
3869 }
3870
3871 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
3872 {
3873     return _impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
3874 }
3875
3876 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
3877 {
3878     CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
3879     for (int i = 0; i < count; i++)
3880         cgRects[i] = NSRectToCGRect(rects[i]);
3881     _impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
3882     free(cgRects);
3883 }
3884
3885 - (void)removeTrackingRect:(NSTrackingRectTag)tag
3886 {
3887     if (!_impl)
3888         return;
3889     _impl->removeTrackingRect(tag);
3890 }
3891
3892 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
3893 {
3894     if (!_impl)
3895         return;
3896     _impl->removeTrackingRects(tags, count);
3897 }
3898
3899 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
3900 {
3901     return _impl->stringForToolTip(tag);
3902 }
3903
3904 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
3905 {
3906     _impl->pasteboardChangedOwner(pasteboard);
3907 }
3908
3909 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
3910 {
3911     _impl->provideDataForPasteboard(pasteboard, type);
3912 }
3913
3914 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
3915 {
3916     return _impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
3917 }
3918
3919 - (BOOL)wantsUpdateLayer
3920 {
3921     return WebKit::WebViewImpl::wantsUpdateLayer();
3922 }
3923
3924 - (void)updateLayer
3925 {
3926     _impl->updateLayer();
3927 }
3928
3929 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3930 {
3931     _impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
3932 }
3933
3934 - (BOOL)allowsBackForwardNavigationGestures
3935 {
3936     return _impl->allowsBackForwardNavigationGestures();
3937 }
3938
3939 - (void)smartMagnifyWithEvent:(NSEvent *)event
3940 {
3941     _impl->smartMagnifyWithEvent(event);
3942 }
3943
3944 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
3945 {
3946     _impl->setMagnification(magnification, NSPointToCGPoint(point));
3947 }
3948
3949 - (void)setMagnification:(double)magnification
3950 {
3951     _impl->setMagnification(magnification);
3952 }
3953
3954 - (double)magnification
3955 {
3956     return _impl->magnification();
3957 }
3958
3959 - (void)setAllowsMagnification:(BOOL)allowsMagnification
3960 {
3961     _impl->setAllowsMagnification(allowsMagnification);
3962 }
3963
3964 - (BOOL)allowsMagnification
3965 {
3966     return _impl->allowsMagnification();
3967 }
3968
3969 - (void)magnifyWithEvent:(NSEvent *)event
3970 {
3971     _impl->magnifyWithEvent(event);
3972 }
3973
3974 #if ENABLE(MAC_GESTURE_EVENTS)
3975 - (void)rotateWithEvent:(NSEvent *)event
3976 {
3977     _impl->rotateWithEvent(event);
3978 }
3979 #endif
3980
3981 - (WKTextFinderClient *)_ensureTextFinderClient
3982 {
3983     if (!_textFinderClient)
3984         _textFinderClient = adoptNS([[WKTextFinderClient alloc] initWithPage:*_page view:self]);
3985     return _textFinderClient.get();
3986 }
3987
3988 - (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
3989 {
3990     [[self _ensureTextFinderClient] findMatchesForString:targetString relativeToMatch:relativeMatch findOptions:findOptions maxResults:maxResults resultCollector:resultCollector];
3991 }
3992
3993 - (NSView *)documentContainerView
3994 {
3995     return self;
3996 }
3997
3998 - (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler
3999 {
4000     [[self _ensureTextFinderClient] getSelectedText:completionHandler];
4001 }
4002
4003 - (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler
4004 {
4005     [[self _ensureTextFinderClient] selectFindMatch:findMatch completionHandler:completionHandler];
4006 }
4007
4008 - (NSTextInputContext *)_web_superInputContext
4009 {
4010     return [super inputContext];
4011 }
4012
4013 - (void)_web_superQuickLookWithEvent:(NSEvent *)event
4014 {
4015     [super quickLookWithEvent:event];
4016 }
4017
4018 - (void)_web_superSwipeWithEvent:(NSEvent *)event
4019 {
4020     [super swipeWithEvent:event];
4021 }
4022
4023 - (void)_web_superMagnifyWithEvent:(NSEvent *)event
4024 {
4025     [super magnifyWithEvent:event];
4026 }
4027
4028 - (void)_web_superSmartMagnifyWithEvent:(NSEvent *)event
4029 {
4030     [super smartMagnifyWithEvent:event];
4031 }
4032
4033 - (void)_web_superRemoveTrackingRect:(NSTrackingRectTag)tag
4034 {
4035     [super removeTrackingRect:tag];
4036 }
4037
4038 - (id)_web_superAccessibilityAttributeValue:(NSString *)attribute
4039 {
4040 #pragma clang diagnostic push
4041 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
4042     return [super accessibilityAttributeValue:attribute];
4043 #pragma clang diagnostic pop
4044 }
4045
4046 - (void)_web_superDoCommandBySelector:(SEL)selector
4047 {
4048     [super doCommandBySelector:selector];
4049 }
4050
4051 - (BOOL)_web_superPerformKeyEquivalent:(NSEvent *)event
4052 {
4053     return [super performKeyEquivalent:event];
4054 }
4055
4056 - (void)_web_superKeyDown:(NSEvent *)event
4057 {
4058     [super keyDown:event];
4059 }
4060
4061 - (NSView *)_web_superHitTest:(NSPoint)point
4062 {
4063     return [super hitTest:point];
4064 }
4065
4066 - (id)_web_immediateActionAnimationControllerForHitTestResultInternal:(API::HitTestResult*)hitTestResult withType:(uint32_t)type userData:(API::Object*)userData
4067 {
4068     id<NSSecureCoding> data = userData ? static_cast<id<NSSecureCoding>>(userData->wrapper()) : nil;
4069     return [self _immediateActionAnimationControllerForHitTestResult:wrapper(*hitTestResult) withType:(_WKImmediateActionType)type userData:data];
4070 }
4071
4072 - (void)_web_prepareForImmediateActionAnimation
4073 {
4074     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
4075     if ([uiDelegate respondsToSelector:@selector(_prepareForImmediateActionAnimationForWebView:)])
4076         [uiDelegate _prepareForImmediateActionAnimationForWebView:self];
4077     else
4078         [self _prepareForImmediateActionAnimation];
4079 }
4080
4081 - (void)_web_cancelImmediateActionAnimation
4082 {
4083     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
4084     if ([uiDelegate respondsToSelector:@selector(_cancelImmediateActionAnimationForWebView:)])
4085         [uiDelegate _cancelImmediateActionAnimationForWebView:self];
4086     else
4087         [self _cancelImmediateActionAnimation];
4088 }
4089
4090 - (void)_web_completeImmediateActionAnimation
4091 {
4092     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
4093     if ([uiDelegate respondsToSelector:@selector(_completeImmediateActionAnimationForWebView:)])
4094         [uiDelegate _completeImmediateActionAnimationForWebView:self];
4095     else
4096         [self _completeImmediateActionAnimation];
4097 }
4098
4099 - (void)_web_didChangeContentSize:(NSSize)newSize
4100 {
4101 }
4102
4103 #if ENABLE(DRAG_SUPPORT)
4104
4105 - (WKDragDestinationAction)_web_dragDestinationActionForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
4106 {
4107     id <WKUIDelegatePrivate> uiDelegate = (id <WKUIDelegatePrivate>)[self UIDelegate];
4108     if&nb