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