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