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