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