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