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