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