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