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