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