Unreviewed, rolling out r191902.
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / Cocoa / WKWebView.mm
1 /*
2  * Copyright (C) 2014, 2015 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 "_WKDiagnosticLoggingDelegate.h"
76 #import "_WKFindDelegate.h"
77 #import "_WKFormDelegate.h"
78 #import "_WKInputDelegate.h"
79 #import "_WKRemoteObjectRegistryInternal.h"
80 #import "_WKSessionStateInternal.h"
81 #import "_WKVisitedLinkStoreInternal.h"
82 #import <WebCore/IOSurface.h>
83 #import <WebCore/JSDOMBinding.h>
84 #import <wtf/HashMap.h>
85 #import <wtf/MathExtras.h>
86 #import <wtf/NeverDestroyed.h>
87 #import <wtf/Optional.h>
88 #import <wtf/RetainPtr.h>
89 #import <wtf/TemporaryChange.h>
90
91 #if PLATFORM(IOS)
92 #import "_WKFrameHandleInternal.h"
93 #import "_WKWebViewPrintFormatter.h"
94 #import "PrintInfo.h"
95 #import "ProcessThrottler.h"
96 #import "RemoteLayerTreeDrawingAreaProxy.h"
97 #import "RemoteScrollingCoordinatorProxy.h"
98 #import "UIKitSPI.h"
99 #import "WKContentViewInteraction.h"
100 #import "WKPDFView.h"
101 #import "WKScrollView.h"
102 #import "WKWebViewContentProviderRegistry.h"
103 #import "WebPageMessages.h"
104 #import "WebVideoFullscreenManagerProxy.h"
105 #import <UIKit/UIApplication.h>
106 #import <WebCore/CoreGraphicsSPI.h>
107 #import <WebCore/FrameLoaderTypes.h>
108 #import <WebCore/InspectorOverlay.h>
109 #import <WebCore/QuartzCoreSPI.h>
110
111 @interface UIScrollView (UIScrollViewInternal)
112 - (void)_adjustForAutomaticKeyboardInfo:(NSDictionary*)info animated:(BOOL)animated lastAdjustment:(CGFloat*)lastAdjustment;
113 - (BOOL)_isScrollingToTop;
114 - (BOOL)_isInterruptingDeceleration;
115 - (CGPoint)_animatedTargetOffset;
116 @end
117
118 @interface UIPeripheralHost(UIKitInternal)
119 - (CGFloat)getVerticalOverlapForView:(UIView *)view usingKeyboardInfo:(NSDictionary *)info;
120 @end
121
122 @interface UIView (UIViewInternal)
123 - (UIViewController *)_viewControllerForAncestor;
124 @end
125
126 @interface UIWindow (UIWindowInternal)
127 - (BOOL)_isHostedInAnotherProcess;
128 @end
129
130 @interface UIViewController (UIViewControllerInternal)
131 - (UIViewController *)_rootAncestorViewController;
132 - (UIViewController *)_viewControllerForSupportedInterfaceOrientations;
133 @end
134
135 enum class DynamicViewportUpdateMode {
136     NotResizing,
137     ResizingWithAnimation,
138     ResizingWithDocumentHidden,
139 };
140
141 #endif
142
143 #if PLATFORM(MAC)
144 #import "WKViewInternal.h"
145 #import <WebCore/ColorMac.h>
146 #endif
147
148 static HashMap<WebKit::WebPageProxy*, WKWebView *>& pageToViewMap()
149 {
150     static NeverDestroyed<HashMap<WebKit::WebPageProxy*, WKWebView *>> map;
151     return map;
152 }
153
154 WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
155 {
156     return pageToViewMap().get(&page);
157 }
158
159 @implementation WKWebView {
160     std::unique_ptr<WebKit::NavigationState> _navigationState;
161     std::unique_ptr<WebKit::UIDelegate> _uiDelegate;
162
163     RetainPtr<_WKRemoteObjectRegistry> _remoteObjectRegistry;
164     _WKRenderingProgressEvents _observedRenderingProgressEvents;
165
166     WebKit::WeakObjCPtr<id <_WKInputDelegate>> _inputDelegate;
167
168 #if PLATFORM(IOS)
169     RetainPtr<WKScrollView> _scrollView;
170     RetainPtr<WKContentView> _contentView;
171
172     BOOL _overridesMinimumLayoutSize;
173     CGSize _minimumLayoutSizeOverride;
174     BOOL _overridesMaximumUnobscuredSize;
175     CGSize _maximumUnobscuredSizeOverride;
176     CGRect _inputViewBounds;
177     CGFloat _viewportMetaTagWidth;
178     CGFloat _initialScaleFactor;
179     BOOL _fastClickingIsDisabled;
180
181     BOOL _allowsLinkPreview;
182
183     UIEdgeInsets _obscuredInsets;
184     BOOL _haveSetObscuredInsets;
185     BOOL _isChangingObscuredInsetsInteractively;
186
187     UIInterfaceOrientation _interfaceOrientationOverride;
188     BOOL _overridesInterfaceOrientation;
189
190     BOOL _hasCommittedLoadForMainFrame;
191     BOOL _needsResetViewStateAfterCommitLoadForMainFrame;
192     uint64_t _firstPaintAfterCommitLoadTransactionID;
193     DynamicViewportUpdateMode _dynamicViewportUpdateMode;
194     CATransform3D _resizeAnimationTransformAdjustments;
195     uint64_t _resizeAnimationTransformTransactionID;
196     RetainPtr<UIView> _resizeAnimationView;
197     CGFloat _lastAdjustmentForScroller;
198     Optional<CGRect> _frozenVisibleContentRect;
199     Optional<CGRect> _frozenUnobscuredContentRect;
200
201     BOOL _needsToRestoreExposedRect;
202     WebCore::FloatRect _exposedRectToRestore;
203     BOOL _needsToRestoreUnobscuredCenter;
204     WebCore::FloatPoint _unobscuredCenterToRestore;
205     uint64_t _firstTransactionIDAfterPageRestore;
206     double _scaleToRestore;
207
208     std::unique_ptr<WebKit::ViewGestureController> _gestureController;
209     BOOL _allowsBackForwardNavigationGestures;
210
211     RetainPtr<UIView <WKWebViewContentProvider>> _customContentView;
212     RetainPtr<UIView> _customContentFixedOverlayView;
213
214     WebCore::Color _scrollViewBackgroundColor;
215
216     // This value tracks the current adjustment added to the bottom inset due to the keyboard sliding out from the bottom
217     // when computing obscured content insets. This is used when updating the visible content rects where we should not
218     // include this adjustment.
219     CGFloat _totalScrollViewBottomInsetAdjustmentForKeyboard;
220     BOOL _currentlyAdjustingScrollViewInsetsForKeyboard;
221
222     BOOL _delayUpdateVisibleContentRects;
223     BOOL _hadDelayedUpdateVisibleContentRects;
224
225     BOOL _pageIsPrintingToPDF;
226     RetainPtr<CGPDFDocumentRef> _printedDocument;
227     Vector<std::function<void ()>> _snapshotsDeferredDuringResize;
228 #endif
229 #if PLATFORM(MAC)
230     RetainPtr<WKView> _wkView;
231     CGSize _intrinsicContentSize;
232 #endif
233 }
234
235 - (instancetype)initWithFrame:(CGRect)frame
236 {
237     return [self initWithFrame:frame configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()];
238 }
239
240 #if PLATFORM(IOS)
241 static int32_t deviceOrientationForUIInterfaceOrientation(UIInterfaceOrientation orientation)
242 {
243     switch (orientation) {
244     case UIInterfaceOrientationUnknown:
245     case UIInterfaceOrientationPortrait:
246         return 0;
247     case UIInterfaceOrientationPortraitUpsideDown:
248         return 180;
249     case UIInterfaceOrientationLandscapeLeft:
250         return -90;
251     case UIInterfaceOrientationLandscapeRight:
252         return 90;
253     }
254 }
255
256 static int32_t deviceOrientation()
257 {
258     return deviceOrientationForUIInterfaceOrientation([[UIApplication sharedApplication] statusBarOrientation]);
259 }
260
261 - (BOOL)_isShowingVideoPictureInPicture
262 {
263     if (!_page || !_page->videoFullscreenManager())
264         return false;
265     
266     return _page->videoFullscreenManager()->hasMode(WebCore::HTMLMediaElementEnums::VideoFullscreenModePictureInPicture);
267 }
268
269 - (BOOL)_mayAutomaticallyShowVideoPictureInPicture
270 {
271 #if !HAVE(AVKIT)
272     return false;
273 #else
274     if (!_page || !_page->videoFullscreenManager())
275         return false;
276
277     return _page->videoFullscreenManager()->mayAutomaticallyShowVideoPictureInPicture();
278 #endif
279 }
280
281 static bool shouldAllowPictureInPictureMediaPlayback()
282 {
283     static bool shouldAllowPictureInPictureMediaPlayback = iosExecutableWasLinkedOnOrAfterVersion(wkIOSSystemVersion_9_0);
284     return shouldAllowPictureInPictureMediaPlayback;
285 }
286
287 #endif
288
289 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
290 {
291     if (!(self = [super initWithFrame:frame]))
292         return nil;
293
294     if (!configuration)
295         [NSException raise:NSInvalidArgumentException format:@"Configuration cannot be nil"];
296
297     _configuration = adoptNS([configuration copy]);
298
299     if (WKWebView *relatedWebView = [_configuration _relatedWebView]) {
300         WKProcessPool *processPool = [_configuration processPool];
301         WKProcessPool *relatedWebViewProcessPool = [relatedWebView->_configuration processPool];
302         if (processPool && processPool != relatedWebViewProcessPool)
303             [NSException raise:NSInvalidArgumentException format:@"Related web view %@ has process pool %@ but configuration specifies a different process pool %@", relatedWebView, relatedWebViewProcessPool, configuration.processPool];
304
305         [_configuration setProcessPool:relatedWebViewProcessPool];
306     }
307
308     [_configuration _validate];
309
310     CGRect bounds = self.bounds;
311
312     WebKit::WebProcessPool& processPool = *[_configuration processPool]->_processPool;
313     
314     auto pageConfiguration = API::PageConfiguration::create();
315
316     pageConfiguration->setProcessPool(&processPool);
317     pageConfiguration->setPreferences([_configuration preferences]->_preferences.get());
318     if (WKWebView *relatedWebView = [_configuration _relatedWebView])
319         pageConfiguration->setRelatedPage(relatedWebView->_page.get());
320
321     pageConfiguration->setUserContentController([_configuration userContentController]->_userContentControllerProxy.get());
322     pageConfiguration->setVisitedLinkStore([_configuration _visitedLinkStore]->_visitedLinkStore.get());
323     pageConfiguration->setWebsiteDataStore([_configuration websiteDataStore]->_websiteDataStore.get());
324     pageConfiguration->setTreatsSHA1SignedCertificatesAsInsecure([_configuration _treatsSHA1SignedCertificatesAsInsecure]);
325
326     RefPtr<WebKit::WebPageGroup> pageGroup;
327     NSString *groupIdentifier = configuration._groupIdentifier;
328     if (groupIdentifier.length) {
329         pageGroup = WebKit::WebPageGroup::create(configuration._groupIdentifier);
330         pageConfiguration->setPageGroup(pageGroup.get());
331     }
332
333     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::suppressesIncrementalRenderingKey(), WebKit::WebPreferencesStore::Value(!![_configuration suppressesIncrementalRendering]));
334
335 #if PLATFORM(IOS)
336     pageConfiguration->setAlwaysRunsAtForegroundPriority([_configuration _alwaysRunsAtForegroundPriority]);
337
338     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsInlineMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsInlineMediaPlayback]));
339     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey(), WebKit::WebPreferencesStore::Value(!![_configuration _inlineMediaPlaybackRequiresPlaysInlineAttribute]));
340     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback()));
341     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::requiresUserGestureForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration requiresUserActionForMediaPlayback]));
342     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::mediaDataLoadsAutomaticallyKey(), WebKit::WebPreferencesStore::Value(!![_configuration _mediaDataLoadsAutomatically]));
343 #endif
344 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
345     pageConfiguration->preferenceValues().set(WebKit::WebPreferencesKey::allowsAirPlayForMediaPlaybackKey(), WebKit::WebPreferencesStore::Value(!![_configuration allowsAirPlayForMediaPlayback]));
346 #endif
347
348 #if PLATFORM(IOS)
349     _scrollView = adoptNS([[WKScrollView alloc] initWithFrame:bounds]);
350     [_scrollView setInternalDelegate:self];
351     [_scrollView setBouncesZoom:YES];
352
353     [self addSubview:_scrollView.get()];
354
355     _contentView = adoptNS([[WKContentView alloc] initWithFrame:bounds processPool:processPool configuration:WTF::move(pageConfiguration) webView:self]);
356
357     _page = [_contentView page];
358     _page->setDeviceOrientation(deviceOrientation());
359
360     [_contentView layer].anchorPoint = CGPointZero;
361     [_contentView setFrame:bounds];
362     [_scrollView addSubview:_contentView.get()];
363     [_scrollView addSubview:[_contentView unscaledView]];
364     [self _updateScrollViewBackground];
365
366     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
367     _initialScaleFactor = 1;
368     _fastClickingIsDisabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitFastClickingDisabled"];
369
370     [self _frameOrBoundsChanged];
371
372     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
373     [center addObserver:self selector:@selector(_keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
374     [center addObserver:self selector:@selector(_keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
375     [center addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
376     [center addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
377     [center addObserver:self selector:@selector(_windowDidRotate:) name:UIWindowDidRotateNotification object:nil];
378     [center addObserver:self selector:@selector(_contentSizeCategoryDidChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
379     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
380
381     [[_configuration _contentProviderRegistry] addPage:*_page];
382 #endif
383
384 #if PLATFORM(MAC)
385     _wkView = adoptNS([[WKView alloc] initWithFrame:bounds processPool:processPool configuration:WTF::move(pageConfiguration) webView:self]);
386     [self addSubview:_wkView.get()];
387     _page = WebKit::toImpl([_wkView pageRef]);
388
389     _intrinsicContentSize = CGSizeMake(NSViewNoInstrinsicMetric, NSViewNoInstrinsicMetric);
390
391 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
392     [_wkView _setAutomaticallyAdjustsContentInsets:YES];
393 #endif
394 #endif
395
396     _page->setBackgroundExtendsBeyondPage(true);
397
398     if (NSString *applicationNameForUserAgent = configuration.applicationNameForUserAgent)
399         _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
400
401     _navigationState = std::make_unique<WebKit::NavigationState>(self);
402     _uiDelegate = std::make_unique<WebKit::UIDelegate>(self);
403     _page->setFindClient(std::make_unique<WebKit::FindClient>(self));
404     _page->setDiagnosticLoggingClient(std::make_unique<WebKit::DiagnosticLoggingClient>(self));
405
406     pageToViewMap().add(_page.get(), self);
407
408     return self;
409 }
410
411 - (instancetype)initWithCoder:(NSCoder *)coder
412 {
413     [self release];
414     return nil;
415 }
416
417 - (void)dealloc
418 {
419     if (_remoteObjectRegistry)
420         _page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID());
421
422     _page->close();
423
424     [_remoteObjectRegistry _invalidate];
425 #if PLATFORM(IOS)
426     [[_configuration _contentProviderRegistry] removePage:*_page];
427     [[NSNotificationCenter defaultCenter] removeObserver:self];
428     [_scrollView setInternalDelegate:nil];
429 #endif
430
431     pageToViewMap().remove(_page.get());
432
433     [super dealloc];
434 }
435
436 - (WKWebViewConfiguration *)configuration
437 {
438     return [[_configuration copy] autorelease];
439 }
440
441 - (WKBackForwardList *)backForwardList
442 {
443     return wrapper(_page->backForwardList());
444 }
445
446 - (id <WKNavigationDelegate>)navigationDelegate
447 {
448     return _navigationState->navigationDelegate().autorelease();
449 }
450
451 - (void)setNavigationDelegate:(id <WKNavigationDelegate>)navigationDelegate
452 {
453     _page->setNavigationClient(_navigationState->createNavigationClient());
454     _navigationState->setNavigationDelegate(navigationDelegate);
455 }
456
457 - (id <WKUIDelegate>)UIDelegate
458 {
459     return _uiDelegate->delegate().autorelease();
460 }
461
462 - (void)setUIDelegate:(id<WKUIDelegate>)UIDelegate
463 {
464 #if ENABLE(CONTEXT_MENUS)
465     _page->setContextMenuClient(_uiDelegate->createContextMenuClient());
466 #endif
467     _page->setUIClient(_uiDelegate->createUIClient());
468     _uiDelegate->setDelegate(UIDelegate);
469 }
470
471 - (WKNavigation *)loadRequest:(NSURLRequest *)request
472 {
473     auto navigation = _page->loadRequest(request);
474     if (!navigation)
475         return nil;
476
477     return [wrapper(*navigation.release().leakRef()) autorelease];
478 }
479
480 - (WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
481 {
482     if (![URL isFileURL])
483         [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", URL];
484
485     if (![readAccessURL isFileURL])
486         [NSException raise:NSInvalidArgumentException format:@"%@ is not a file URL", readAccessURL];
487
488     auto navigation = _page->loadFile([URL _web_originalDataAsWTFString], [readAccessURL _web_originalDataAsWTFString]);
489     if (!navigation)
490         return nil;
491
492     return [wrapper(*navigation.release().leakRef()) autorelease];
493 }
494
495 - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
496 {
497     NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
498
499     return [self loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL];
500 }
501
502 - (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
503 {
504     auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString);
505     if (!navigation)
506         return nil;
507
508     return [wrapper(*navigation.release().leakRef()) autorelease];
509 }
510
511 - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item
512 {
513     auto navigation = _page->goToBackForwardItem(&item._item);
514     if (!navigation)
515         return nil;
516
517     return [wrapper(*navigation.release().leakRef()) autorelease];
518 }
519
520 - (NSString *)title
521 {
522     return _page->pageLoadState().title();
523 }
524
525 - (NSURL *)URL
526 {
527     return [NSURL _web_URLWithWTFString:_page->pageLoadState().activeURL()];
528 }
529
530 - (BOOL)isLoading
531 {
532     return _page->pageLoadState().isLoading();
533 }
534
535 - (double)estimatedProgress
536 {
537     return _page->pageLoadState().estimatedProgress();
538 }
539
540 - (BOOL)hasOnlySecureContent
541 {
542     return _page->pageLoadState().hasOnlySecureContent();
543 }
544
545 - (NSArray *)certificateChain
546 {
547     auto certificateInfo = _page->pageLoadState().certificateInfo();
548     if (!certificateInfo)
549         return @[ ];
550
551     return (NSArray *)certificateInfo->certificateInfo().certificateChain() ?: @[ ];
552 }
553
554 - (BOOL)canGoBack
555 {
556     return _page->pageLoadState().canGoBack();
557 }
558
559 - (BOOL)canGoForward
560 {
561     return _page->pageLoadState().canGoForward();
562 }
563
564 - (WKNavigation *)goBack
565 {
566     auto navigation = _page->goBack();
567     if (!navigation)
568         return nil;
569  
570     return [wrapper(*navigation.release().leakRef()) autorelease];
571 }
572
573 - (WKNavigation *)goForward
574 {
575     auto navigation = _page->goForward();
576     if (!navigation)
577         return nil;
578
579     return [wrapper(*navigation.release().leakRef()) autorelease];
580 }
581
582 - (WKNavigation *)reload
583 {
584     const bool reloadFromOrigin = false;
585     const bool contentBlockersEnabled = true;
586     auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
587     if (!navigation)
588         return nil;
589
590     return [wrapper(*navigation.release().leakRef()) autorelease];
591 }
592
593 - (WKNavigation *)reloadFromOrigin
594 {
595     const bool reloadFromOrigin = true;
596     const bool contentBlockersEnabled = true;
597     auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
598     if (!navigation)
599         return nil;
600
601     return [wrapper(*navigation.release().leakRef()) autorelease];
602 }
603
604 - (void)stopLoading
605 {
606     _page->stopLoading();
607 }
608
609 static WKErrorCode callbackErrorCode(WebKit::CallbackBase::Error error)
610 {
611     switch (error) {
612     case WebKit::CallbackBase::Error::None:
613         ASSERT_NOT_REACHED();
614         return WKErrorUnknown;
615
616     case WebKit::CallbackBase::Error::Unknown:
617         return WKErrorUnknown;
618
619     case WebKit::CallbackBase::Error::ProcessExited:
620         return WKErrorWebContentProcessTerminated;
621
622     case WebKit::CallbackBase::Error::OwnerWasInvalidated:
623         return WKErrorWebViewInvalidated;
624     }
625 }
626
627 - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
628 {
629     auto handler = adoptNS([completionHandler copy]);
630
631     _page->runJavaScriptInMainFrame(javaScriptString, [handler](API::SerializedScriptValue* serializedScriptValue, bool hadException, const WebCore::ExceptionDetails& details, WebKit::ScriptValueCallback::Error errorCode) {
632         if (!handler)
633             return;
634
635         if (errorCode != WebKit::ScriptValueCallback::Error::None) {
636             auto error = createNSError(callbackErrorCode(errorCode));
637             if (errorCode == WebKit::ScriptValueCallback::Error::OwnerWasInvalidated) {
638                 // The OwnerWasInvalidated callback is synchronous. We don't want to call the block from within it
639                 // because that can trigger re-entrancy bugs in WebKit.
640                 // FIXME: It would be even better if GenericCallback did this for us.
641                 dispatch_async(dispatch_get_main_queue(), [handler, error] {
642                     auto rawHandler = (void (^)(id, NSError *))handler.get();
643                     rawHandler(nil, error.get());
644                 });
645                 return;
646             }
647
648             auto rawHandler = (void (^)(id, NSError *))handler.get();
649             rawHandler(nil, error.get());
650             return;
651         }
652
653         auto rawHandler = (void (^)(id, NSError *))handler.get();
654         if (hadException) {
655             ASSERT(!serializedScriptValue);
656
657             RetainPtr<NSMutableDictionary> userInfo = adoptNS([[NSMutableDictionary alloc] init]);
658
659             [userInfo setObject:localizedDescriptionForErrorCode(WKErrorJavaScriptExceptionOccurred) forKey:NSLocalizedDescriptionKey];
660             [userInfo setObject:static_cast<NSString *>(details.message) forKey:_WKJavaScriptExceptionMessageErrorKey];
661             [userInfo setObject:@(details.lineNumber) forKey:_WKJavaScriptExceptionLineNumberErrorKey];
662             [userInfo setObject:@(details.columnNumber) forKey:_WKJavaScriptExceptionColumnNumberErrorKey];
663
664             if (!details.sourceURL.isEmpty())
665                 [userInfo setObject:[NSURL _web_URLWithWTFString:details.sourceURL] forKey:_WKJavaScriptExceptionSourceURLErrorKey];
666
667             rawHandler(nil, adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:WKErrorJavaScriptExceptionOccurred userInfo:userInfo.get()]).get());
668             return;
669         }
670
671         if (!serializedScriptValue) {
672             rawHandler(nil, createNSError(WKErrorJavaScriptResultTypeIsUnsupported).get());
673             return;
674         }
675
676         id body = API::SerializedScriptValue::deserialize(*serializedScriptValue->internalRepresentation(), 0);
677         rawHandler(body, nil);
678     });
679 }
680
681 - (NSString *)customUserAgent
682 {
683     return _page->customUserAgent();
684 }
685
686 - (void)setCustomUserAgent:(NSString *)customUserAgent
687 {
688     _page->setCustomUserAgent(customUserAgent);
689 }
690
691 - (WKPageRef)_pageForTesting
692 {
693     return toAPI(_page.get());
694 }
695
696 - (BOOL)allowsLinkPreview
697 {
698 #if PLATFORM(MAC)
699     return [_wkView allowsLinkPreview];
700 #elif PLATFORM(IOS)
701     return _allowsLinkPreview;
702 #endif
703 }
704
705 - (void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
706 {
707 #if PLATFORM(MAC)
708     [_wkView setAllowsLinkPreview:allowsLinkPreview];
709     return;
710 #elif PLATFORM(IOS)
711     if (_allowsLinkPreview == allowsLinkPreview)
712         return;
713
714     _allowsLinkPreview = allowsLinkPreview;
715
716 #if HAVE(LINK_PREVIEW)
717     if (_allowsLinkPreview)
718         [_contentView _registerPreview];
719     else
720         [_contentView _unregisterPreview];
721 #endif // HAVE(LINK_PREVIEW)
722 #endif // PLATFORM(IOS)
723 }
724
725 #pragma mark iOS-specific methods
726
727 #if PLATFORM(IOS)
728 - (void)setFrame:(CGRect)frame
729 {
730     CGRect oldFrame = self.frame;
731     [super setFrame:frame];
732
733     if (!CGSizeEqualToSize(oldFrame.size, frame.size))
734         [self _frameOrBoundsChanged];
735 }
736
737 - (void)setBounds:(CGRect)bounds
738 {
739     CGRect oldBounds = self.bounds;
740     [super setBounds:bounds];
741     [_customContentFixedOverlayView setFrame:self.bounds];
742
743     if (!CGSizeEqualToSize(oldBounds.size, bounds.size))
744         [self _frameOrBoundsChanged];
745 }
746
747 - (UIScrollView *)scrollView
748 {
749     return _scrollView.get();
750 }
751
752 - (WKBrowsingContextController *)browsingContextController
753 {
754     return [_contentView browsingContextController];
755 }
756
757 - (BOOL)becomeFirstResponder
758 {
759     return [_contentView becomeFirstResponder] || [super becomeFirstResponder];
760 }
761
762 static inline CGFloat floorToDevicePixel(CGFloat input, float deviceScaleFactor)
763 {
764     return CGFloor(input * deviceScaleFactor) / deviceScaleFactor;
765 }
766
767 static inline bool pointsEqualInDevicePixels(CGPoint a, CGPoint b, float deviceScaleFactor)
768 {
769     return fabs(a.x * deviceScaleFactor - b.x * deviceScaleFactor) < std::numeric_limits<float>::epsilon()
770         && fabs(a.y * deviceScaleFactor - b.y * deviceScaleFactor) < std::numeric_limits<float>::epsilon();
771 }
772
773 static CGSize roundScrollViewContentSize(const WebKit::WebPageProxy& page, CGSize contentSize)
774 {
775     float deviceScaleFactor = page.deviceScaleFactor();
776     return CGSizeMake(floorToDevicePixel(contentSize.width, deviceScaleFactor), floorToDevicePixel(contentSize.height, deviceScaleFactor));
777 }
778
779 - (UIView *)_currentContentView
780 {
781     return _customContentView ? _customContentView.get() : _contentView.get();
782 }
783
784 - (void)_setHasCustomContentView:(BOOL)pageHasCustomContentView loadedMIMEType:(const WTF::String&)mimeType
785 {
786     if (pageHasCustomContentView) {
787         [_customContentView removeFromSuperview];
788         [_customContentFixedOverlayView removeFromSuperview];
789
790         Class representationClass = [[_configuration _contentProviderRegistry] providerForMIMEType:mimeType];
791         ASSERT(representationClass);
792         _customContentView = adoptNS([[representationClass alloc] web_initWithFrame:self.bounds webView:self]);
793         _customContentFixedOverlayView = adoptNS([[UIView alloc] initWithFrame:self.bounds]);
794         [_customContentFixedOverlayView setUserInteractionEnabled:NO];
795
796         [[_contentView unscaledView] removeFromSuperview];
797         [_contentView removeFromSuperview];
798         [_scrollView addSubview:_customContentView.get()];
799         [self addSubview:_customContentFixedOverlayView.get()];
800
801         [_customContentView web_setMinimumSize:self.bounds.size];
802         [_customContentView web_setFixedOverlayView:_customContentFixedOverlayView.get()];
803     } else if (_customContentView) {
804         [_customContentView removeFromSuperview];
805         _customContentView = nullptr;
806
807         [_customContentFixedOverlayView removeFromSuperview];
808         _customContentFixedOverlayView = nullptr;
809
810         [_scrollView addSubview:_contentView.get()];
811         [_scrollView addSubview:[_contentView unscaledView]];
812         [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
813
814         [_customContentFixedOverlayView setFrame:self.bounds];
815         [self addSubview:_customContentFixedOverlayView.get()];
816     }
817 }
818
819 - (void)_didFinishLoadingDataForCustomContentProviderWithSuggestedFilename:(const String&)suggestedFilename data:(NSData *)data
820 {
821     ASSERT(_customContentView);
822     [_customContentView web_setContentProviderData:data suggestedFilename:suggestedFilename];
823
824     // FIXME: It may make more sense for custom content providers to invoke this when they're ready,
825     // because there's no guarantee that all custom content providers will lay out synchronously.
826     _page->didLayoutForCustomContentProvider();
827 }
828
829 - (void)_willInvokeUIScrollViewDelegateCallback
830 {
831     _delayUpdateVisibleContentRects = YES;
832 }
833
834 - (void)_didInvokeUIScrollViewDelegateCallback
835 {
836     _delayUpdateVisibleContentRects = NO;
837     if (_hadDelayedUpdateVisibleContentRects) {
838         _hadDelayedUpdateVisibleContentRects = NO;
839         [self _updateVisibleContentRects];
840     }
841 }
842
843 static CGFloat contentZoomScale(WKWebView *webView)
844 {
845     CGFloat scale = webView._currentContentView.layer.affineTransform.a;
846     ASSERT(scale == [webView->_scrollView zoomScale]);
847     return scale;
848 }
849
850 static WebCore::Color baseScrollViewBackgroundColor(WKWebView *webView)
851 {
852     if (webView->_customContentView)
853         return [webView->_customContentView backgroundColor].CGColor;
854
855     if (webView->_gestureController) {
856         WebCore::Color color = webView->_gestureController->backgroundColorForCurrentSnapshot();
857         if (color.isValid())
858             return color;
859     }
860
861     return webView->_page->pageExtendedBackgroundColor();
862 }
863
864 static WebCore::Color scrollViewBackgroundColor(WKWebView *webView)
865 {
866     if (!webView.opaque)
867         return WebCore::Color::transparent;
868
869     WebCore::Color color = baseScrollViewBackgroundColor(webView);
870
871     if (!color.isValid())
872         color = WebCore::Color::white;
873
874     CGFloat zoomScale = contentZoomScale(webView);
875     CGFloat minimumZoomScale = [webView->_scrollView minimumZoomScale];
876     if (zoomScale < minimumZoomScale) {
877         CGFloat slope = 12;
878         CGFloat opacity = std::max<CGFloat>(1 - slope * (minimumZoomScale - zoomScale), 0);
879         color = WebCore::colorWithOverrideAlpha(color.rgb(), opacity);
880     }
881
882     return color;
883 }
884
885 - (void)_updateScrollViewBackground
886 {
887     WebCore::Color color = scrollViewBackgroundColor(self);
888
889     if (_scrollViewBackgroundColor == color)
890         return;
891
892     _scrollViewBackgroundColor = color;
893
894     auto uiBackgroundColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(color, WebCore::ColorSpaceDeviceRGB)]);
895     [_scrollView setBackgroundColor:uiBackgroundColor.get()];
896
897     // Update the indicator style based on the lightness/darkness of the background color.
898     double hue, saturation, lightness;
899     color.getHSL(hue, saturation, lightness);
900     if (lightness <= .5 && color.alpha() > 0)
901         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
902     else
903         [_scrollView setIndicatorStyle:UIScrollViewIndicatorStyleDefault];
904 }
905
906 - (CGPoint)_adjustedContentOffset:(CGPoint)point
907 {
908     CGPoint result = point;
909     UIEdgeInsets contentInset = [self _computedContentInset];
910
911     result.x -= contentInset.left;
912     result.y -= contentInset.top;
913
914     return result;
915 }
916
917 - (UIEdgeInsets)_computedContentInset
918 {
919     if (_haveSetObscuredInsets)
920         return _obscuredInsets;
921
922     return [_scrollView contentInset];
923 }
924
925 - (void)_processDidExit
926 {
927     if (!_customContentView && _dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
928         NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
929         [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
930         [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
931         [_resizeAnimationView removeFromSuperview];
932         _resizeAnimationView = nil;
933
934         _resizeAnimationTransformAdjustments = CATransform3DIdentity;
935     }
936     [_contentView setFrame:self.bounds];
937     [_scrollView setBackgroundColor:[UIColor whiteColor]];
938     [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
939     [_scrollView setZoomScale:1];
940
941     _viewportMetaTagWidth = WebCore::ViewportArguments::ValueAuto;
942     _initialScaleFactor = 1;
943     _hasCommittedLoadForMainFrame = NO;
944     _needsResetViewStateAfterCommitLoadForMainFrame = NO;
945     _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
946     [_contentView setHidden:NO];
947     _needsToRestoreExposedRect = NO;
948     _needsToRestoreUnobscuredCenter = NO;
949     _scrollViewBackgroundColor = WebCore::Color();
950     _delayUpdateVisibleContentRects = NO;
951     _hadDelayedUpdateVisibleContentRects = NO;
952 }
953
954 - (void)_didCommitLoadForMainFrame
955 {
956     _firstPaintAfterCommitLoadTransactionID = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
957
958     _hasCommittedLoadForMainFrame = YES;
959     _needsResetViewStateAfterCommitLoadForMainFrame = YES;
960 }
961
962 static CGPoint contentOffsetBoundedInValidRange(UIScrollView *scrollView, CGPoint contentOffset)
963 {
964     UIEdgeInsets contentInsets = scrollView.contentInset;
965     CGSize contentSize = scrollView.contentSize;
966     CGSize scrollViewSize = scrollView.bounds.size;
967
968     CGFloat maxHorizontalOffset = contentSize.width + contentInsets.right - scrollViewSize.width;
969     contentOffset.x = std::min(maxHorizontalOffset, contentOffset.x);
970     contentOffset.x = std::max(-contentInsets.left, contentOffset.x);
971
972     CGFloat maxVerticalOffset = contentSize.height + contentInsets.bottom - scrollViewSize.height;
973     contentOffset.y = std::min(maxVerticalOffset, contentOffset.y);
974     contentOffset.y = std::max(-contentInsets.top, contentOffset.y);
975     return contentOffset;
976 }
977
978 static void changeContentOffsetBoundedInValidRange(UIScrollView *scrollView, WebCore::FloatPoint contentOffset)
979 {
980     scrollView.contentOffset = contentOffsetBoundedInValidRange(scrollView, contentOffset);
981 }
982
983 - (WebCore::FloatRect)visibleRectInViewCoordinates
984 {
985     WebCore::FloatRect bounds = self.bounds;
986     bounds.moveBy([_scrollView contentOffset]);
987     WebCore::FloatRect contentViewBounds = [_contentView bounds];
988     bounds.intersect(contentViewBounds);
989     return bounds;
990 }
991
992 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
993 // we need to ignore differences that are within a small rounding error on floats.
994 static inline bool areEssentiallyEqualAsFloat(float a, float b)
995 {
996     return WTF::areEssentiallyEqual(a, b);
997 }
998
999 - (void)_didCommitLayerTree:(const WebKit::RemoteLayerTreeTransaction&)layerTreeTransaction
1000 {
1001     if (_customContentView)
1002         return;
1003
1004     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1005         if (layerTreeTransaction.transactionID() >= _resizeAnimationTransformTransactionID) {
1006             [_resizeAnimationView layer].sublayerTransform = _resizeAnimationTransformAdjustments;
1007             if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithDocumentHidden) {
1008                 [_contentView setHidden:NO];
1009                 [self _endAnimatedResize];
1010             }
1011         }
1012         return;
1013     }
1014
1015     CGSize newContentSize = roundScrollViewContentSize(*_page, [_contentView frame].size);
1016     [_scrollView _setContentSizePreservingContentOffsetDuringRubberband:newContentSize];
1017
1018     [_scrollView setMinimumZoomScale:layerTreeTransaction.minimumScaleFactor()];
1019     [_scrollView setMaximumZoomScale:layerTreeTransaction.maximumScaleFactor()];
1020     [_scrollView setZoomEnabled:layerTreeTransaction.allowsUserScaling()];
1021     if (!layerTreeTransaction.scaleWasSetByUIProcess() && ![_scrollView isZooming] && ![_scrollView isZoomBouncing] && ![_scrollView _isAnimatingZoom])
1022         [_scrollView setZoomScale:layerTreeTransaction.pageScaleFactor()];
1023
1024     _viewportMetaTagWidth = layerTreeTransaction.viewportMetaTagWidth();
1025     _initialScaleFactor = layerTreeTransaction.initialScaleFactor();
1026     if (![_contentView _mayDisableDoubleTapGesturesDuringSingleTap])
1027         [_contentView _setDoubleTapGesturesEnabled:self._allowsDoubleTapGestures];
1028
1029     [self _updateScrollViewBackground];
1030
1031     if (_gestureController)
1032         _gestureController->setRenderTreeSize(layerTreeTransaction.renderTreeSize());
1033
1034     if (_needsResetViewStateAfterCommitLoadForMainFrame && layerTreeTransaction.transactionID() >= _firstPaintAfterCommitLoadTransactionID) {
1035         _needsResetViewStateAfterCommitLoadForMainFrame = NO;
1036         [_scrollView setContentOffset:[self _adjustedContentOffset:CGPointZero]];
1037         [self _updateVisibleContentRects];
1038         if (_observedRenderingProgressEvents & _WKRenderingProgressEventFirstPaint)
1039             _navigationState->didFirstPaint();
1040     }
1041
1042     bool isTransactionAfterPageRestore = layerTreeTransaction.transactionID() >= _firstTransactionIDAfterPageRestore;
1043
1044     if (_needsToRestoreExposedRect && isTransactionAfterPageRestore) {
1045         _needsToRestoreExposedRect = NO;
1046
1047         if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1048             WebCore::FloatPoint exposedPosition = _exposedRectToRestore.location();
1049             exposedPosition.scale(_scaleToRestore, _scaleToRestore);
1050
1051             changeContentOffsetBoundedInValidRange(_scrollView.get(), exposedPosition);
1052             if (_gestureController)
1053                 _gestureController->didRestoreScrollPosition();
1054         }
1055         [self _updateVisibleContentRects];
1056     }
1057
1058     if (_needsToRestoreUnobscuredCenter && isTransactionAfterPageRestore) {
1059         _needsToRestoreUnobscuredCenter = NO;
1060
1061         if (areEssentiallyEqualAsFloat(contentZoomScale(self), _scaleToRestore)) {
1062             CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, _obscuredInsets);
1063             WebCore::FloatSize unobscuredContentSizeAtNewScale(unobscuredRect.size.width / _scaleToRestore, unobscuredRect.size.height / _scaleToRestore);
1064             WebCore::FloatPoint topLeftInDocumentCoordinates(_unobscuredCenterToRestore.x() - unobscuredContentSizeAtNewScale.width() / 2, _unobscuredCenterToRestore.y() - unobscuredContentSizeAtNewScale.height() / 2);
1065
1066             topLeftInDocumentCoordinates.scale(_scaleToRestore, _scaleToRestore);
1067             topLeftInDocumentCoordinates.moveBy(WebCore::FloatPoint(-_obscuredInsets.left, -_obscuredInsets.top));
1068
1069             changeContentOffsetBoundedInValidRange(_scrollView.get(), topLeftInDocumentCoordinates);
1070             if (_gestureController)
1071                 _gestureController->didRestoreScrollPosition();
1072         }
1073         [self _updateVisibleContentRects];
1074     }
1075     
1076     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1077         scrollPerfData->didCommitLayerTree([self visibleRectInViewCoordinates]);
1078 }
1079
1080 - (void)_dynamicViewportUpdateChangedTargetToScale:(double)newScale position:(CGPoint)newScrollPosition nextValidLayerTreeTransactionID:(uint64_t)nextValidLayerTreeTransactionID
1081 {
1082     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
1083         CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
1084         double currentTargetScale = animatingScaleTarget * [[_contentView layer] transform].m11;
1085         double scale = newScale / currentTargetScale;
1086         _resizeAnimationTransformAdjustments = CATransform3DMakeScale(scale, scale, 1);
1087
1088         CGPoint newContentOffset = [self _adjustedContentOffset:CGPointMake(newScrollPosition.x * newScale, newScrollPosition.y * newScale)];
1089         CGPoint currentContentOffset = [_scrollView contentOffset];
1090
1091         _resizeAnimationTransformAdjustments.m41 = (currentContentOffset.x - newContentOffset.x) / animatingScaleTarget;
1092         _resizeAnimationTransformAdjustments.m42 = (currentContentOffset.y - newContentOffset.y) / animatingScaleTarget;
1093         _resizeAnimationTransformTransactionID = nextValidLayerTreeTransactionID;
1094     }
1095 }
1096
1097 - (void)_couldNotRestorePageState
1098 {
1099     // The gestureController may be waiting for the scroll position to be restored
1100     // in order to remove the swipe snapshot. Since the scroll position could not be
1101     // restored, tell the gestureController it was restored so that it no longer waits
1102     // for it.
1103     if (_gestureController)
1104         _gestureController->didRestoreScrollPosition();
1105 }
1106
1107 - (void)_restorePageStateToExposedRect:(WebCore::FloatRect)exposedRect scale:(double)scale
1108 {
1109     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1110         return;
1111
1112     if (_customContentView)
1113         return;
1114
1115     _needsToRestoreUnobscuredCenter = NO;
1116     _needsToRestoreExposedRect = YES;
1117     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1118     _exposedRectToRestore = exposedRect;
1119     _scaleToRestore = scale;
1120 }
1121
1122 - (void)_restorePageStateToUnobscuredCenter:(WebCore::FloatPoint)center scale:(double)scale
1123 {
1124     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1125         return;
1126
1127     if (_customContentView)
1128         return;
1129
1130     _needsToRestoreExposedRect = NO;
1131     _needsToRestoreUnobscuredCenter = YES;
1132     _firstTransactionIDAfterPageRestore = downcast<WebKit::RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).nextLayerTreeTransactionID();
1133     _unobscuredCenterToRestore = center;
1134     _scaleToRestore = scale;
1135 }
1136
1137 - (PassRefPtr<WebKit::ViewSnapshot>)_takeViewSnapshot
1138 {
1139     float deviceScale = WKGetScreenScaleFactor();
1140     WebCore::FloatSize snapshotSize(self.bounds.size);
1141     snapshotSize.scale(deviceScale, deviceScale);
1142
1143     CATransform3D transform = CATransform3DMakeScale(deviceScale, deviceScale, 1);
1144
1145 #if USE(IOSURFACE)
1146     auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(snapshotSize), WebCore::ColorSpaceDeviceRGB);
1147     CARenderServerRenderLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform);
1148
1149     RefPtr<WebKit::ViewSnapshot> viewSnapshot = WebKit::ViewSnapshot::create(nullptr);
1150     WebCore::IOSurface::convertToFormat(WTF::move(surface), WebCore::IOSurface::Format::YUV422, [viewSnapshot](std::unique_ptr<WebCore::IOSurface> convertedSurface) {
1151         viewSnapshot->setSurface(WTF::move(convertedSurface));
1152     });
1153
1154     return viewSnapshot;
1155 #else
1156     uint32_t slotID = [WebKit::ViewSnapshotStore::snapshottingContext() createImageSlot:snapshotSize hasAlpha:YES];
1157
1158     if (!slotID)
1159         return nullptr;
1160
1161     CARenderServerCaptureLayerWithTransform(MACH_PORT_NULL, self.layer.context.contextId, (uint64_t)self.layer, slotID, 0, 0, &transform);
1162     WebCore::IntSize imageSize = WebCore::expandedIntSize(WebCore::FloatSize(snapshotSize));
1163     return WebKit::ViewSnapshot::create(slotID, imageSize, imageSize.width() * imageSize.height() * 4);
1164 #endif
1165 }
1166
1167 - (void)_zoomToPoint:(WebCore::FloatPoint)point atScale:(double)scale animated:(BOOL)animated
1168 {
1169     CFTimeInterval duration = 0;
1170     CGFloat zoomScale = contentZoomScale(self);
1171
1172     if (animated) {
1173         const double maximumZoomDuration = 0.4;
1174         const double minimumZoomDuration = 0.1;
1175         const double zoomDurationFactor = 0.3;
1176
1177         duration = std::min(fabs(log(zoomScale) - log(scale)) * zoomDurationFactor + minimumZoomDuration, maximumZoomDuration);
1178     }
1179
1180     if (scale != zoomScale)
1181         _page->willStartUserTriggeredZooming();
1182
1183     [_scrollView _zoomToCenter:point scale:scale duration:duration];
1184 }
1185
1186 - (void)_zoomToRect:(WebCore::FloatRect)targetRect atScale:(double)scale origin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1187 {
1188     // FIXME: Some of this could be shared with _scrollToRect.
1189     const double visibleRectScaleChange = contentZoomScale(self) / scale;
1190     const WebCore::FloatRect visibleRect([self convertRect:self.bounds toView:self._currentContentView]);
1191     const WebCore::FloatRect unobscuredRect([self _contentRectForUserInteraction]);
1192
1193     const WebCore::FloatSize topLeftObscuredInsetAfterZoom((unobscuredRect.minXMinYCorner() - visibleRect.minXMinYCorner()) * visibleRectScaleChange);
1194     const WebCore::FloatSize bottomRightObscuredInsetAfterZoom((visibleRect.maxXMaxYCorner() - unobscuredRect.maxXMaxYCorner()) * visibleRectScaleChange);
1195
1196     const WebCore::FloatSize unobscuredRectSizeAfterZoom(unobscuredRect.size() * visibleRectScaleChange);
1197
1198     // Center to the target rect.
1199     WebCore::FloatPoint unobscuredRectLocationAfterZoom = targetRect.location() - (unobscuredRectSizeAfterZoom - targetRect.size()) * 0.5;
1200
1201     // Center to the tap point instead in case the target rect won't fit in a direction.
1202     if (targetRect.width() > unobscuredRectSizeAfterZoom.width())
1203         unobscuredRectLocationAfterZoom.setX(origin.x() - unobscuredRectSizeAfterZoom.width() / 2);
1204     if (targetRect.height() > unobscuredRectSizeAfterZoom.height())
1205         unobscuredRectLocationAfterZoom.setY(origin.y() - unobscuredRectSizeAfterZoom.height() / 2);
1206
1207     // We have computed where we want the unobscured rect to be. Now adjust for the obscuring insets.
1208     WebCore::FloatRect visibleRectAfterZoom(unobscuredRectLocationAfterZoom, unobscuredRectSizeAfterZoom);
1209     visibleRectAfterZoom.move(-topLeftObscuredInsetAfterZoom);
1210     visibleRectAfterZoom.expand(topLeftObscuredInsetAfterZoom + bottomRightObscuredInsetAfterZoom);
1211
1212     [self _zoomToPoint:visibleRectAfterZoom.center() atScale:scale animated:animated];
1213 }
1214
1215 static WebCore::FloatPoint constrainContentOffset(WebCore::FloatPoint contentOffset, WebCore::FloatSize contentSize, WebCore::FloatSize unobscuredContentSize)
1216 {
1217     WebCore::FloatSize maximumContentOffset = contentSize - unobscuredContentSize;
1218     contentOffset = contentOffset.shrunkTo(WebCore::FloatPoint(maximumContentOffset.width(), maximumContentOffset.height()));
1219     contentOffset = contentOffset.expandedTo(WebCore::FloatPoint());
1220     return contentOffset;
1221 }
1222
1223 - (void)_scrollToContentOffset:(WebCore::FloatPoint)contentOffsetInPageCoordinates scrollOrigin:(WebCore::IntPoint)scrollOrigin
1224 {
1225     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing)
1226         return;
1227
1228     WebCore::FloatPoint contentOffsetRespectingOrigin = scrollOrigin + toFloatSize(contentOffsetInPageCoordinates);
1229
1230     WebCore::FloatPoint scaledOffset = contentOffsetRespectingOrigin;
1231     CGFloat zoomScale = contentZoomScale(self);
1232     scaledOffset.scale(zoomScale, zoomScale);
1233
1234     CGPoint contentOffsetInScrollViewCoordinates = [self _adjustedContentOffset:scaledOffset];
1235     contentOffsetInScrollViewCoordinates = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffsetInScrollViewCoordinates);
1236
1237     [_scrollView _stopScrollingAndZoomingAnimations];
1238
1239     if (!CGPointEqualToPoint(contentOffsetInScrollViewCoordinates, [_scrollView contentOffset]))
1240         [_scrollView setContentOffset:contentOffsetInScrollViewCoordinates];
1241     else {
1242         // If we haven't changed anything, there would not be any VisibleContentRect update sent to the content.
1243         // The WebProcess would keep the invalid contentOffset as its scroll position.
1244         // To synchronize the WebProcess with what is on screen, we send the VisibleContentRect again.
1245         _page->resendLastVisibleContentRects();
1246     }
1247 }
1248
1249 - (BOOL)_scrollToRect:(WebCore::FloatRect)targetRect origin:(WebCore::FloatPoint)origin minimumScrollDistance:(float)minimumScrollDistance
1250 {
1251     WebCore::FloatRect unobscuredContentRect([self _contentRectForUserInteraction]);
1252     WebCore::FloatPoint unobscuredContentOffset = unobscuredContentRect.location();
1253     WebCore::FloatSize contentSize([self._currentContentView bounds].size);
1254
1255     // Center the target rect in the scroll view.
1256     // If the target doesn't fit in the scroll view, center on the gesture location instead.
1257     WebCore::FloatPoint newUnobscuredContentOffset;
1258     if (targetRect.width() <= unobscuredContentRect.width())
1259         newUnobscuredContentOffset.setX(targetRect.x() - (unobscuredContentRect.width() - targetRect.width()) / 2);
1260     else
1261         newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1262     if (targetRect.height() <= unobscuredContentRect.height())
1263         newUnobscuredContentOffset.setY(targetRect.y() - (unobscuredContentRect.height() - targetRect.height()) / 2);
1264     else
1265         newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1266     newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1267
1268     if (unobscuredContentOffset == newUnobscuredContentOffset) {
1269         if (targetRect.width() > unobscuredContentRect.width())
1270             newUnobscuredContentOffset.setX(origin.x() - unobscuredContentRect.width() / 2);
1271         if (targetRect.height() > unobscuredContentRect.height())
1272             newUnobscuredContentOffset.setY(origin.y() - unobscuredContentRect.height() / 2);
1273         newUnobscuredContentOffset = constrainContentOffset(newUnobscuredContentOffset, contentSize, unobscuredContentRect.size());
1274     }
1275
1276     WebCore::FloatSize scrollViewOffsetDelta = newUnobscuredContentOffset - unobscuredContentOffset;
1277     scrollViewOffsetDelta.scale(contentZoomScale(self));
1278
1279     float scrollDistance = scrollViewOffsetDelta.diagonalLength();
1280     if (scrollDistance < minimumScrollDistance)
1281         return false;
1282
1283     [_contentView willStartZoomOrScroll];
1284
1285     [_scrollView setContentOffset:([_scrollView contentOffset] + scrollViewOffsetDelta) animated:YES];
1286     return true;
1287 }
1288
1289 - (void)_scrollByOffset:(WebCore::FloatPoint)offset
1290 {
1291     CGPoint currentOffset = ([_scrollView _isAnimatingScroll]) ? [_scrollView _animatedTargetOffset] : [_scrollView contentOffset];
1292
1293     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), currentOffset + offset);
1294     
1295     if (CGPointEqualToPoint(boundedOffset, currentOffset))
1296         return;
1297     [_contentView willStartZoomOrScroll];
1298     [_scrollView setContentOffset:boundedOffset animated:YES];
1299 }
1300
1301 - (void)_zoomOutWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1302 {
1303     [self _zoomToPoint:origin atScale:[_scrollView minimumZoomScale] animated:animated];
1304 }
1305
1306 - (void)_zoomToInitialScaleWithOrigin:(WebCore::FloatPoint)origin animated:(BOOL)animated
1307 {
1308     ASSERT(_initialScaleFactor > 0);
1309     [self _zoomToPoint:origin atScale:_initialScaleFactor animated:animated];
1310 }
1311
1312 // focusedElementRect and selectionRect are both in document coordinates.
1313 - (void)_zoomToFocusRect:(WebCore::FloatRect)focusedElementRectInDocumentCoordinates selectionRect:(WebCore::FloatRect)selectionRectInDocumentCoordinates fontSize:(float)fontSize minimumScale:(double)minimumScale maximumScale:(double)maximumScale allowScaling:(BOOL)allowScaling forceScroll:(BOOL)forceScroll
1314 {
1315     const double WKWebViewStandardFontSize = 16;
1316     const double kMinimumHeightToShowContentAboveKeyboard = 106;
1317     const CFTimeInterval UIWebFormAnimationDuration = 0.25;
1318     const double CaretOffsetFromWindowEdge = 20;
1319
1320     // Zoom around the element's bounding frame. We use a "standard" size to determine the proper frame.
1321     double scale = allowScaling ? std::min(std::max(WKWebViewStandardFontSize / fontSize, minimumScale), maximumScale) : contentZoomScale(self);
1322     CGFloat documentWidth = [_contentView bounds].size.width;
1323     scale = CGRound(documentWidth * scale) / documentWidth;
1324
1325     UIWindow *window = [_scrollView window];
1326
1327     WebCore::FloatRect focusedElementRectInNewScale = focusedElementRectInDocumentCoordinates;
1328     focusedElementRectInNewScale.scale(scale);
1329     focusedElementRectInNewScale.moveBy([_contentView frame].origin);
1330
1331     // Find the portion of the view that is visible on the screen.
1332     UIViewController *topViewController = [[[_scrollView _viewControllerForAncestor] _rootAncestorViewController] _viewControllerForSupportedInterfaceOrientations];
1333     UIView *fullScreenView = topViewController.view;
1334     if (!fullScreenView)
1335         fullScreenView = window;
1336
1337     CGRect unobscuredScrollViewRectInWebViewCoordinates = UIEdgeInsetsInsetRect([self bounds], _obscuredInsets);
1338     CGRect visibleScrollViewBoundsInWebViewCoordinates = CGRectIntersection(unobscuredScrollViewRectInWebViewCoordinates, [fullScreenView convertRect:[fullScreenView bounds] toView:self]);
1339     CGRect formAssistantFrameInWebViewCoordinates = [window convertRect:_inputViewBounds toView:self];
1340     CGRect intersectionBetweenScrollViewAndFormAssistant = CGRectIntersection(visibleScrollViewBoundsInWebViewCoordinates, formAssistantFrameInWebViewCoordinates);
1341     CGSize visibleSize = visibleScrollViewBoundsInWebViewCoordinates.size;
1342
1343     CGFloat visibleOffsetFromTop = 0;
1344     if (!CGRectIsEmpty(intersectionBetweenScrollViewAndFormAssistant)) {
1345         CGFloat heightVisibleAboveFormAssistant = CGRectGetMinY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1346         CGFloat heightVisibleBelowFormAssistant = CGRectGetMaxY(visibleScrollViewBoundsInWebViewCoordinates) - CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant);
1347
1348         if (heightVisibleAboveFormAssistant >= kMinimumHeightToShowContentAboveKeyboard || heightVisibleBelowFormAssistant < heightVisibleAboveFormAssistant)
1349             visibleSize.height = heightVisibleAboveFormAssistant;
1350         else {
1351             visibleSize.height = heightVisibleBelowFormAssistant;
1352             visibleOffsetFromTop = CGRectGetMaxY(intersectionBetweenScrollViewAndFormAssistant) - CGRectGetMinY(visibleScrollViewBoundsInWebViewCoordinates);
1353         }
1354     }
1355
1356     BOOL selectionRectIsNotNull = !selectionRectInDocumentCoordinates.isZero();
1357     if (!forceScroll) {
1358         CGRect currentlyVisibleRegionInWebViewCoordinates;
1359         currentlyVisibleRegionInWebViewCoordinates.origin = unobscuredScrollViewRectInWebViewCoordinates.origin;
1360         currentlyVisibleRegionInWebViewCoordinates.origin.y += visibleOffsetFromTop;
1361         currentlyVisibleRegionInWebViewCoordinates.size = visibleSize;
1362
1363         // Don't bother scrolling if the entire node is already visible, whether or not we got a selectionRect.
1364         if (CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:focusedElementRectInDocumentCoordinates fromView:_contentView.get()]))
1365             return;
1366
1367         // Don't bother scrolling if we have a valid selectionRect and it is already visible.
1368         if (selectionRectIsNotNull && CGRectContainsRect(currentlyVisibleRegionInWebViewCoordinates, [self convertRect:selectionRectInDocumentCoordinates fromView:_contentView.get()]))
1369             return;
1370     }
1371
1372     // We want to zoom to the left/top corner of the DOM node, with as much spacing on all sides as we
1373     // can get based on the visible area after zooming (workingFrame).  The spacing in either dimension is half the
1374     // difference between the size of the DOM node and the size of the visible frame.
1375     CGFloat horizontalSpaceInWebViewCoordinates = std::max((visibleSize.width - focusedElementRectInNewScale.width()) / 2.0, 0.0);
1376     CGFloat verticalSpaceInWebViewCoordinates = std::max((visibleSize.height - focusedElementRectInNewScale.height()) / 2.0, 0.0);
1377
1378     CGPoint topLeft;
1379     topLeft.x = focusedElementRectInNewScale.x() - horizontalSpaceInWebViewCoordinates;
1380     topLeft.y = focusedElementRectInNewScale.y() - verticalSpaceInWebViewCoordinates - visibleOffsetFromTop;
1381
1382     CGFloat minimumAllowableHorizontalOffsetInWebViewCoordinates = -INFINITY;
1383     CGFloat minimumAllowableVerticalOffsetInWebViewCoordinates = -INFINITY;
1384     if (selectionRectIsNotNull) {
1385         WebCore::FloatRect selectionRectInNewScale = selectionRectInDocumentCoordinates;
1386         selectionRectInNewScale.scale(scale);
1387         selectionRectInNewScale.moveBy([_contentView frame].origin);
1388         minimumAllowableHorizontalOffsetInWebViewCoordinates = CGRectGetMaxX(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.width;
1389         minimumAllowableVerticalOffsetInWebViewCoordinates = CGRectGetMaxY(selectionRectInNewScale) + CaretOffsetFromWindowEdge - visibleSize.height - visibleOffsetFromTop;
1390     }
1391
1392     WebCore::FloatRect documentBoundsInNewScale = [_contentView bounds];
1393     documentBoundsInNewScale.scale(scale);
1394     documentBoundsInNewScale.moveBy([_contentView frame].origin);
1395
1396     // Constrain the left edge in document coordinates so that:
1397     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
1398     //  - it isn't so great that the document's right edge is less than the right edge of the screen
1399     if (selectionRectIsNotNull && topLeft.x < minimumAllowableHorizontalOffsetInWebViewCoordinates)
1400         topLeft.x = minimumAllowableHorizontalOffsetInWebViewCoordinates;
1401     else {
1402         CGFloat maximumAllowableHorizontalOffset = CGRectGetMaxX(documentBoundsInNewScale) - visibleSize.width;
1403         if (topLeft.x > maximumAllowableHorizontalOffset)
1404             topLeft.x = maximumAllowableHorizontalOffset;
1405     }
1406
1407     // Constrain the top edge in document coordinates so that:
1408     //  - it isn't so small that the scrollVisibleRect isn't visible on the screen
1409     //  - it isn't so great that the document's bottom edge is higher than the top of the form assistant
1410     if (selectionRectIsNotNull && topLeft.y < minimumAllowableVerticalOffsetInWebViewCoordinates)
1411         topLeft.y = minimumAllowableVerticalOffsetInWebViewCoordinates;
1412     else {
1413         CGFloat maximumAllowableVerticalOffset = CGRectGetMaxY(documentBoundsInNewScale) - visibleSize.height;
1414         if (topLeft.y > maximumAllowableVerticalOffset)
1415             topLeft.y = maximumAllowableVerticalOffset;
1416     }
1417
1418     WebCore::FloatPoint newCenter = CGPointMake(topLeft.x + unobscuredScrollViewRectInWebViewCoordinates.size.width / 2.0, topLeft.y + unobscuredScrollViewRectInWebViewCoordinates.size.height / 2.0);
1419
1420     if (scale != contentZoomScale(self))
1421         _page->willStartUserTriggeredZooming();
1422
1423     // The newCenter has been computed in the new scale, but _zoomToCenter expected the center to be in the original scale.
1424     newCenter.scale(1 / scale, 1 / scale);
1425     [_scrollView _zoomToCenter:newCenter
1426                         scale:scale
1427                      duration:UIWebFormAnimationDuration
1428                         force:YES];
1429 }
1430
1431 - (CGFloat)_targetContentZoomScaleForRect:(const WebCore::FloatRect&)targetRect currentScale:(double)currentScale fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale
1432 {
1433     WebCore::FloatSize unobscuredContentSize([self _contentRectForUserInteraction].size);
1434     double horizontalScale = unobscuredContentSize.width() * currentScale / targetRect.width();
1435     double verticalScale = unobscuredContentSize.height() * currentScale / targetRect.height();
1436
1437     horizontalScale = std::min(std::max(horizontalScale, minimumScale), maximumScale);
1438     verticalScale = std::min(std::max(verticalScale, minimumScale), maximumScale);
1439
1440     return fitEntireRect ? std::min(horizontalScale, verticalScale) : horizontalScale;
1441 }
1442
1443 - (BOOL)_zoomToRect:(WebCore::FloatRect)targetRect withOrigin:(WebCore::FloatPoint)origin fitEntireRect:(BOOL)fitEntireRect minimumScale:(double)minimumScale maximumScale:(double)maximumScale minimumScrollDistance:(float)minimumScrollDistance
1444 {
1445     const float maximumScaleFactorDeltaForPanScroll = 0.02;
1446
1447     double currentScale = contentZoomScale(self);
1448     double targetScale = [self _targetContentZoomScaleForRect:targetRect currentScale:currentScale fitEntireRect:fitEntireRect minimumScale:minimumScale maximumScale:maximumScale];
1449
1450     if (fabs(targetScale - currentScale) < maximumScaleFactorDeltaForPanScroll) {
1451         if ([self _scrollToRect:targetRect origin:origin minimumScrollDistance:minimumScrollDistance])
1452             return true;
1453     } else if (targetScale != currentScale) {
1454         [self _zoomToRect:targetRect atScale:targetScale origin:origin animated:YES];
1455         return true;
1456     }
1457     
1458     return false;
1459 }
1460
1461 - (void)didMoveToWindow
1462 {
1463     _page->viewStateDidChange(WebCore::ViewState::AllFlags);
1464 }
1465
1466 - (void)setOpaque:(BOOL)opaque
1467 {
1468     BOOL oldOpaque = self.opaque;
1469
1470     [super setOpaque:opaque];
1471     [_contentView setOpaque:opaque];
1472
1473     if (oldOpaque == opaque)
1474         return;
1475
1476     _page->setDrawsBackground(opaque);
1477     [self _updateScrollViewBackground];
1478 }
1479
1480 - (void)setBackgroundColor:(UIColor *)backgroundColor
1481 {
1482     [super setBackgroundColor:backgroundColor];
1483     [_contentView setBackgroundColor:backgroundColor];
1484 }
1485
1486 #pragma mark - UIScrollViewDelegate
1487
1488 - (BOOL)usesStandardContentView
1489 {
1490     return !_customContentView;
1491 }
1492
1493 - (CGSize)scrollView:(UIScrollView*)scrollView contentSizeForZoomScale:(CGFloat)scale withProposedSize:(CGSize)proposedSize
1494 {
1495     return roundScrollViewContentSize(*_page, proposedSize);
1496 }
1497
1498 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
1499 {
1500     ASSERT(_scrollView == scrollView);
1501
1502     if (_customContentView)
1503         return _customContentView.get();
1504
1505     return _contentView.get();
1506 }
1507
1508 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
1509 {
1510     if (![self usesStandardContentView])
1511         return;
1512
1513     if (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan) {
1514         _page->willStartUserTriggeredZooming();
1515         [_contentView scrollViewWillStartPanOrPinchGesture];
1516     }
1517     [_contentView willStartZoomOrScroll];
1518 }
1519
1520 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
1521 {
1522     if (![self usesStandardContentView])
1523         return;
1524
1525     if (scrollView.panGestureRecognizer.state == UIGestureRecognizerStateBegan)
1526         [_contentView scrollViewWillStartPanOrPinchGesture];
1527
1528     [_contentView willStartZoomOrScroll];
1529 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1530     // FIXME: We will want to detect whether snapping will occur before beginning to drag. See WebPageProxy::didCommitLayerTree.
1531     WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
1532     ASSERT(scrollView == _scrollView.get());
1533     CGFloat scrollDecelerationFactor = (coordinator && coordinator->shouldSetScrollViewDecelerationRateFast()) ? UIScrollViewDecelerationRateFast : [_scrollView preferredScrollDecelerationFactor];
1534     scrollView.horizontalScrollDecelerationFactor = scrollDecelerationFactor;
1535     scrollView.verticalScrollDecelerationFactor = scrollDecelerationFactor;
1536 #endif
1537 }
1538
1539 - (void)_didFinishScrolling
1540 {
1541     if (![self usesStandardContentView])
1542         return;
1543
1544     [self _updateVisibleContentRects];
1545     [_contentView didFinishScrolling];
1546 }
1547
1548 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
1549 {
1550     // Work around <rdar://problem/16374753> by avoiding deceleration while
1551     // zooming. We'll animate to the right place once the zoom finishes.
1552     if ([scrollView isZooming])
1553         *targetContentOffset = [scrollView contentOffset];
1554 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1555     if (WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy()) {
1556         // FIXME: Here, I'm finding the maximum horizontal/vertical scroll offsets. There's probably a better way to do this.
1557         CGSize maxScrollOffsets = CGSizeMake(scrollView.contentSize.width - scrollView.bounds.size.width, scrollView.contentSize.height - scrollView.bounds.size.height);
1558         
1559         CGRect fullViewRect = self.bounds;
1560
1561         UIEdgeInsets contentInset;
1562
1563         id<WKUIDelegatePrivate> uiDelegatePrivate = static_cast<id <WKUIDelegatePrivate>>([self UIDelegate]);
1564         if ([uiDelegatePrivate respondsToSelector:@selector(_webView:finalObscuredInsetsForScrollView:withVelocity:targetContentOffset:)])
1565             contentInset = [uiDelegatePrivate _webView:self finalObscuredInsetsForScrollView:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
1566         else
1567             contentInset = [self _computedContentInset];
1568
1569         CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, contentInset);
1570         
1571         coordinator->adjustTargetContentOffsetForSnapping(maxScrollOffsets, velocity, unobscuredRect.origin.y, targetContentOffset);
1572     }
1573 #endif
1574 }
1575
1576 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
1577 {
1578     // If we're decelerating, scroll offset will be updated when scrollViewDidFinishDecelerating: is called.
1579     if (!decelerate)
1580         [self _didFinishScrolling];
1581 }
1582
1583 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
1584 {
1585     [self _didFinishScrolling];
1586 }
1587
1588 - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
1589 {
1590     [self _didFinishScrolling];
1591 }
1592
1593 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
1594 {
1595     if (![self usesStandardContentView])
1596         [_customContentView scrollViewDidScroll:(UIScrollView *)scrollView];
1597
1598     [self _updateVisibleContentRects];
1599     
1600     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
1601         scrollPerfData->didScroll([self visibleRectInViewCoordinates]);
1602 }
1603
1604 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
1605 {
1606     [self _updateScrollViewBackground];
1607     [self _updateVisibleContentRects];
1608 }
1609
1610 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
1611 {
1612     ASSERT(scrollView == _scrollView);
1613     [self _updateVisibleContentRects];
1614     [_contentView didZoomToScale:scale];
1615 }
1616
1617 - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
1618 {
1619     [self _didFinishScrolling];
1620 }
1621
1622 - (void)_scrollViewDidInterruptDecelerating:(UIScrollView *)scrollView
1623 {
1624     if (![self usesStandardContentView])
1625         return;
1626
1627     [_contentView didInterruptScrolling];
1628     [self _updateVisibleContentRects];
1629 }
1630
1631 - (void)_frameOrBoundsChanged
1632 {
1633     CGRect bounds = self.bounds;
1634     [_scrollView setFrame:bounds];
1635
1636     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing) {
1637         if (!_overridesMinimumLayoutSize)
1638             _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(bounds.size));
1639         if (!_overridesMaximumUnobscuredSize)
1640             _page->setMaximumUnobscuredSize(WebCore::FloatSize(bounds.size));
1641         if (WebKit::DrawingAreaProxy* drawingArea = _page->drawingArea())
1642             drawingArea->setSize(WebCore::IntSize(bounds.size), WebCore::IntSize(), WebCore::IntSize());
1643     }
1644
1645     [_customContentView web_setMinimumSize:bounds.size];
1646     [self _updateVisibleContentRects];
1647 }
1648
1649 // 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.
1650 - (CGRect)_contentRectForUserInteraction
1651 {
1652     // FIXME: handle split keyboard.
1653     UIEdgeInsets obscuredInsets = _obscuredInsets;
1654     obscuredInsets.bottom = std::max(_obscuredInsets.bottom, _inputViewBounds.size.height);
1655     CGRect unobscuredRect = UIEdgeInsetsInsetRect(self.bounds, obscuredInsets);
1656     return [self convertRect:unobscuredRect toView:self._currentContentView];
1657 }
1658
1659 // Ideally UIScrollView would expose this for us: <rdar://problem/21394567>.
1660 - (BOOL)_scrollViewIsRubberBanding
1661 {
1662     float deviceScaleFactor = _page->deviceScaleFactor();
1663
1664     CGPoint contentOffset = [_scrollView contentOffset];
1665     CGPoint boundedOffset = contentOffsetBoundedInValidRange(_scrollView.get(), contentOffset);
1666     return !pointsEqualInDevicePixels(contentOffset, boundedOffset, deviceScaleFactor);
1667 }
1668
1669 - (void)_updateVisibleContentRects
1670 {
1671     if (![self usesStandardContentView]) {
1672         [_customContentView web_computedContentInsetDidChange];
1673         return;
1674     }
1675
1676     if (_delayUpdateVisibleContentRects) {
1677         _hadDelayedUpdateVisibleContentRects = YES;
1678         return;
1679     }
1680
1681     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing
1682         || _needsResetViewStateAfterCommitLoadForMainFrame
1683         || [_scrollView isZoomBouncing]
1684         || _currentlyAdjustingScrollViewInsetsForKeyboard)
1685         return;
1686
1687     CGRect fullViewRect = self.bounds;
1688     CGRect visibleRectInContentCoordinates = _frozenVisibleContentRect ? _frozenVisibleContentRect.value() : [self convertRect:fullViewRect toView:_contentView.get()];
1689
1690     UIEdgeInsets computedContentInsetUnadjustedForKeyboard = [self _computedContentInset];
1691     if (!_haveSetObscuredInsets)
1692         computedContentInsetUnadjustedForKeyboard.bottom -= _totalScrollViewBottomInsetAdjustmentForKeyboard;
1693
1694     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
1695     CGRect unobscuredRectInContentCoordinates = _frozenUnobscuredContentRect ? _frozenUnobscuredContentRect.value() : [self convertRect:unobscuredRect toView:_contentView.get()];
1696
1697     CGFloat scaleFactor = contentZoomScale(self);
1698
1699     BOOL isStableState = !(_isChangingObscuredInsetsInteractively || [_scrollView isDragging] || [_scrollView isDecelerating] || [_scrollView isZooming] || [_scrollView _isAnimatingZoom] || [_scrollView _isScrollingToTop] || [self _scrollViewIsRubberBanding]);
1700
1701     // FIXME: this can be made static after we stop supporting iOS 8.x.
1702     if (isStableState && [_scrollView respondsToSelector:@selector(_isInterruptingDeceleration)])
1703         isStableState = ![_scrollView performSelector:@selector(_isInterruptingDeceleration)];
1704
1705 #if ENABLE(CSS_SCROLL_SNAP) && ENABLE(ASYNC_SCROLLING)
1706     if (isStableState) {
1707         WebKit::RemoteScrollingCoordinatorProxy* coordinator = _page->scrollingCoordinatorProxy();
1708         if (coordinator && coordinator->hasActiveSnapPoint()) {
1709             CGRect fullViewRect = self.bounds;
1710             CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, computedContentInsetUnadjustedForKeyboard);
1711             
1712             CGPoint currentPoint = [_scrollView contentOffset];
1713             CGPoint activePoint = coordinator->nearestActiveContentInsetAdjustedSnapPoint(unobscuredRect.origin.y, currentPoint);
1714
1715             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
1716                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
1717                 dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
1718                     [strongScrollView setContentOffset:activePoint animated:NO];
1719                 });
1720             }
1721         }
1722     }
1723 #endif
1724     
1725     [_contentView didUpdateVisibleRect:visibleRectInContentCoordinates
1726         unobscuredRect:unobscuredRectInContentCoordinates
1727         unobscuredRectInScrollViewCoordinates:unobscuredRect
1728         scale:scaleFactor minimumScale:[_scrollView minimumZoomScale]
1729         inStableState:isStableState isChangingObscuredInsetsInteractively:_isChangingObscuredInsetsInteractively];
1730 }
1731
1732 - (void)_didFinishLoadForMainFrame
1733 {
1734     if (_gestureController)
1735         _gestureController->didFinishLoadForMainFrame();
1736 }
1737
1738 - (void)_didFailLoadForMainFrame
1739 {
1740     if (_gestureController)
1741         _gestureController->didFailLoadForMainFrame();
1742 }
1743
1744 - (void)_didSameDocumentNavigationForMainFrame:(WebKit::SameDocumentNavigationType)navigationType
1745 {
1746     [_customContentView web_didSameDocumentNavigation:toAPI(navigationType)];
1747
1748     if (_gestureController)
1749         _gestureController->didSameDocumentNavigationForMainFrame(navigationType);
1750 }
1751
1752 - (void)_keyboardChangedWithInfo:(NSDictionary *)keyboardInfo adjustScrollView:(BOOL)adjustScrollView
1753 {
1754     NSValue *endFrameValue = [keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
1755     if (!endFrameValue)
1756         return;
1757
1758     // The keyboard rect is always in screen coordinates. In the view services case the window does not
1759     // have the interface orientation rotation transformation; its host does. So, it makes no sense to
1760     // clip the keyboard rect against its screen.
1761     if ([[self window] _isHostedInAnotherProcess])
1762         _inputViewBounds = [self.window convertRect:[endFrameValue CGRectValue] fromWindow:nil];
1763     else
1764         _inputViewBounds = [self.window convertRect:CGRectIntersection([endFrameValue CGRectValue], self.window.screen.bounds) fromWindow:nil];
1765
1766     if (adjustScrollView) {
1767         CGFloat bottomInsetBeforeAdjustment = [_scrollView contentInset].bottom;
1768         TemporaryChange<BOOL> insetAdjustmentGuard(_currentlyAdjustingScrollViewInsetsForKeyboard, YES);
1769         [_scrollView _adjustForAutomaticKeyboardInfo:keyboardInfo animated:YES lastAdjustment:&_lastAdjustmentForScroller];
1770         CGFloat bottomInsetAfterAdjustment = [_scrollView contentInset].bottom;
1771         if (bottomInsetBeforeAdjustment != bottomInsetAfterAdjustment)
1772             _totalScrollViewBottomInsetAdjustmentForKeyboard += bottomInsetAfterAdjustment - bottomInsetBeforeAdjustment;
1773     }
1774
1775     [self _updateVisibleContentRects];
1776 }
1777
1778 - (BOOL)_shouldUpdateKeyboardWithInfo:(NSDictionary *)keyboardInfo
1779 {
1780     if ([_contentView isAssistingNode])
1781         return YES;
1782
1783     NSNumber *isLocalKeyboard = [keyboardInfo valueForKey:UIKeyboardIsLocalUserInfoKey];
1784     return isLocalKeyboard && !isLocalKeyboard.boolValue;
1785 }
1786
1787 - (void)_keyboardWillChangeFrame:(NSNotification *)notification
1788 {
1789     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
1790         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1791 }
1792
1793 - (void)_keyboardDidChangeFrame:(NSNotification *)notification
1794 {
1795     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:NO];
1796 }
1797
1798 - (void)_keyboardWillShow:(NSNotification *)notification
1799 {
1800     if ([self _shouldUpdateKeyboardWithInfo:notification.userInfo])
1801         [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1802 }
1803
1804 - (void)_keyboardWillHide:(NSNotification *)notification
1805 {
1806     // Ignore keyboard will hide notifications sent during rotation. They're just there for
1807     // backwards compatibility reasons and processing the will hide notification would
1808     // temporarily screw up the the unobscured view area.
1809     if ([[UIPeripheralHost sharedInstance] rotationState])
1810         return;
1811
1812     [self _keyboardChangedWithInfo:notification.userInfo adjustScrollView:YES];
1813 }
1814
1815 - (void)_windowDidRotate:(NSNotification *)notification
1816 {
1817     if (!_overridesInterfaceOrientation)
1818         _page->setDeviceOrientation(deviceOrientation());
1819 }
1820
1821 - (void)_contentSizeCategoryDidChange:(NSNotification *)notification
1822 {
1823     _page->contentSizeCategoryDidChange([self _contentSizeCategory]);
1824 }
1825
1826 - (NSString *)_contentSizeCategory
1827 {
1828     return [[UIApplication sharedApplication] preferredContentSizeCategory];
1829 }
1830
1831 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
1832 {
1833     if (_allowsBackForwardNavigationGestures == allowsBackForwardNavigationGestures)
1834         return;
1835
1836     _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
1837
1838     if (allowsBackForwardNavigationGestures) {
1839         if (!_gestureController) {
1840             _gestureController = std::make_unique<WebKit::ViewGestureController>(*_page);
1841             _gestureController->installSwipeHandler(self, [self scrollView]);
1842             _gestureController->setAlternateBackForwardListSourceView([_configuration _alternateWebViewForNavigationGestures]);
1843         }
1844     } else
1845         _gestureController = nullptr;
1846
1847     _page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
1848 }
1849
1850 - (BOOL)allowsBackForwardNavigationGestures
1851 {
1852     return _allowsBackForwardNavigationGestures;
1853 }
1854
1855 - (void)_navigationGestureDidBegin
1856 {
1857     // During a back/forward swipe, there's a view interposed between this view and the content view that has
1858     // an offset and animation on it, which results in computing incorrect rectangles. Work around by using
1859     // frozen rects during swipes.
1860     CGRect fullViewRect = self.bounds;
1861     CGRect unobscuredRect = UIEdgeInsetsInsetRect(fullViewRect, [self _computedContentInset]);
1862
1863     _frozenVisibleContentRect = [self convertRect:fullViewRect toView:_contentView.get()];
1864     _frozenUnobscuredContentRect = [self convertRect:unobscuredRect toView:_contentView.get()];
1865 }
1866
1867 - (void)_navigationGestureDidEnd
1868 {
1869     _frozenVisibleContentRect = Nullopt;
1870     _frozenUnobscuredContentRect = Nullopt;
1871 }
1872
1873 #endif // PLATFORM(IOS)
1874
1875 #pragma mark OS X-specific methods
1876
1877 #if PLATFORM(MAC)
1878
1879 - (BOOL)becomeFirstResponder
1880 {
1881     return [[self window] makeFirstResponder: _wkView.get()];
1882 }
1883
1884 - (BOOL)acceptsFirstResponder
1885 {
1886     return [_wkView acceptsFirstResponder];
1887 }
1888
1889 - (void)resizeSubviewsWithOldSize:(NSSize)oldSize
1890 {
1891     [_wkView setFrame:self.bounds];
1892 }
1893
1894 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
1895 {
1896     [_wkView setAllowsBackForwardNavigationGestures:allowsBackForwardNavigationGestures];
1897 }
1898
1899 - (BOOL)allowsBackForwardNavigationGestures
1900 {
1901     return [_wkView allowsBackForwardNavigationGestures];
1902 }
1903
1904 - (void)setAllowsMagnification:(BOOL)allowsMagnification
1905 {
1906     [_wkView setAllowsMagnification:allowsMagnification];
1907 }
1908
1909 - (BOOL)allowsMagnification
1910 {
1911     return [_wkView allowsMagnification];
1912 }
1913
1914 - (void)setMagnification:(CGFloat)magnification
1915 {
1916     [_wkView setMagnification:magnification];
1917 }
1918
1919 - (CGFloat)magnification
1920 {
1921     return [_wkView magnification];
1922 }
1923
1924 - (void)setMagnification:(CGFloat)magnification centeredAtPoint:(CGPoint)point
1925 {
1926     [_wkView setMagnification:magnification centeredAtPoint:NSPointFromCGPoint(point)];
1927 }
1928
1929 - (BOOL)_ignoresNonWheelEvents
1930 {
1931     return [_wkView _ignoresNonWheelEvents];
1932 }
1933
1934 - (void)_setIgnoresNonWheelEvents:(BOOL)ignoresNonWheelEvents
1935 {
1936     [_wkView _setIgnoresNonWheelEvents:ignoresNonWheelEvents];
1937 }
1938
1939 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1940 {
1941     return [_wkView draggingEntered:sender];
1942 }
1943
1944 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1945 {
1946     return [_wkView draggingUpdated:sender];
1947 }
1948
1949 - (void)draggingExited:(id <NSDraggingInfo>)sender
1950 {
1951     [_wkView draggingExited:sender];
1952 }
1953
1954 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
1955 {
1956     return [_wkView prepareForDragOperation:sender];
1957 }
1958
1959 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1960 {
1961     return [_wkView performDragOperation:sender];
1962 }
1963
1964 - (CGSize)intrinsicContentSize
1965 {
1966     return _intrinsicContentSize;
1967 }
1968
1969 - (void)_setIntrinsicContentSize:(CGSize)intrinsicContentSize
1970 {
1971     // If the intrinsic content size is less than the minimum layout width, the content flowed to fit,
1972     // so we can report that that dimension is flexible. If not, we need to report our intrinsic width
1973     // so that autolayout will know to provide space for us.
1974
1975     CGSize intrinsicContentSizeAcknowledgingFlexibleWidth = intrinsicContentSize;
1976     if (intrinsicContentSize.width < _page->minimumLayoutSize().width())
1977         intrinsicContentSizeAcknowledgingFlexibleWidth.width = NSViewNoInstrinsicMetric;
1978
1979     _intrinsicContentSize = intrinsicContentSizeAcknowledgingFlexibleWidth;
1980     [self invalidateIntrinsicContentSize];
1981 }
1982
1983 #endif // PLATFORM(MAC)
1984
1985 @end
1986
1987 @implementation WKWebView (WKPrivate)
1988
1989 - (BOOL)_isEditable
1990 {
1991     return _page->isEditable();
1992 }
1993
1994 - (void)_setEditable:(BOOL)editable
1995 {
1996     _page->setEditable(editable);
1997 #if !PLATFORM(IOS)
1998     [_wkView _addFontPanelObserver];
1999 #endif
2000 }
2001
2002 - (_WKRemoteObjectRegistry *)_remoteObjectRegistry
2003 {
2004     if (!_remoteObjectRegistry) {
2005         _remoteObjectRegistry = adoptNS([[_WKRemoteObjectRegistry alloc] _initWithMessageSender:*_page]);
2006         _page->process().processPool().addMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID(), [_remoteObjectRegistry remoteObjectRegistry]);
2007     }
2008
2009     return _remoteObjectRegistry.get();
2010 }
2011
2012 - (WKBrowsingContextHandle *)_handle
2013 {
2014     return [[[WKBrowsingContextHandle alloc] _initWithPageID:_page->pageID()] autorelease];
2015 }
2016
2017 - (_WKRenderingProgressEvents)_observedRenderingProgressEvents
2018 {
2019     return _observedRenderingProgressEvents;
2020 }
2021
2022 - (id <WKHistoryDelegatePrivate>)_historyDelegate
2023 {
2024     return _navigationState->historyDelegate().autorelease();
2025 }
2026
2027 - (void)_setHistoryDelegate:(id <WKHistoryDelegatePrivate>)historyDelegate
2028 {
2029     _page->setHistoryClient(_navigationState->createHistoryClient());
2030     _navigationState->setHistoryDelegate(historyDelegate);
2031 }
2032
2033 - (NSURL *)_unreachableURL
2034 {
2035     return [NSURL _web_URLWithWTFString:_page->pageLoadState().unreachableURL()];
2036 }
2037
2038 - (void)_loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
2039 {
2040     _page->loadAlternateHTMLString(string, [baseURL _web_originalDataAsWTFString], [unreachableURL _web_originalDataAsWTFString]);
2041 }
2042
2043 - (WKNavigation *)_loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL userData:(id)userData
2044 {
2045     auto navigation = _page->loadData(API::Data::createWithoutCopying(data).ptr(), MIMEType, characterEncodingName, baseURL.absoluteString, WebKit::ObjCObjectGraph::create(userData).ptr());
2046     if (!navigation)
2047         return nil;
2048
2049     return [wrapper(*navigation.release().leakRef()) autorelease];
2050 }
2051
2052 - (NSArray *)_certificateChain
2053 {
2054     if (WebKit::WebFrameProxy* mainFrame = _page->mainFrame())
2055         return mainFrame->certificateInfo() ? (NSArray *)mainFrame->certificateInfo()->certificateInfo().certificateChain() : nil;
2056
2057     return nil;
2058 }
2059
2060 - (NSURL *)_committedURL
2061 {
2062     return [NSURL _web_URLWithWTFString:_page->pageLoadState().url()];
2063 }
2064
2065 - (NSString *)_MIMEType
2066 {
2067     if (_page->mainFrame())
2068         return _page->mainFrame()->mimeType();
2069
2070     return nil;
2071 }
2072
2073 - (NSString *)_userAgent
2074 {
2075     return _page->userAgent();
2076 }
2077
2078 - (NSString *)_applicationNameForUserAgent
2079 {
2080     return _page->applicationNameForUserAgent();
2081 }
2082
2083 - (void)_setApplicationNameForUserAgent:(NSString *)applicationNameForUserAgent
2084 {
2085     _page->setApplicationNameForUserAgent(applicationNameForUserAgent);
2086 }
2087
2088 - (NSString *)_customUserAgent
2089 {
2090     return self.customUserAgent;
2091 }
2092
2093 - (void)_setCustomUserAgent:(NSString *)customUserAgent
2094 {
2095     self.customUserAgent = customUserAgent;
2096 }
2097
2098 - (void)_setUserContentExtensionsEnabled:(BOOL)userContentExtensionsEnabled
2099 {
2100     // This is kept for binary compatibility with iOS 9.
2101 }
2102
2103 - (BOOL)_userContentExtensionsEnabled
2104 {
2105     // This is kept for binary compatibility with iOS 9.
2106     return true;
2107 }
2108
2109 - (pid_t)_webProcessIdentifier
2110 {
2111     return _page->isValid() ? _page->processIdentifier() : 0;
2112 }
2113
2114 - (void)_killWebContentProcess
2115 {
2116     if (!_page->isValid())
2117         return;
2118
2119     _page->process().terminate();
2120 }
2121
2122 - (WKNavigation *)_reloadWithoutContentBlockers
2123 {
2124     const bool reloadFromOrigin = false;
2125     const bool contentBlockersEnabled = false;
2126     auto navigation = _page->reload(reloadFromOrigin, contentBlockersEnabled);
2127     if (!navigation)
2128         return nil;
2129     
2130     return [wrapper(*navigation.release().leakRef()) autorelease];
2131 }
2132
2133 - (void)_killWebContentProcessAndResetState
2134 {
2135     _page->terminateProcess();
2136 }
2137
2138 #if PLATFORM(IOS)
2139 static WebCore::FloatSize activeMinimumLayoutSize(WKWebView *webView, const CGRect& bounds)
2140 {
2141     return WebCore::FloatSize(webView->_overridesMinimumLayoutSize ? webView->_minimumLayoutSizeOverride : bounds.size);
2142 }
2143
2144 static WebCore::FloatSize activeMaximumUnobscuredSize(WKWebView *webView, const CGRect& bounds)
2145 {
2146     return WebCore::FloatSize(webView->_overridesMaximumUnobscuredSize ? webView->_maximumUnobscuredSizeOverride : bounds.size);
2147 }
2148
2149 static int32_t activeOrientation(WKWebView *webView)
2150 {
2151     return webView->_overridesInterfaceOrientation ? deviceOrientationForUIInterfaceOrientation(webView->_interfaceOrientationOverride) : webView->_page->deviceOrientation();
2152 }
2153
2154 - (void (^)(void))_retainActiveFocusedState
2155 {
2156     ++_activeFocusedStateRetainCount;
2157
2158     // FIXME: Use something like CompletionHandlerCallChecker to ensure that the returned block is called before it's released.
2159     return [[[self] {
2160         --_activeFocusedStateRetainCount;
2161     } copy] autorelease];
2162 }
2163
2164 - (void)_becomeFirstResponderWithSelectionMovingForward:(BOOL)selectingForward completionHandler:(void (^)(BOOL didBecomeFirstResponder))completionHandler
2165 {
2166     typeof(completionHandler) completionHandlerCopy = nil;
2167     if (completionHandler)
2168         completionHandlerCopy = Block_copy(completionHandler);
2169
2170     [_contentView _becomeFirstResponderWithSelectionMovingForward:selectingForward completionHandler:[completionHandlerCopy](BOOL didBecomeFirstResponder) {
2171         if (!completionHandlerCopy)
2172             return;
2173
2174         completionHandlerCopy(didBecomeFirstResponder);
2175         Block_release(completionHandlerCopy);
2176     }];
2177 }
2178
2179 - (id)_snapshotLayerContentsForBackForwardListItem:(WKBackForwardListItem *)item
2180 {
2181     if (_page->backForwardList().currentItem() == &item._item)
2182         _page->recordNavigationSnapshot(*_page->backForwardList().currentItem());
2183
2184     if (auto* viewSnapshot = item._item.snapshot())
2185         return viewSnapshot->asLayerContents();
2186
2187     return nil;
2188 }
2189
2190 #endif
2191
2192 - (void)_didRelaunchProcess
2193 {
2194 #if PLATFORM(IOS)
2195     CGRect bounds = self.bounds;
2196     WebCore::FloatSize minimalLayoutSize = activeMinimumLayoutSize(self, bounds);
2197     _page->setViewportConfigurationMinimumLayoutSize(minimalLayoutSize);
2198     _page->setMaximumUnobscuredSize(activeMaximumUnobscuredSize(self, bounds));
2199 #endif
2200 }
2201
2202 - (NSData *)_sessionStateData
2203 {
2204     WebKit::SessionState sessionState = _page->sessionState();
2205
2206     // FIXME: This should not use the legacy session state encoder.
2207     return [wrapper(*WebKit::encodeLegacySessionState(sessionState).release().leakRef()) autorelease];
2208 }
2209
2210 - (_WKSessionState *)_sessionState
2211 {
2212     return adoptNS([[_WKSessionState alloc] _initWithSessionState:_page->sessionState()]).autorelease();
2213 }
2214
2215 - (void)_restoreFromSessionStateData:(NSData *)sessionStateData
2216 {
2217     // FIXME: This should not use the legacy session state decoder.
2218     WebKit::SessionState sessionState;
2219     if (!WebKit::decodeLegacySessionState(static_cast<const uint8_t*>(sessionStateData.bytes), sessionStateData.length, sessionState))
2220         return;
2221
2222     _page->restoreFromSessionState(WTF::move(sessionState), true);
2223 }
2224
2225 - (WKNavigation *)_restoreSessionState:(_WKSessionState *)sessionState andNavigate:(BOOL)navigate
2226 {
2227     auto navigation = _page->restoreFromSessionState(sessionState->_sessionState, navigate);
2228     if (!navigation)
2229         return nil;
2230
2231     return [wrapper(*navigation.release().leakRef()) autorelease];
2232 }
2233
2234 - (void)_close
2235 {
2236     _page->close();
2237 }
2238
2239 - (BOOL)_allowsRemoteInspection
2240 {
2241 #if ENABLE(REMOTE_INSPECTOR)
2242     return _page->allowsRemoteInspection();
2243 #else
2244     return NO;
2245 #endif
2246 }
2247
2248 - (void)_setAllowsRemoteInspection:(BOOL)allow
2249 {
2250 #if ENABLE(REMOTE_INSPECTOR)
2251     _page->setAllowsRemoteInspection(allow);
2252 #endif
2253 }
2254
2255 - (BOOL)_addsVisitedLinks
2256 {
2257     return _page->addsVisitedLinks();
2258 }
2259
2260 - (void)_setAddsVisitedLinks:(BOOL)addsVisitedLinks
2261 {
2262     _page->setAddsVisitedLinks(addsVisitedLinks);
2263 }
2264
2265 - (BOOL)_networkRequestsInProgress
2266 {
2267     return _page->pageLoadState().networkRequestsInProgress();
2268 }
2269
2270 static inline WebCore::LayoutMilestones layoutMilestones(_WKRenderingProgressEvents events)
2271 {
2272     WebCore::LayoutMilestones milestones = 0;
2273
2274     if (events & _WKRenderingProgressEventFirstLayout)
2275         milestones |= WebCore::DidFirstLayout;
2276
2277     if (events & _WKRenderingProgressEventFirstVisuallyNonEmptyLayout)
2278         milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
2279
2280     if (events & _WKRenderingProgressEventFirstPaintWithSignificantArea)
2281         milestones |= WebCore::DidHitRelevantRepaintedObjectsAreaThreshold;
2282
2283     if (events & _WKRenderingProgressEventReachedSessionRestorationRenderTreeSizeThreshold)
2284         milestones |= WebCore::ReachedSessionRestorationRenderTreeSizeThreshold;
2285
2286     if (events & _WKRenderingProgressEventFirstLayoutAfterSuppressedIncrementalRendering)
2287         milestones |= WebCore::DidFirstLayoutAfterSuppressedIncrementalRendering;
2288
2289     if (events & _WKRenderingProgressEventFirstPaintAfterSuppressedIncrementalRendering)
2290         milestones |= WebCore::DidFirstPaintAfterSuppressedIncrementalRendering;
2291
2292     return milestones;
2293 }
2294
2295 - (void)_setObservedRenderingProgressEvents:(_WKRenderingProgressEvents)observedRenderingProgressEvents
2296 {
2297     _observedRenderingProgressEvents = observedRenderingProgressEvents;
2298     _page->listenForLayoutMilestones(layoutMilestones(observedRenderingProgressEvents));
2299 }
2300
2301 - (void)_getMainResourceDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
2302 {
2303     auto handler = adoptNS([completionHandler copy]);
2304
2305     _page->getMainResourceDataOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
2306         void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
2307         if (error != WebKit::CallbackBase::Error::None) {
2308             // FIXME: Pipe a proper error in from the WebPageProxy.
2309             RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
2310             completionHandlerBlock(nil, error.get());
2311         } else
2312             completionHandlerBlock(wrapper(*data), nil);
2313     });
2314 }
2315
2316 - (void)_getWebArchiveDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler
2317 {
2318     auto handler = adoptNS([completionHandler copy]);
2319
2320     _page->getWebArchiveOfFrame(_page->mainFrame(), [handler](API::Data* data, WebKit::CallbackBase::Error error) {
2321         void (^completionHandlerBlock)(NSData *, NSError *) = (void (^)(NSData *, NSError *))handler.get();
2322         if (error != WebKit::CallbackBase::Error::None) {
2323             // FIXME: Pipe a proper error in from the WebPageProxy.
2324             RetainPtr<NSError> error = adoptNS([[NSError alloc] init]);
2325             completionHandlerBlock(nil, error.get());
2326         } else
2327             completionHandlerBlock(wrapper(*data), nil);
2328     });
2329 }
2330
2331 - (_WKPaginationMode)_paginationMode
2332 {
2333     switch (_page->paginationMode()) {
2334     case WebCore::Pagination::Unpaginated:
2335         return _WKPaginationModeUnpaginated;
2336     case WebCore::Pagination::LeftToRightPaginated:
2337         return _WKPaginationModeLeftToRight;
2338     case WebCore::Pagination::RightToLeftPaginated:
2339         return _WKPaginationModeRightToLeft;
2340     case WebCore::Pagination::TopToBottomPaginated:
2341         return _WKPaginationModeTopToBottom;
2342     case WebCore::Pagination::BottomToTopPaginated:
2343         return _WKPaginationModeBottomToTop;
2344     }
2345
2346     ASSERT_NOT_REACHED();
2347     return _WKPaginationModeUnpaginated;
2348 }
2349
2350 - (void)_setPaginationMode:(_WKPaginationMode)paginationMode
2351 {
2352     WebCore::Pagination::Mode mode;
2353     switch (paginationMode) {
2354     case _WKPaginationModeUnpaginated:
2355         mode = WebCore::Pagination::Unpaginated;
2356         break;
2357     case _WKPaginationModeLeftToRight:
2358         mode = WebCore::Pagination::LeftToRightPaginated;
2359         break;
2360     case _WKPaginationModeRightToLeft:
2361         mode = WebCore::Pagination::RightToLeftPaginated;
2362         break;
2363     case _WKPaginationModeTopToBottom:
2364         mode = WebCore::Pagination::TopToBottomPaginated;
2365         break;
2366     case _WKPaginationModeBottomToTop:
2367         mode = WebCore::Pagination::BottomToTopPaginated;
2368         break;
2369     default:
2370         return;
2371     }
2372
2373     _page->setPaginationMode(mode);
2374 }
2375
2376 - (BOOL)_paginationBehavesLikeColumns
2377 {
2378     return _page->paginationBehavesLikeColumns();
2379 }
2380
2381 - (void)_setPaginationBehavesLikeColumns:(BOOL)behavesLikeColumns
2382 {
2383     _page->setPaginationBehavesLikeColumns(behavesLikeColumns);
2384 }
2385
2386 - (CGFloat)_pageLength
2387 {
2388     return _page->pageLength();
2389 }
2390
2391 - (void)_setPageLength:(CGFloat)pageLength
2392 {
2393     _page->setPageLength(pageLength);
2394 }
2395
2396 - (CGFloat)_gapBetweenPages
2397 {
2398     return _page->gapBetweenPages();
2399 }
2400
2401 - (void)_setGapBetweenPages:(CGFloat)gapBetweenPages
2402 {
2403     _page->setGapBetweenPages(gapBetweenPages);
2404 }
2405
2406 - (NSUInteger)_pageCount
2407 {
2408     return _page->pageCount();
2409 }
2410
2411 - (BOOL)_supportsTextZoom
2412 {
2413     return _page->supportsTextZoom();
2414 }
2415
2416 - (double)_textZoomFactor
2417 {
2418     return _page->textZoomFactor();
2419 }
2420
2421 - (void)_setTextZoomFactor:(double)zoomFactor
2422 {
2423     _page->setTextZoomFactor(zoomFactor);
2424 }
2425
2426 - (double)_pageZoomFactor
2427 {
2428     return _page->pageZoomFactor();
2429 }
2430
2431 - (void)_setPageZoomFactor:(double)zoomFactor
2432 {
2433     _page->setPageZoomFactor(zoomFactor);
2434 }
2435
2436 - (id <_WKDiagnosticLoggingDelegate>)_diagnosticLoggingDelegate
2437 {
2438     return [static_cast<WebKit::DiagnosticLoggingClient&>(_page->diagnosticLoggingClient()).delegate().leakRef() autorelease];
2439 }
2440
2441 - (void)_setDiagnosticLoggingDelegate:(id<_WKDiagnosticLoggingDelegate>)diagnosticLoggingDelegate
2442 {
2443     static_cast<WebKit::DiagnosticLoggingClient&>(_page->diagnosticLoggingClient()).setDelegate(diagnosticLoggingDelegate);
2444 }
2445
2446 - (id <_WKFindDelegate>)_findDelegate
2447 {
2448     return [static_cast<WebKit::FindClient&>(_page->findClient()).delegate().leakRef() autorelease];
2449 }
2450
2451 - (void)_setFindDelegate:(id<_WKFindDelegate>)findDelegate
2452 {
2453     static_cast<WebKit::FindClient&>(_page->findClient()).setDelegate(findDelegate);
2454 }
2455
2456 static inline WebKit::FindOptions toFindOptions(_WKFindOptions wkFindOptions)
2457 {
2458     unsigned findOptions = 0;
2459
2460     if (wkFindOptions & _WKFindOptionsCaseInsensitive)
2461         findOptions |= WebKit::FindOptionsCaseInsensitive;
2462     if (wkFindOptions & _WKFindOptionsAtWordStarts)
2463         findOptions |= WebKit::FindOptionsAtWordStarts;
2464     if (wkFindOptions & _WKFindOptionsTreatMedialCapitalAsWordStart)
2465         findOptions |= WebKit::FindOptionsTreatMedialCapitalAsWordStart;
2466     if (wkFindOptions & _WKFindOptionsBackwards)
2467         findOptions |= WebKit::FindOptionsBackwards;
2468     if (wkFindOptions & _WKFindOptionsWrapAround)
2469         findOptions |= WebKit::FindOptionsWrapAround;
2470     if (wkFindOptions & _WKFindOptionsShowOverlay)
2471         findOptions |= WebKit::FindOptionsShowOverlay;
2472     if (wkFindOptions & _WKFindOptionsShowFindIndicator)
2473         findOptions |= WebKit::FindOptionsShowFindIndicator;
2474     if (wkFindOptions & _WKFindOptionsShowHighlight)
2475         findOptions |= WebKit::FindOptionsShowHighlight;
2476     if (wkFindOptions & _WKFindOptionsDetermineMatchIndex)
2477         findOptions |= WebKit::FindOptionsDetermineMatchIndex;
2478
2479     return static_cast<WebKit::FindOptions>(findOptions);
2480 }
2481
2482 - (void)_countStringMatches:(NSString *)string options:(_WKFindOptions)options maxCount:(NSUInteger)maxCount
2483 {
2484 #if PLATFORM(IOS)
2485     if (_customContentView) {
2486         [_customContentView web_countStringMatches:string options:options maxCount:maxCount];
2487         return;
2488     }
2489 #endif
2490     _page->countStringMatches(string, toFindOptions(options), maxCount);
2491 }
2492
2493 - (void)_findString:(NSString *)string options:(_WKFindOptions)options maxCount:(NSUInteger)maxCount
2494 {
2495 #if PLATFORM(IOS)
2496     if (_customContentView) {
2497         [_customContentView web_findString:string options:options maxCount:maxCount];
2498         return;
2499     }
2500 #endif
2501     _page->findString(string, toFindOptions(options), maxCount);
2502 }
2503
2504 - (void)_hideFindUI
2505 {
2506 #if PLATFORM(IOS)
2507     if (_customContentView) {
2508         [_customContentView web_hideFindUI];
2509         return;
2510     }
2511 #endif
2512     _page->hideFindUI();
2513 }
2514
2515 - (void)_saveBackForwardSnapshotForItem:(WKBackForwardListItem *)item
2516 {
2517     _page->recordNavigationSnapshot(item._item);
2518 }
2519
2520 - (id <_WKInputDelegate>)_inputDelegate
2521 {
2522     return _inputDelegate.getAutoreleased();
2523 }
2524
2525 - (id <_WKFormDelegate>)_formDelegate
2526 {
2527     return (id <_WKFormDelegate>)[self _inputDelegate];
2528 }
2529
2530 - (void)_setInputDelegate:(id <_WKInputDelegate>)inputDelegate
2531 {
2532     _inputDelegate = inputDelegate;
2533
2534     class FormClient : public API::FormClient {
2535     public:
2536         explicit FormClient(WKWebView *webView)
2537             : m_webView(webView)
2538         {
2539         }
2540
2541         virtual ~FormClient() { }
2542
2543         virtual 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
2544         {
2545             if (userData && userData->type() != API::Object::Type::Data) {
2546                 ASSERT(!userData || userData->type() == API::Object::Type::Data);
2547                 m_webView->_page->process().connection()->markCurrentlyDispatchedMessageAsInvalid();
2548                 listener->continueSubmission();
2549                 return;
2550             }
2551
2552             auto inputDelegate = m_webView->_inputDelegate.get();
2553
2554             if (![inputDelegate respondsToSelector:@selector(_webView:willSubmitFormValues:userObject:submissionHandler:)]) {
2555                 listener->continueSubmission();
2556                 return;
2557             }
2558
2559             auto valueMap = adoptNS([[NSMutableDictionary alloc] initWithCapacity:textFieldValues.size()]);
2560             for (const auto& pair : textFieldValues)
2561                 [valueMap setObject:pair.second forKey:pair.first];
2562
2563             NSObject <NSSecureCoding> *userObject = nil;
2564             if (API::Data* data = static_cast<API::Data*>(userData)) {
2565                 auto nsData = adoptNS([[NSData alloc] initWithBytesNoCopy:const_cast<void*>(static_cast<const void*>(data->bytes())) length:data->size() freeWhenDone:NO]);
2566                 auto unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingWithData:nsData.get()]);
2567                 [unarchiver setRequiresSecureCoding:YES];
2568                 @try {
2569                     userObject = [unarchiver decodeObjectOfClass:[NSObject class] forKey:@"userObject"];
2570                 } @catch (NSException *exception) {
2571                     LOG_ERROR("Failed to decode user data: %@", exception);
2572                 }
2573             }
2574
2575             RefPtr<WebKit::WebFormSubmissionListenerProxy> localListener = WTF::move(listener);
2576             RefPtr<WebKit::CompletionHandlerCallChecker> checker = WebKit::CompletionHandlerCallChecker::create(inputDelegate.get(), @selector(_webView:willSubmitFormValues:userObject:submissionHandler:));
2577             [inputDelegate _webView:m_webView willSubmitFormValues:valueMap.get() userObject:userObject submissionHandler:[localListener, checker] {
2578                 checker->didCallCompletionHandler();
2579                 localListener->continueSubmission();
2580             }];
2581         }
2582
2583     private:
2584         WKWebView *m_webView;
2585     };
2586
2587     if (inputDelegate)
2588         _page->setFormClient(std::make_unique<FormClient>(self));
2589     else
2590         _page->setFormClient(nullptr);
2591 }
2592
2593 - (void)_setFormDelegate:(id <_WKFormDelegate>)formDelegate
2594 {
2595     [self _setInputDelegate:(id <_WKInputDelegate>)formDelegate];
2596 }
2597
2598 - (BOOL)_isDisplayingStandaloneImageDocument
2599 {
2600     if (auto* mainFrame = _page->mainFrame())
2601         return mainFrame->isDisplayingStandaloneImageDocument();
2602     return NO;
2603 }
2604
2605 - (BOOL)_isDisplayingStandaloneMediaDocument
2606 {
2607     if (auto* mainFrame = _page->mainFrame())
2608         return mainFrame->isDisplayingStandaloneMediaDocument();
2609     return NO;
2610 }
2611
2612 - (BOOL)_isShowingNavigationGestureSnapshot
2613 {
2614     return _page->isShowingNavigationGestureSnapshot();
2615 }
2616
2617 - (_WKLayoutMode)_layoutMode
2618 {
2619 #if PLATFORM(MAC)
2620     switch ([_wkView _layoutMode]) {
2621     case kWKLayoutModeFixedSize:
2622         return _WKLayoutModeFixedSize;
2623     case kWKLayoutModeDynamicSizeComputedFromViewScale:
2624         return _WKLayoutModeDynamicSizeComputedFromViewScale;
2625     case kWKLayoutModeDynamicSizeComputedFromMinimumDocumentSize:
2626         return _WKLayoutModeDynamicSizeComputedFromMinimumDocumentSize;
2627     case kWKLayoutModeViewSize:
2628     default:
2629         return _WKLayoutModeViewSize;
2630     }
2631 #else
2632     return _page->useFixedLayout() ? _WKLayoutModeFixedSize : _WKLayoutModeViewSize;
2633 #endif
2634 }
2635
2636 - (void)_setLayoutMode:(_WKLayoutMode)layoutMode
2637 {
2638 #if PLATFORM(MAC)
2639     WKLayoutMode wkViewLayoutMode;
2640     switch (layoutMode) {
2641     case _WKLayoutModeFixedSize:
2642         wkViewLayoutMode = kWKLayoutModeFixedSize;
2643         break;
2644     case _WKLayoutModeDynamicSizeComputedFromViewScale:
2645         wkViewLayoutMode = kWKLayoutModeDynamicSizeComputedFromViewScale;
2646         break;
2647     case _WKLayoutModeDynamicSizeComputedFromMinimumDocumentSize:
2648         wkViewLayoutMode = kWKLayoutModeDynamicSizeComputedFromMinimumDocumentSize;
2649         break;
2650     case _WKLayoutModeViewSize:
2651     default:
2652         wkViewLayoutMode = kWKLayoutModeViewSize;
2653         break;
2654     }
2655     [_wkView _setLayoutMode:wkViewLayoutMode];
2656 #else
2657     _page->setUseFixedLayout(layoutMode == _WKLayoutModeFixedSize || layoutMode == _WKLayoutModeDynamicSizeComputedFromViewScale);
2658 #endif
2659 }
2660
2661 - (CGSize)_fixedLayoutSize
2662 {
2663     return _page->fixedLayoutSize();
2664 }
2665
2666 - (void)_setFixedLayoutSize:(CGSize)fixedLayoutSize
2667 {
2668     _page->setFixedLayoutSize(WebCore::expandedIntSize(WebCore::FloatSize(fixedLayoutSize)));
2669 }
2670
2671 - (CGFloat)_viewScale
2672 {
2673     return _page->viewScaleFactor();
2674 }
2675
2676 - (void)_setViewScale:(CGFloat)viewScale
2677 {
2678 #if PLATFORM(MAC)
2679     [_wkView _setViewScale:viewScale];
2680 #else
2681     if (viewScale <= 0 || isnan(viewScale) || isinf(viewScale))
2682         [NSException raise:NSInvalidArgumentException format:@"View scale should be a positive number"];
2683
2684     _page->scaleView(viewScale);
2685 #endif
2686 }
2687
2688 #pragma mark scrollperf methods
2689
2690 - (void)_setScrollPerformanceDataCollectionEnabled:(BOOL)enabled
2691 {
2692     _page->setScrollPerformanceDataCollectionEnabled(enabled);
2693 }
2694
2695 - (BOOL)_scrollPerformanceDataCollectionEnabled
2696 {
2697     return _page->scrollPerformanceDataCollectionEnabled();
2698 }
2699
2700 - (NSArray *)_scrollPerformanceData
2701 {
2702 #if PLATFORM(IOS)
2703     if (WebKit::RemoteLayerTreeScrollingPerformanceData* scrollPerfData = _page->scrollingPerformanceData())
2704         return scrollPerfData->data();
2705 #endif
2706     return nil;
2707 }
2708
2709 #pragma mark media playback restrictions
2710
2711 - (BOOL)_allowsMediaDocumentInlinePlayback
2712 {
2713 #if PLATFORM(IOS)
2714     return _page->allowsMediaDocumentInlinePlayback();
2715 #else
2716     return NO;
2717 #endif
2718 }
2719
2720 - (void)_setAllowsMediaDocumentInlinePlayback:(BOOL)flag
2721 {
2722 #if PLATFORM(IOS)
2723     _page->setAllowsMediaDocumentInlinePlayback(flag);
2724 #endif
2725 }
2726
2727 #pragma mark iOS-specific methods
2728
2729 #if PLATFORM(IOS)
2730
2731 - (CGSize)_minimumLayoutSizeOverride
2732 {
2733     ASSERT(_overridesMinimumLayoutSize);
2734     return _minimumLayoutSizeOverride;
2735 }
2736
2737 - (void)_setMinimumLayoutSizeOverride:(CGSize)minimumLayoutSizeOverride
2738 {
2739     _overridesMinimumLayoutSize = YES;
2740     if (CGSizeEqualToSize(_minimumLayoutSizeOverride, minimumLayoutSizeOverride))
2741         return;
2742
2743     _minimumLayoutSizeOverride = minimumLayoutSizeOverride;
2744     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2745         _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(minimumLayoutSizeOverride));
2746 }
2747
2748 - (UIEdgeInsets)_obscuredInsets
2749 {
2750     return _obscuredInsets;
2751 }
2752
2753 - (void)_setObscuredInsets:(UIEdgeInsets)obscuredInsets
2754 {
2755     ASSERT(obscuredInsets.top >= 0);
2756     ASSERT(obscuredInsets.left >= 0);
2757     ASSERT(obscuredInsets.bottom >= 0);
2758     ASSERT(obscuredInsets.right >= 0);
2759     
2760     _haveSetObscuredInsets = YES;
2761
2762     if (UIEdgeInsetsEqualToEdgeInsets(_obscuredInsets, obscuredInsets))
2763         return;
2764
2765     _obscuredInsets = obscuredInsets;
2766
2767     [self _updateVisibleContentRects];
2768 }
2769
2770 - (void)_setInterfaceOrientationOverride:(UIInterfaceOrientation)interfaceOrientation
2771 {
2772     if (!_overridesInterfaceOrientation)
2773         [[NSNotificationCenter defaultCenter] removeObserver:self name:UIWindowDidRotateNotification object:nil];
2774
2775     _overridesInterfaceOrientation = YES;
2776
2777     if (interfaceOrientation == _interfaceOrientationOverride)
2778         return;
2779
2780     _interfaceOrientationOverride = interfaceOrientation;
2781
2782     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2783         _page->setDeviceOrientation(deviceOrientationForUIInterfaceOrientation(_interfaceOrientationOverride));
2784 }
2785
2786 - (UIInterfaceOrientation)_interfaceOrientationOverride
2787 {
2788     ASSERT(_overridesInterfaceOrientation);
2789     return _interfaceOrientationOverride;
2790 }
2791
2792 - (CGSize)_maximumUnobscuredSizeOverride
2793 {
2794     ASSERT(_overridesMaximumUnobscuredSize);
2795     return _maximumUnobscuredSizeOverride;
2796 }
2797
2798 - (void)_setMaximumUnobscuredSizeOverride:(CGSize)size
2799 {
2800     ASSERT(size.width <= self.bounds.size.width && size.height <= self.bounds.size.height);
2801     _overridesMaximumUnobscuredSize = YES;
2802     if (CGSizeEqualToSize(_maximumUnobscuredSizeOverride, size))
2803         return;
2804
2805     _maximumUnobscuredSizeOverride = size;
2806     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2807         _page->setMaximumUnobscuredSize(WebCore::FloatSize(size));
2808 }
2809
2810 - (void)_setBackgroundExtendsBeyondPage:(BOOL)backgroundExtends
2811 {
2812     _page->setBackgroundExtendsBeyondPage(backgroundExtends);
2813 }
2814
2815 - (BOOL)_backgroundExtendsBeyondPage
2816 {
2817     return _page->backgroundExtendsBeyondPage();
2818 }
2819
2820 - (void)_beginInteractiveObscuredInsetsChange
2821 {
2822     ASSERT(!_isChangingObscuredInsetsInteractively);
2823     _isChangingObscuredInsetsInteractively = YES;
2824 }
2825
2826 - (void)_endInteractiveObscuredInsetsChange
2827 {
2828     ASSERT(_isChangingObscuredInsetsInteractively);
2829     _isChangingObscuredInsetsInteractively = NO;
2830     [self _updateVisibleContentRects];
2831 }
2832
2833 - (void)_hideContentUntilNextUpdate
2834 {
2835     if (auto* area = _page->drawingArea())
2836         area->hideContentUntilAnyUpdate();
2837 }
2838
2839 - (void)_beginAnimatedResizeWithUpdates:(void (^)(void))updateBlock
2840 {
2841     CGRect oldBounds = self.bounds;
2842     WebCore::FloatRect oldUnobscuredContentRect = _page->unobscuredContentRect();
2843
2844     if (_customContentView || !_hasCommittedLoadForMainFrame || CGRectIsEmpty(oldBounds) || oldUnobscuredContentRect.isEmpty()) {
2845         updateBlock();
2846         return;
2847     }
2848
2849     _dynamicViewportUpdateMode = DynamicViewportUpdateMode::ResizingWithAnimation;
2850
2851     WebCore::FloatSize oldMinimumLayoutSize = activeMinimumLayoutSize(self, oldBounds);
2852     WebCore::FloatSize oldMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, oldBounds);
2853     int32_t oldOrientation = activeOrientation(self);
2854     UIEdgeInsets oldObscuredInsets = _obscuredInsets;
2855
2856     updateBlock();
2857
2858     CGRect newBounds = self.bounds;
2859     WebCore::FloatSize newMinimumLayoutSize = activeMinimumLayoutSize(self, newBounds);
2860     WebCore::FloatSize newMaximumUnobscuredSize = activeMaximumUnobscuredSize(self, newBounds);
2861     int32_t newOrientation = activeOrientation(self);
2862     UIEdgeInsets newObscuredInsets = _obscuredInsets;
2863     CGRect futureUnobscuredRectInSelfCoordinates = UIEdgeInsetsInsetRect(newBounds, _obscuredInsets);
2864     CGRect contentViewBounds = [_contentView bounds];
2865
2866     ASSERT_WITH_MESSAGE(!(_overridesMinimumLayoutSize && newMinimumLayoutSize.isEmpty()), "Clients controlling the layout size should maintain a valid layout size to minimize layouts.");
2867     if (CGRectIsEmpty(newBounds) || newMinimumLayoutSize.isEmpty() || CGRectIsEmpty(futureUnobscuredRectInSelfCoordinates) || CGRectIsEmpty(contentViewBounds)) {
2868         _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
2869         [self _frameOrBoundsChanged];
2870         if (_overridesMinimumLayoutSize)
2871             _page->setViewportConfigurationMinimumLayoutSize(WebCore::FloatSize(newMinimumLayoutSize));
2872         if (_overridesMaximumUnobscuredSize)
2873             _page->setMaximumUnobscuredSize(WebCore::FloatSize(newMaximumUnobscuredSize));
2874         if (_overridesInterfaceOrientation)
2875             _page->setDeviceOrientation(newOrientation);
2876         [self _updateVisibleContentRects];
2877         return;
2878     }
2879
2880     if (CGRectEqualToRect(oldBounds, newBounds)
2881         && oldMinimumLayoutSize == newMinimumLayoutSize
2882         && oldMaximumUnobscuredSize == newMaximumUnobscuredSize
2883         && oldOrientation == newOrientation
2884         && UIEdgeInsetsEqualToEdgeInsets(oldObscuredInsets, newObscuredInsets)) {
2885         _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
2886         [self _updateVisibleContentRects];
2887         return;
2888     }
2889
2890     _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2891
2892     NSUInteger indexOfContentView = [[_scrollView subviews] indexOfObject:_contentView.get()];
2893     _resizeAnimationView = adoptNS([[UIView alloc] init]);
2894     [_scrollView insertSubview:_resizeAnimationView.get() atIndex:indexOfContentView];
2895     [_resizeAnimationView addSubview:_contentView.get()];
2896     [_resizeAnimationView addSubview:[_contentView unscaledView]];
2897
2898     CGSize contentSizeInContentViewCoordinates = contentViewBounds.size;
2899     [_scrollView setMinimumZoomScale:std::min(newMinimumLayoutSize.width() / contentSizeInContentViewCoordinates.width, [_scrollView minimumZoomScale])];
2900     [_scrollView setMaximumZoomScale:std::max(newMinimumLayoutSize.width() / contentSizeInContentViewCoordinates.width, [_scrollView maximumZoomScale])];
2901
2902     // Compute the new scale to keep the current content width in the scrollview.
2903     CGFloat oldWebViewWidthInContentViewCoordinates = oldUnobscuredContentRect.width();
2904     CGFloat visibleContentViewWidthInContentCoordinates = std::min(contentSizeInContentViewCoordinates.width, oldWebViewWidthInContentViewCoordinates);
2905     CGFloat targetScale = newMinimumLayoutSize.width() / visibleContentViewWidthInContentCoordinates;
2906     CGFloat resizeAnimationViewAnimationScale = targetScale / contentZoomScale(self);
2907     [_resizeAnimationView setTransform:CGAffineTransformMakeScale(resizeAnimationViewAnimationScale, resizeAnimationViewAnimationScale)];
2908
2909     // Compute a new position to keep the content centered.
2910     CGPoint originalContentCenter = oldUnobscuredContentRect.center();
2911     CGPoint originalContentCenterInSelfCoordinates = [self convertPoint:originalContentCenter fromView:_contentView.get()];
2912     CGPoint futureUnobscuredRectCenterInSelfCoordinates = CGPointMake(futureUnobscuredRectInSelfCoordinates.origin.x + futureUnobscuredRectInSelfCoordinates.size.width / 2, futureUnobscuredRectInSelfCoordinates.origin.y + futureUnobscuredRectInSelfCoordinates.size.height / 2);
2913
2914     CGPoint originalContentOffset = [_scrollView contentOffset];
2915     CGPoint contentOffset = originalContentOffset;
2916     contentOffset.x += (originalContentCenterInSelfCoordinates.x - futureUnobscuredRectCenterInSelfCoordinates.x);
2917     contentOffset.y += (originalContentCenterInSelfCoordinates.y - futureUnobscuredRectCenterInSelfCoordinates.y);
2918
2919     // Limit the new offset within the scrollview, we do not want to rubber band programmatically.
2920     CGSize futureContentSizeInSelfCoordinates = CGSizeMake(contentSizeInContentViewCoordinates.width * targetScale, contentSizeInContentViewCoordinates.height * targetScale);
2921     CGFloat maxHorizontalOffset = futureContentSizeInSelfCoordinates.width - newBounds.size.width + _obscuredInsets.right;
2922     contentOffset.x = std::min(contentOffset.x, maxHorizontalOffset);
2923     CGFloat maxVerticalOffset = futureContentSizeInSelfCoordinates.height - newBounds.size.height + _obscuredInsets.bottom;
2924     contentOffset.y = std::min(contentOffset.y, maxVerticalOffset);
2925
2926     contentOffset.x = std::max(contentOffset.x, -_obscuredInsets.left);
2927     contentOffset.y = std::max(contentOffset.y, -_obscuredInsets.top);
2928
2929     // Make the top/bottom edges "sticky" within 1 pixel.
2930     if (oldUnobscuredContentRect.maxY() > contentSizeInContentViewCoordinates.height - 1)
2931         contentOffset.y = maxVerticalOffset;
2932     if (oldUnobscuredContentRect.y() < 1)
2933         contentOffset.y = -_obscuredInsets.top;
2934
2935     // FIXME: if we have content centered after double tap to zoom, we should also try to keep that rect in view.
2936     [_scrollView setContentSize:roundScrollViewContentSize(*_page, futureContentSizeInSelfCoordinates)];
2937     [_scrollView setContentOffset:contentOffset];
2938
2939     CGRect visibleRectInContentCoordinates = [self convertRect:newBounds toView:_contentView.get()];
2940     CGRect unobscuredRectInContentCoordinates = [self convertRect:futureUnobscuredRectInSelfCoordinates toView:_contentView.get()];
2941
2942     _page->dynamicViewportSizeUpdate(newMinimumLayoutSize, newMaximumUnobscuredSize, visibleRectInContentCoordinates, unobscuredRectInContentCoordinates, futureUnobscuredRectInSelfCoordinates, targetScale, newOrientation);
2943     if (WebKit::DrawingAreaProxy* drawingArea = _page->drawingArea())
2944         drawingArea->setSize(WebCore::IntSize(newBounds.size), WebCore::IntSize(), WebCore::IntSize());
2945 }
2946
2947 - (void)_endAnimatedResize
2948 {
2949     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::NotResizing)
2950         return;
2951
2952     _page->synchronizeDynamicViewportUpdate();
2953
2954     NSUInteger indexOfResizeAnimationView = [[_scrollView subviews] indexOfObject:_resizeAnimationView.get()];
2955     [_scrollView insertSubview:_contentView.get() atIndex:indexOfResizeAnimationView];
2956     [_scrollView insertSubview:[_contentView unscaledView] atIndex:indexOfResizeAnimationView + 1];
2957
2958     CALayer *contentViewLayer = [_contentView layer];
2959     CGFloat adjustmentScale = _resizeAnimationTransformAdjustments.m11;
2960     contentViewLayer.sublayerTransform = CATransform3DIdentity;
2961
2962     CGFloat animatingScaleTarget = [[_resizeAnimationView layer] transform].m11;
2963     CALayer *contentLayer = [_contentView layer];
2964     CATransform3D contentLayerTransform = contentLayer.transform;
2965     CGFloat currentScale = [[_resizeAnimationView layer] transform].m11 * contentLayerTransform.m11;
2966
2967     // We cannot use [UIScrollView setZoomScale:] directly because the UIScrollView delegate would get a callback with
2968     // an invalid contentOffset. The real content offset is only set below.
2969     // Since there is no public API for setting both the zoomScale and the contentOffset, we set the zoomScale manually
2970     // on the zoom layer and then only change the contentOffset.
2971     CGFloat adjustedScale = adjustmentScale * currentScale;
2972     contentLayerTransform.m11 = adjustedScale;
2973     contentLayerTransform.m22 = adjustedScale;
2974     contentLayer.transform = contentLayerTransform;
2975
2976     CGPoint currentScrollOffset = [_scrollView contentOffset];
2977     double horizontalScrollAdjustement = _resizeAnimationTransformAdjustments.m41 * animatingScaleTarget;
2978     double verticalScrollAdjustment = _resizeAnimationTransformAdjustments.m42 * animatingScaleTarget;
2979
2980     [_scrollView setContentSize:roundScrollViewContentSize(*_page, [_contentView frame].size)];
2981     [_scrollView setContentOffset:CGPointMake(currentScrollOffset.x - horizontalScrollAdjustement, currentScrollOffset.y - verticalScrollAdjustment)];
2982
2983     [_resizeAnimationView removeFromSuperview];
2984     _resizeAnimationView = nil;
2985     _resizeAnimationTransformAdjustments = CATransform3DIdentity;
2986
2987     _dynamicViewportUpdateMode = DynamicViewportUpdateMode::NotResizing;
2988     [_contentView setHidden:NO];
2989     [self _updateVisibleContentRects];
2990
2991     while (!_snapshotsDeferredDuringResize.isEmpty())
2992         _snapshotsDeferredDuringResize.takeLast()();
2993 }
2994
2995 - (void)_resizeWhileHidingContentWithUpdates:(void (^)(void))updateBlock
2996 {
2997     [self _beginAnimatedResizeWithUpdates:updateBlock];
2998     if (_dynamicViewportUpdateMode == DynamicViewportUpdateMode::ResizingWithAnimation) {
2999         [_contentView setHidden:YES];
3000         _dynamicViewportUpdateMode = DynamicViewportUpdateMode::ResizingWithDocumentHidden;
3001     }
3002 }
3003
3004 - (void)_setOverlaidAccessoryViewsInset:(CGSize)inset
3005 {
3006     [_customContentView web_setOverlaidAccessoryViewsInset:inset];
3007 }
3008
3009 - (void)_snapshotRect:(CGRect)rectInViewCoordinates intoImageOfWidth:(CGFloat)imageWidth completionHandler:(void(^)(CGImageRef))completionHandler
3010 {
3011     if (_dynamicViewportUpdateMode != DynamicViewportUpdateMode::NotResizing) {
3012         // Defer snapshotting until after the current resize completes.
3013         void (^copiedCompletionHandler)(CGImageRef) = [completionHandler copy];
3014         RetainPtr<WKWebView> retainedSelf = self;
3015         _snapshotsDeferredDuringResize.append([retainedSelf, rectInViewCoordinates, imageWidth, copiedCompletionHandler] {
3016             [retainedSelf _snapshotRect:rectInViewCoordinates intoImageOfWidth:imageWidth completionHandler:copiedCompletionHandler];
3017             [copiedCompletionHandler release];
3018         });
3019         return;
3020     }
3021
3022     CGRect snapshotRectInContentCoordinates = [self convertRect:rectInViewCoordinates toView:self._currentContentView];
3023     CGFloat imageScale = imageWidth / snapshotRectInContentCoordinates.size.width;
3024     CGFloat imageHeight = imageScale * snapshotRectInContentCoordinates.size.height;
3025     CGSize imageSize = CGSizeMake(imageWidth, imageHeight);
3026
3027 #if USE(IOSURFACE)
3028     // If we are parented and thus won't incur a significant penalty from paging in tiles, snapshot the view hierarchy directly.
3029     if (CADisplay *display = self.window.screen._display) {
3030         auto surface = WebCore::IOSurface::create(WebCore::expandedIntSize(WebCore::FloatSize(imageSize)), WebCore::ColorSpaceDeviceRGB);
3031         CGFloat imageScaleInViewCoordinates = imageWidth / rectInViewCoordinates.size.width;
3032         CATransform3D transform = CATransform3DMakeScale(imageScaleInViewCoordinates, imageScaleInViewCoordinates, 1);
3033         transform = CATransform3DTranslate(transform, -rectInViewCoordinates.origin.x, -rectInViewCoordinates.origin.y, 0);
3034         CARenderServerRenderDisplayLayerWithTransformAndTimeOffset(MACH_PORT_NULL, (CFStringRef)display.name, self.layer.context.contextId, reinterpret_cast<uint64_t>(self.layer), surface->surface(), 0, 0, &transform, 0);
3035         completionHandler(surface->createImage().get());
3036         return;
3037     }
3038 #endif
3039     
3040     if (_customContentView) {
3041         UIGraphicsBeginImageContextWithOptions(imageSize, YES, 1);
3042
3043         UIView *customContentView = _customContentView.get();
3044         [customContentView.backgroundColor set];
3045         UIRectFill(CGRectMake(0, 0, imageWidth, imageHeight));
3046
3047         CGContextRef context = UIGraphicsGetCurrentContext();
3048         CGContextTranslateCTM(context, -snapshotRectInContentCoordinates.origin.x * imageScale, -snapshotRectInContentCoordinates.origin.y * imageScale);
3049         CGContextScaleCTM(context, imageScale, imageScale);
3050         [customContentView.layer renderInContext:context];
3051
3052         completionHandler([UIGraphicsGetImageFromCurrentImageContext() CGImage]);
3053
3054         UIGraphicsEndImageContext();
3055         return;
3056     }
3057
3058     void(^copiedCompletionHandler)(CGImageRef) = [completionHandler copy];
3059     _page->takeSnapshot(WebCore::enclosingIntRect(snapshotRectInContentCoordinates), WebCore::expandedIntSize(WebCore::FloatSize(imageSize)), WebKit::SnapshotOptionsExcludeDeviceScaleFactor, [=](const WebKit::ShareableBitmap::Handle& imageHandle, WebKit::CallbackBase::Error) {
3060         if (imageHandle.isNull()) {
3061             copiedCompletionHandler(nullptr);
3062             [copiedCompletionHandler release];
3063             return;
3064         }
3065
3066         RefPtr<WebKit::ShareableBitmap> bitmap = WebKit::ShareableBitmap::create(imageHandle, WebKit::SharedMemory::Protection::ReadOnly);
3067
3068         if (!bitmap) {
3069             copiedCompletionHandler(nullptr);
3070             [copiedCompletionHandler release];
3071             return;
3072         }
3073
3074         RetainPtr<CGImageRef> cgImage;
3075         cgImage = bitmap->makeCGImage();
3076         copiedCompletionHandler(cgImage.get());
3077         [copiedCompletionHandler release];
3078     });
3079 }
3080
3081 - (void)_overrideLayoutParametersWithMinimumLayoutSize:(CGSize)minimumLayoutSize minimumLayoutSizeForMinimalUI:(CGSize)minimumLayoutSizeForMinimalUI maximumUnobscuredSizeOverride:(CGSize)maximumUnobscuredSizeOverride
3082 {
3083     UNUSED_PARAM(minimumLayoutSizeForMinimalUI);
3084     [self _overrideLayoutParametersWithMinimumLayoutSize:minimumLayoutSize maximumUnobscuredSizeOverride:maximumUnobscuredSizeOverride];
3085 }
3086
3087 - (void)_overrideLayoutParametersWithMinimumLayoutSize:(CGSize)minimumLayoutSize maximumUnobscuredSizeOverride:(CGSize)maximumUnobscuredSizeOverride
3088 {
3089     [self _setMinimumLayoutSizeOverride:minimumLayoutSize];
3090     [self _setMaximumUnobscuredSizeOverride:maximumUnobscuredSizeOverride];
3091 }
3092
3093 - (UIView *)_viewForFindUI
3094 {
3095     return [self viewForZoomingInScrollView:[self scrollView]];
3096 }
3097
3098 - (BOOL)_isDisplayingPDF
3099 {
3100     return [_customContentView isKindOfClass:[WKPDFView class]];
3101 }
3102
3103 - (NSData *)_dataForDisplayedPDF
3104 {
3105     if (![self _isDisplayingPDF])
3106         return nil;
3107     CGPDFDocumentRef pdfDocument = [(WKPDFView *)_customContentView pdfDocument];
3108     return [(NSData *)CGDataProviderCopyData(CGPDFDocumentGetDataProvider(pdfDocument)) autorelease];
3109 }
3110
3111 - (NSString *)_suggestedFilenameForDisplayedPDF
3112 {
3113     if (![self _isDisplayingPDF])
3114         return nil;
3115     return [(WKPDFView *)_customContentView.get() suggestedFilename];
3116 }
3117
3118 - (BOOL)_allowsDoubleTapGestures
3119 {
3120     if (_fastClickingIsDisabled)
3121         return YES;
3122
3123     // If the page is not user scalable, we don't allow double tap gestures.
3124     if (![_scrollView isZoomEnabled] || [_scrollView minimumZoomScale] >= [_scrollView maximumZoomScale])
3125         return NO;
3126
3127     // For scalable viewports, only disable double tap gestures if the viewport width is device width.
3128     if (_viewportMetaTagWidth != WebCore::ViewportArguments::ValueDeviceWidth)
3129         return YES;
3130
3131     return !areEssentiallyEqualAsFloat(contentZoomScale(self), _initialScaleFactor);
3132 }
3133
3134 - (_WKWebViewPrintFormatter *)_webViewPrintFormatter
3135 {
3136     UIViewPrintFormatter *viewPrintFormatter = self.viewPrintFormatter;
3137     ASSERT([viewPrintFormatter isKindOfClass:[_WKWebViewPrintFormatter class]]);
3138     return (_WKWebViewPrintFormatter *)viewPrintFormatter;
3139 }
3140
3141 #else // #if PLATFORM(IOS)
3142
3143 #pragma mark - OS X-specific methods
3144
3145 - (NSColor *)_pageExtendedBackgroundColor
3146 {
3147     WebCore::Color color = _page->pageExtendedBackgroundColor();
3148     if (!color.isValid())
3149         return nil;
3150
3151     return nsColor(color);
3152 }
3153
3154 - (BOOL)_drawsTransparentBackground
3155 {
3156     return _page->drawsTransparentBackground();
3157 }
3158
3159 - (void)_setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
3160 {
3161     _page->setDrawsTransparentBackground(drawsTransparentBackground);
3162 }
3163
3164 - (void)_setOverrideDeviceScaleFactor:(CGFloat)deviceScaleFactor
3165 {
3166     [_wkView _setOverrideDeviceScaleFactor:deviceScaleFactor];
3167 }
3168
3169 - (CGFloat)_overrideDeviceScaleFactor
3170 {
3171     return [_wkView _overrideDeviceScaleFactor];
3172 }
3173
3174 - (id)_immediateActionAnimationControllerForHitTestResult:(_WKHitTestResult *)hitTestResult withType:(_WKImmediateActionType)type userData:(id<NSSecureCoding>)userData
3175 {
3176     return nil;
3177 }
3178
3179 - (void)_setTopContentInset:(CGFloat)contentInset
3180 {
3181     [_wkView _setTopContentInset:contentInset];
3182 }
3183
3184 - (CGFloat)_topContentInset
3185 {
3186     return [_wkView _topContentInset];
3187 }
3188
3189 - (BOOL)_windowOcclusionDetectionEnabled
3190 {
3191     return [_wkView windowOcclusionDetectionEnabled];
3192 }
3193
3194 - (void)_setWindowOcclusionDetectionEnabled:(BOOL)flag
3195 {
3196     [_wkView setWindowOcclusionDetectionEnabled:flag];
3197 }
3198
3199 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
3200
3201 - (void)_setAutomaticallyAdjustsContentInsets:(BOOL)automaticallyAdjustsContentInsets
3202 {
3203     [_wkView _setAutomaticallyAdjustsContentInsets:automaticallyAdjustsContentInsets];
3204 }
3205
3206 - (BOOL)_automaticallyAdjustsContentInsets
3207 {
3208     return [_wkView _automaticallyAdjustsContentInsets];
3209 }
3210
3211 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
3212
3213 - (CGFloat)_minimumLayoutWidth
3214 {
3215     return _page->minimumLayoutSize().width();
3216 }
3217
3218 - (void)_setMinimumLayoutWidth:(CGFloat)width
3219 {
3220     BOOL expandsToFit = width > 0;
3221
3222     _page->setMinimumLayoutSize(WebCore::IntSize(width, 0));
3223     _page->setMainFrameIsScrollable(!expandsToFit);
3224
3225     [_wkView setShouldClipToVisibleRect:expandsToFit];
3226 }
3227
3228 #endif
3229
3230 @end
3231
3232
3233 @implementation WKWebView (WKTesting)
3234
3235 #if PLATFORM(IOS)
3236
3237 - (CGRect)_contentVisibleRect
3238 {
3239     return [self convertRect:[self bounds] toView:self._currentContentView];
3240 }
3241
3242 - (CGPoint)_convertPointFromContentsToView:(CGPoint)point
3243 {
3244     return [self convertPoint:point fromView:self._currentContentView];
3245 }
3246
3247 - (CGPoint)_convertPointFromViewToContents:(CGPoint)point
3248 {
3249     return [self convertPoint:point toView:self._currentContentView];
3250 }
3251
3252 #endif // PLATFORM(IOS)
3253
3254 // Execute the supplied block after the next transaction from the WebProcess.
3255 - (void)_doAfterNextPresentationUpdate:(void (^)(void))updateBlock
3256 {
3257     void (^updateBlockCopy)(void) = nil;
3258     if (updateBlock)
3259         updateBlockCopy = Block_copy(updateBlock);
3260
3261     _page->callAfterNextPresentationUpdate([updateBlockCopy](WebKit::CallbackBase::Error error) {
3262         if (updateBlockCopy) {
3263             updateBlockCopy();
3264             Block_release(updateBlockCopy);
3265         }
3266     });
3267 }
3268
3269 @end
3270
3271
3272 #if PLATFORM(MAC)
3273
3274 @implementation WKWebView (WKIBActions)
3275
3276 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
3277 {
3278     SEL action = item.action;
3279
3280     if (action == @selector(goBack:))
3281         return !!_page->backForwardList().backItem();
3282
3283     if (action == @selector(goForward:))
3284         return !!_page->backForwardList().forwardItem();
3285
3286     if (action == @selector(stopLoading:)) {
3287         // FIXME: Return no if we're stopped.
3288         return YES;
3289     }
3290
3291     if (action == @selector(reload:) || action == @selector(reloadFromOrigin:)) {
3292         // FIXME: Return no if we're loading.
3293         return YES;
3294     }
3295
3296     return NO;
3297 }
3298
3299 - (IBAction)goBack:(id)sender
3300 {
3301     [self goBack];
3302 }
3303
3304 - (IBAction)goForward:(id)sender
3305 {
3306     [self goForward];
3307 }
3308
3309 - (IBAction)reload:(id)sender
3310 {
3311     [self reload];
3312 }
3313
3314 - (IBAction)reloadFromOrigin:(id)sender
3315 {
3316     [self reloadFromOrigin];
3317 }
3318
3319 - (IBAction)stopLoading:(id)sender
3320 {
3321     _page->stopLoading();
3322 }
3323
3324 @end
3325
3326 #endif // PLATFORM(MAC)
3327
3328 #if PLATFORM(IOS)
3329 @implementation WKWebView (_WKWebViewPrintFormatter)
3330
3331 - (Class)_printFormatterClass
3332 {
3333     return [_WKWebViewPrintFormatter class];
3334 }
3335
3336 - (NSInteger)_computePageCountAndStartDrawingToPDFForFrame:(_WKFrameHandle *)frame printInfo:(const WebKit::PrintInfo&)printInfo firstPage:(uint32_t)firstPage computedTotalScaleFactor:(double&)totalScaleFactor
3337 {
3338     if ([self _isDisplayingPDF])
3339         return CGPDFDocumentGetNumberOfPages([(WKPDFView *)_customContentView pdfDocument]);
3340
3341     _pageIsPrintingToPDF = YES;
3342     Vector<WebCore::IntRect> pageRects;
3343     uint64_t frameID = frame ? frame._frameID : _page->mainFrame()->frameID();
3344     if (!_page->sendSync(Messages::WebPage::ComputePagesForPrintingAndStartDrawingToPDF(frameID, printInfo, firstPage), Messages::WebPage::ComputePagesForPrintingAndStartDrawingToPDF::Reply(pageRects, totalScaleFactor)))
3345         return 0;
3346     return pageRects.size();
3347 }
3348
3349 - (void)_endPrinting
3350 {
3351     _pageIsPrintingToPDF = NO;
3352     _printedDocument = nullptr;
3353     _page->send(Messages::WebPage::EndPrinting());
3354 }
3355
3356 // FIXME: milliseconds::max() overflows when converted to nanoseconds, causing condition_variable::wait_for() to believe
3357 // a timeout occurred on any spurious wakeup. Use nanoseconds::max() (converted to ms) to avoid this. We should perhaps
3358 // change waitForAndDispatchImmediately() to take nanoseconds to avoid this issue.
3359 static constexpr std::chrono::milliseconds didFinishLoadingTimeout = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::nanoseconds::max());
3360
3361 - (CGPDFDocumentRef)_printedDocument
3362 {
3363     if ([self _isDisplayingPDF]) {
3364         ASSERT(!_pageIsPrintingToPDF);
3365         return [(WKPDFView *)_customContentView pdfDocument];
3366     }
3367
3368     if (_pageIsPrintingToPDF) {
3369         if (!_page->process().connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DidFinishDrawingPagesToPDF>(_page->pageID(), didFinishLoadingTimeout)) {
3370             ASSERT_NOT_REACHED();
3371             return nullptr;
3372         }
3373         ASSERT(!_pageIsPrintingToPDF);
3374     }
3375     return _printedDocument.get();
3376 }
3377
3378 - (void)_setPrintedDocument:(CGPDFDocumentRef)printedDocument
3379 {
3380     if (!_pageIsPrintingToPDF)
3381         return;
3382     ASSERT(![self _isDisplayingPDF]);
3383     _printedDocument = printedDocument;
3384     _pageIsPrintingToPDF = NO;
3385 }
3386
3387 @end
3388 #endif
3389
3390 #endif // WK_API_ENABLED