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