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