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