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