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