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