Use MPAVRoutingController instead of deprecated versions.
[WebKit-https.git] / Source / WebKit / UIProcess / ios / WKContentViewInteraction.mm
1 /*
2  * Copyright (C) 2012-2017 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 "WKContentViewInteraction.h"
28
29 #if PLATFORM(IOS)
30
31 #import "APIUIClient.h"
32 #import "EditingRange.h"
33 #import "InputViewUpdateDeferrer.h"
34 #import "Logging.h"
35 #import "ManagedConfigurationSPI.h"
36 #import "NativeWebKeyboardEvent.h"
37 #import "NativeWebTouchEvent.h"
38 #import "RemoteLayerTreeDrawingAreaProxy.h"
39 #import "SmartMagnificationController.h"
40 #import "TextInputSPI.h"
41 #import "UIKitSPI.h"
42 #import "WKActionSheetAssistant.h"
43 #import "WKFormInputControl.h"
44 #import "WKFormSelectControl.h"
45 #import "WKImagePreviewViewController.h"
46 #import "WKInspectorNodeSearchGestureRecognizer.h"
47 #import "WKNSURLExtras.h"
48 #import "WKPreviewActionItemIdentifiers.h"
49 #import "WKPreviewActionItemInternal.h"
50 #import "WKPreviewElementInfoInternal.h"
51 #import "WKUIDelegatePrivate.h"
52 #import "WKWebViewConfiguration.h"
53 #import "WKWebViewConfigurationPrivate.h"
54 #import "WKWebViewInternal.h"
55 #import "WKWebViewPrivate.h"
56 #import "WebEvent.h"
57 #import "WebIOSEventFactory.h"
58 #import "WebPageMessages.h"
59 #import "WebProcessProxy.h"
60 #import "_WKActivatedElementInfoInternal.h"
61 #import "_WKElementAction.h"
62 #import "_WKFocusedElementInfo.h"
63 #import "_WKFormInputSession.h"
64 #import "_WKInputDelegate.h"
65 #import <CoreText/CTFont.h>
66 #import <CoreText/CTFontDescriptor.h>
67 #import <MobileCoreServices/UTCoreTypes.h>
68 #import <WebCore/Color.h>
69 #import <WebCore/CoreGraphicsSPI.h>
70 #import <WebCore/DataDetectorsCoreSPI.h>
71 #import <WebCore/DataDetectorsUISPI.h>
72 #import <WebCore/FloatQuad.h>
73 #import <WebCore/NotImplemented.h>
74 #import <WebCore/Pasteboard.h>
75 #import <WebCore/Path.h>
76 #import <WebCore/PathUtilities.h>
77 #import <WebCore/RuntimeApplicationChecks.h>
78 #import <WebCore/Scrollbar.h>
79 #import <WebCore/TextIndicator.h>
80 #import <WebCore/TextStream.h>
81 #import <WebCore/VisibleSelection.h>
82 #import <WebCore/WebCoreNSURLExtras.h>
83 #import <WebCore/WebEvent.h>
84 #import <WebKit/WebSelectionRect.h> // FIXME: WK2 should not include WebKit headers!
85 #import <wtf/Optional.h>
86 #import <wtf/RetainPtr.h>
87 #import <wtf/SetForScope.h>
88 #import <wtf/SoftLinking.h>
89
90 #if ENABLE(DRAG_SUPPORT)
91 #import <WebCore/DragData.h>
92 #import <WebCore/DragItem.h>
93 #import <WebCore/PlatformPasteboard.h>
94 #import <WebCore/WebItemProviderPasteboard.h>
95 #endif
96
97 @interface UIEvent(UIEventInternal)
98 @property (nonatomic, assign) UIKeyboardInputFlags _inputFlags;
99 @end
100
101 @interface WKWebEvent : WebEvent
102 @property (nonatomic, retain) UIEvent *uiEvent;
103 @end
104
105 @implementation WKWebEvent
106
107 - (void)dealloc
108 {
109     [_uiEvent release];
110     [super dealloc];
111 }
112
113 @end
114
115 using namespace WebCore;
116 using namespace WebKit;
117
118 namespace WebKit {
119
120 WKSelectionDrawingInfo::WKSelectionDrawingInfo()
121     : type(SelectionType::None)
122 {
123 }
124
125 WKSelectionDrawingInfo::WKSelectionDrawingInfo(const EditorState& editorState)
126 {
127     if (editorState.selectionIsNone) {
128         type = SelectionType::None;
129         return;
130     }
131
132     if (editorState.isInPlugin) {
133         type = SelectionType::Plugin;
134         return;
135     }
136
137     type = SelectionType::Range;
138     auto& postLayoutData = editorState.postLayoutData();
139     caretRect = postLayoutData.caretRectAtEnd;
140     selectionRects = postLayoutData.selectionRects;
141 }
142
143 inline bool operator==(const WKSelectionDrawingInfo& a, const WKSelectionDrawingInfo& b)
144 {
145     if (a.type != b.type)
146         return false;
147
148     if (a.type == WKSelectionDrawingInfo::SelectionType::Range) {
149         if (a.caretRect != b.caretRect)
150             return false;
151
152         if (a.selectionRects.size() != b.selectionRects.size())
153             return false;
154
155         for (unsigned i = 0; i < a.selectionRects.size(); ++i) {
156             if (a.selectionRects[i].rect() != b.selectionRects[i].rect())
157                 return false;
158         }
159     }
160
161     return true;
162 }
163
164 inline bool operator!=(const WKSelectionDrawingInfo& a, const WKSelectionDrawingInfo& b)
165 {
166     return !(a == b);
167 }
168
169 static WebCore::TextStream& operator<<(WebCore::TextStream& stream, WKSelectionDrawingInfo::SelectionType type)
170 {
171     switch (type) {
172     case WKSelectionDrawingInfo::SelectionType::None: stream << "none"; break;
173     case WKSelectionDrawingInfo::SelectionType::Plugin: stream << "plugin"; break;
174     case WKSelectionDrawingInfo::SelectionType::Range: stream << "range"; break;
175     }
176     
177     return stream;
178 }
179
180 WebCore::TextStream& operator<<(WebCore::TextStream& stream, const WKSelectionDrawingInfo& info)
181 {
182     TextStream::GroupScope group(stream);
183     stream.dumpProperty("type", info.type);
184     stream.dumpProperty("caret rect", info.caretRect);
185     stream.dumpProperty("selection rects", info.selectionRects);
186     return stream;
187 }
188
189 } // namespace WebKit
190
191 static const float highlightDelay = 0.12;
192 static const float tapAndHoldDelay  = 0.75;
193 const CGFloat minimumTapHighlightRadius = 2.0;
194
195 @interface WKTextRange : UITextRange {
196     CGRect _startRect;
197     CGRect _endRect;
198     BOOL _isNone;
199     BOOL _isRange;
200     BOOL _isEditable;
201     NSArray *_selectionRects;
202     NSUInteger _selectedTextLength;
203 }
204 @property (nonatomic) CGRect startRect;
205 @property (nonatomic) CGRect endRect;
206 @property (nonatomic) BOOL isNone;
207 @property (nonatomic) BOOL isRange;
208 @property (nonatomic) BOOL isEditable;
209 @property (nonatomic) NSUInteger selectedTextLength;
210 @property (copy, nonatomic) NSArray *selectionRects;
211
212 + (WKTextRange *)textRangeWithState:(BOOL)isNone isRange:(BOOL)isRange isEditable:(BOOL)isEditable startRect:(CGRect)startRect endRect:(CGRect)endRect selectionRects:(NSArray *)selectionRects selectedTextLength:(NSUInteger)selectedTextLength;
213
214 @end
215
216 @interface WKTextPosition : UITextPosition {
217     CGRect _positionRect;
218 }
219
220 @property (nonatomic) CGRect positionRect;
221
222 + (WKTextPosition *)textPositionWithRect:(CGRect)positionRect;
223
224 @end
225
226 @interface WKTextSelectionRect : UITextSelectionRect
227
228 @property (nonatomic, retain) WebSelectionRect *webRect;
229
230 + (NSArray *)textSelectionRectsWithWebRects:(NSArray *)webRects;
231
232 @end
233
234 @interface WKAutocorrectionRects : UIWKAutocorrectionRects
235 + (WKAutocorrectionRects *)autocorrectionRectsWithRects:(CGRect)firstRect lastRect:(CGRect)lastRect;
236 @end
237
238 @interface WKAutocorrectionContext : UIWKAutocorrectionContext
239 + (WKAutocorrectionContext *)autocorrectionContextWithData:(NSString *)beforeText markedText:(NSString *)markedText selectedText:(NSString *)selectedText afterText:(NSString *)afterText selectedRangeInMarkedText:(NSRange)range;
240 @end
241
242 @interface UITextInteractionAssistant (UITextInteractionAssistant_Internal)
243 // FIXME: this needs to be moved from the internal header to the private.
244 - (id)initWithView:(UIResponder <UITextInput> *)view;
245 - (void)selectWord;
246 - (void)scheduleReanalysis;
247 @end
248
249 @interface UIView (UIViewInternalHack)
250 + (BOOL)_addCompletion:(void(^)(BOOL))completion;
251 @end
252
253 @protocol UISelectionInteractionAssistant;
254 #if HAVE(LINK_PREVIEW)
255 @interface UIPreviewItemController (StagingToRemove)
256 @property (strong, nonatomic, readonly) UIGestureRecognizer *presentationSecondaryGestureRecognizer;
257 @end
258 #endif
259
260 @interface WKFocusedElementInfo : NSObject <_WKFocusedElementInfo>
261 - (instancetype)initWithAssistedNodeInformation:(const AssistedNodeInformation&)information isUserInitiated:(BOOL)isUserInitiated;
262 @end
263
264 @interface WKFormInputSession : NSObject <_WKFormInputSession>
265
266 - (instancetype)initWithContentView:(WKContentView *)view focusedElementInfo:(WKFocusedElementInfo *)elementInfo userObject:(NSObject <NSSecureCoding> *)userObject;
267 - (void)invalidate;
268
269 @end
270
271 @implementation WKFormInputSession {
272     WKContentView *_contentView;
273     RetainPtr<NSObject <NSSecureCoding>> _userObject;
274     RetainPtr<WKFocusedElementInfo> _focusedElementInfo;
275     RetainPtr<UIView> _customInputView;
276     RetainPtr<NSArray<UITextSuggestion *>> _suggestions;
277     BOOL _accessoryViewShouldNotShow;
278     BOOL _forceSecureTextEntry;
279 }
280
281 - (instancetype)initWithContentView:(WKContentView *)view focusedElementInfo:(WKFocusedElementInfo *)elementInfo userObject:(NSObject <NSSecureCoding> *)userObject
282 {
283     if (!(self = [super init]))
284         return nil;
285
286     _contentView = view;
287     _focusedElementInfo = elementInfo;
288     _userObject = userObject;
289
290     return self;
291 }
292
293 - (id <_WKFocusedElementInfo>)focusedElementInfo
294 {
295     return _focusedElementInfo.get();
296 }
297
298 - (NSObject <NSSecureCoding> *)userObject
299 {
300     return _userObject.get();
301 }
302
303 - (BOOL)isValid
304 {
305     return _contentView != nil;
306 }
307
308 - (NSString *)accessoryViewCustomButtonTitle
309 {
310     return [[[_contentView formAccessoryView] _autofill] title];
311 }
312
313 - (void)setAccessoryViewCustomButtonTitle:(NSString *)title
314 {
315     if (title.length)
316         [[_contentView formAccessoryView] showAutoFillButtonWithTitle:title];
317     else
318         [[_contentView formAccessoryView] hideAutoFillButton];
319     if (UICurrentUserInterfaceIdiomIsPad())
320         [_contentView reloadInputViews];
321 }
322
323 - (BOOL)accessoryViewShouldNotShow
324 {
325     return _accessoryViewShouldNotShow;
326 }
327
328 - (void)setAccessoryViewShouldNotShow:(BOOL)accessoryViewShouldNotShow
329 {
330     if (_accessoryViewShouldNotShow == accessoryViewShouldNotShow)
331         return;
332
333     _accessoryViewShouldNotShow = accessoryViewShouldNotShow;
334     [_contentView reloadInputViews];
335 }
336
337 - (BOOL)forceSecureTextEntry
338 {
339     return _forceSecureTextEntry;
340 }
341
342 - (void)setForceSecureTextEntry:(BOOL)forceSecureTextEntry
343 {
344     if (_forceSecureTextEntry == forceSecureTextEntry)
345         return;
346
347     _forceSecureTextEntry = forceSecureTextEntry;
348     [_contentView reloadInputViews];
349 }
350
351 - (UIView *)customInputView
352 {
353     return _customInputView.get();
354 }
355
356 - (void)setCustomInputView:(UIView *)customInputView
357 {
358     if (customInputView == _customInputView)
359         return;
360
361     _customInputView = customInputView;
362     [_contentView reloadInputViews];
363 }
364
365 - (NSArray<UITextSuggestion *> *)suggestions
366 {
367     return _suggestions.get();
368 }
369
370 - (void)setSuggestions:(NSArray<UITextSuggestion *> *)suggestions
371 {
372     id <UITextInputSuggestionDelegate> suggestionDelegate = (id <UITextInputSuggestionDelegate>)_contentView.inputDelegate;
373     _suggestions = adoptNS([suggestions copy]);
374     [suggestionDelegate setSuggestions:suggestions];
375 }
376
377 - (void)invalidate
378 {
379     id <UITextInputSuggestionDelegate> suggestionDelegate = (id <UITextInputSuggestionDelegate>)_contentView.inputDelegate;
380     [suggestionDelegate setSuggestions:nil];
381     _contentView = nil;
382 }
383
384 @end
385
386 @implementation WKFocusedElementInfo {
387     WKInputType _type;
388     RetainPtr<NSString> _value;
389     BOOL _isUserInitiated;
390 }
391
392 - (instancetype)initWithAssistedNodeInformation:(const AssistedNodeInformation&)information isUserInitiated:(BOOL)isUserInitiated
393 {
394     if (!(self = [super init]))
395         return nil;
396
397     switch (information.elementType) {
398     case WebKit::InputType::ContentEditable:
399         _type = WKInputTypeContentEditable;
400         break;
401     case WebKit::InputType::Text:
402         _type = WKInputTypeText;
403         break;
404     case WebKit::InputType::Password:
405         _type = WKInputTypePassword;
406         break;
407     case WebKit::InputType::TextArea:
408         _type = WKInputTypeTextArea;
409         break;
410     case WebKit::InputType::Search:
411         _type = WKInputTypeSearch;
412         break;
413     case WebKit::InputType::Email:
414         _type = WKInputTypeEmail;
415         break;
416     case WebKit::InputType::URL:
417         _type = WKInputTypeURL;
418         break;
419     case WebKit::InputType::Phone:
420         _type = WKInputTypePhone;
421         break;
422     case WebKit::InputType::Number:
423         _type = WKInputTypeNumber;
424         break;
425     case WebKit::InputType::NumberPad:
426         _type = WKInputTypeNumberPad;
427         break;
428     case WebKit::InputType::Date:
429         _type = WKInputTypeDate;
430         break;
431     case WebKit::InputType::DateTime:
432         _type = WKInputTypeDateTime;
433         break;
434     case WebKit::InputType::DateTimeLocal:
435         _type = WKInputTypeDateTimeLocal;
436         break;
437     case WebKit::InputType::Month:
438         _type = WKInputTypeMonth;
439         break;
440     case WebKit::InputType::Week:
441         _type = WKInputTypeWeek;
442         break;
443     case WebKit::InputType::Time:
444         _type = WKInputTypeTime;
445         break;
446     case WebKit::InputType::Select:
447         _type = WKInputTypeSelect;
448         break;
449     case WebKit::InputType::None:
450         _type = WKInputTypeNone;
451         break;
452     }
453     _value = information.value;
454     _isUserInitiated = isUserInitiated;
455     return self;
456 }
457
458 - (WKInputType)type
459 {
460     return _type;
461 }
462
463 - (NSString *)value
464 {
465     return _value.get();
466 }
467
468 - (BOOL)isUserInitiated
469 {
470     return _isUserInitiated;
471 }
472 @end
473
474 @interface WKContentView (WKInteractionPrivate)
475 - (void)accessibilitySpeakSelectionSetContent:(NSString *)string;
476 - (NSArray *)webSelectionRectsForSelectionRects:(const Vector<WebCore::SelectionRect>&)selectionRects;
477 - (void)_accessibilityDidGetSelectionRects:(NSArray *)selectionRects withGranularity:(UITextGranularity)granularity atOffset:(NSInteger)offset;
478 @end
479
480 @implementation WKContentView (WKInteraction)
481
482 - (void)_createAndConfigureDoubleTapGestureRecognizer
483 {
484     _doubleTapGestureRecognizer = adoptNS([[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_doubleTapRecognized:)]);
485     [_doubleTapGestureRecognizer setNumberOfTapsRequired:2];
486     [_doubleTapGestureRecognizer setDelegate:self];
487     [self addGestureRecognizer:_doubleTapGestureRecognizer.get()];
488     [_singleTapGestureRecognizer requireGestureRecognizerToFail:_doubleTapGestureRecognizer.get()];
489 }
490
491 - (void)_createAndConfigureLongPressGestureRecognizer
492 {
493     _longPressGestureRecognizer = adoptNS([[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(_longPressRecognized:)]);
494     [_longPressGestureRecognizer setDelay:tapAndHoldDelay];
495     [_longPressGestureRecognizer setDelegate:self];
496     [_longPressGestureRecognizer _setRequiresQuietImpulse:YES];
497     [self addGestureRecognizer:_longPressGestureRecognizer.get()];
498 }
499
500 - (void)setupInteraction
501 {
502     if (!_interactionViewsContainerView) {
503         _interactionViewsContainerView = adoptNS([[UIView alloc] init]);
504         [_interactionViewsContainerView layer].name = @"InteractionViewsContainer";
505         [_interactionViewsContainerView setOpaque:NO];
506         [_interactionViewsContainerView layer].anchorPoint = CGPointZero;
507         [self.superview addSubview:_interactionViewsContainerView.get()];
508     }
509
510     [self.layer addObserver:self forKeyPath:@"transform" options:NSKeyValueObservingOptionInitial context:nil];
511
512     _touchEventGestureRecognizer = adoptNS([[UIWebTouchEventsGestureRecognizer alloc] initWithTarget:self action:@selector(_webTouchEventsRecognized:) touchDelegate:self]);
513     [_touchEventGestureRecognizer setDelegate:self];
514     [self addGestureRecognizer:_touchEventGestureRecognizer.get()];
515
516     _singleTapGestureRecognizer = adoptNS([[WKSyntheticClickTapGestureRecognizer alloc] initWithTarget:self action:@selector(_singleTapCommited:)]);
517     [_singleTapGestureRecognizer setDelegate:self];
518     [_singleTapGestureRecognizer setGestureRecognizedTarget:self action:@selector(_singleTapRecognized:)];
519     [_singleTapGestureRecognizer setResetTarget:self action:@selector(_singleTapDidReset:)];
520     [self addGestureRecognizer:_singleTapGestureRecognizer.get()];
521
522     _nonBlockingDoubleTapGestureRecognizer = adoptNS([[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_nonBlockingDoubleTapRecognized:)]);
523     [_nonBlockingDoubleTapGestureRecognizer setNumberOfTapsRequired:2];
524     [_nonBlockingDoubleTapGestureRecognizer setDelegate:self];
525     [_nonBlockingDoubleTapGestureRecognizer setEnabled:NO];
526     [self addGestureRecognizer:_nonBlockingDoubleTapGestureRecognizer.get()];
527
528     [self _createAndConfigureDoubleTapGestureRecognizer];
529
530     _twoFingerDoubleTapGestureRecognizer = adoptNS([[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_twoFingerDoubleTapRecognized:)]);
531     [_twoFingerDoubleTapGestureRecognizer setNumberOfTapsRequired:2];
532     [_twoFingerDoubleTapGestureRecognizer setNumberOfTouchesRequired:2];
533     [_twoFingerDoubleTapGestureRecognizer setDelegate:self];
534     [self addGestureRecognizer:_twoFingerDoubleTapGestureRecognizer.get()];
535
536     _highlightLongPressGestureRecognizer = adoptNS([[_UIWebHighlightLongPressGestureRecognizer alloc] initWithTarget:self action:@selector(_highlightLongPressRecognized:)]);
537     [_highlightLongPressGestureRecognizer setDelay:highlightDelay];
538     [_highlightLongPressGestureRecognizer setDelegate:self];
539     [self addGestureRecognizer:_highlightLongPressGestureRecognizer.get()];
540
541     [self _createAndConfigureLongPressGestureRecognizer];
542
543 #if ENABLE(DATA_INTERACTION)
544     [self setupDataInteractionDelegates];
545 #endif
546
547     _twoFingerSingleTapGestureRecognizer = adoptNS([[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_twoFingerSingleTapGestureRecognized:)]);
548     [_twoFingerSingleTapGestureRecognizer setAllowableMovement:60];
549     [_twoFingerSingleTapGestureRecognizer _setAllowableSeparation:150];
550     [_twoFingerSingleTapGestureRecognizer setNumberOfTapsRequired:1];
551     [_twoFingerSingleTapGestureRecognizer setNumberOfTouchesRequired:2];
552     [_twoFingerSingleTapGestureRecognizer setDelaysTouchesEnded:NO];
553     [_twoFingerSingleTapGestureRecognizer setDelegate:self];
554     [self addGestureRecognizer:_twoFingerSingleTapGestureRecognizer.get()];
555
556 #if HAVE(LINK_PREVIEW)
557     [self _registerPreview];
558 #endif
559
560     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_resetShowingTextStyle:) name:UIMenuControllerDidHideMenuNotification object:nil];
561     _showingTextStyleOptions = NO;
562
563     // FIXME: This should be called when we get notified that loading has completed.
564     [self useSelectionAssistantWithGranularity:_webView._selectionGranularity];
565     
566     _actionSheetAssistant = adoptNS([[WKActionSheetAssistant alloc] initWithView:self]);
567     [_actionSheetAssistant setDelegate:self];
568     _smartMagnificationController = std::make_unique<SmartMagnificationController>(self);
569     _isExpectingFastSingleTapCommit = NO;
570     _potentialTapInProgress = NO;
571     _isDoubleTapPending = NO;
572     _showDebugTapHighlightsForFastClicking = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitShowFastClickDebugTapHighlights"];
573     _needsDeferredEndScrollingSelectionUpdate = NO;
574 }
575
576 - (void)cleanupInteraction
577 {
578     _webSelectionAssistant = nil;
579     _textSelectionAssistant = nil;
580     
581     [_actionSheetAssistant cleanupSheet];
582     _actionSheetAssistant = nil;
583     
584     _smartMagnificationController = nil;
585     _didAccessoryTabInitiateFocus = NO;
586     _isExpectingFastSingleTapCommit = NO;
587     _needsDeferredEndScrollingSelectionUpdate = NO;
588     [_formInputSession invalidate];
589     _formInputSession = nil;
590     [_highlightView removeFromSuperview];
591     _outstandingPositionInformationRequest = std::nullopt;
592
593     if (_interactionViewsContainerView) {
594         [self.layer removeObserver:self forKeyPath:@"transform"];
595         [_interactionViewsContainerView removeFromSuperview];
596         _interactionViewsContainerView = nil;
597     }
598
599     [_touchEventGestureRecognizer setDelegate:nil];
600     [self removeGestureRecognizer:_touchEventGestureRecognizer.get()];
601
602     [_singleTapGestureRecognizer setDelegate:nil];
603     [_singleTapGestureRecognizer setGestureRecognizedTarget:nil action:nil];
604     [_singleTapGestureRecognizer setResetTarget:nil action:nil];
605     [self removeGestureRecognizer:_singleTapGestureRecognizer.get()];
606
607     [_highlightLongPressGestureRecognizer setDelegate:nil];
608     [self removeGestureRecognizer:_highlightLongPressGestureRecognizer.get()];
609
610     [_longPressGestureRecognizer setDelegate:nil];
611     [self removeGestureRecognizer:_longPressGestureRecognizer.get()];
612
613     [_doubleTapGestureRecognizer setDelegate:nil];
614     [self removeGestureRecognizer:_doubleTapGestureRecognizer.get()];
615
616     [_nonBlockingDoubleTapGestureRecognizer setDelegate:nil];
617     [self removeGestureRecognizer:_nonBlockingDoubleTapGestureRecognizer.get()];
618
619     [_twoFingerDoubleTapGestureRecognizer setDelegate:nil];
620     [self removeGestureRecognizer:_twoFingerDoubleTapGestureRecognizer.get()];
621
622     [_twoFingerSingleTapGestureRecognizer setDelegate:nil];
623     [self removeGestureRecognizer:_twoFingerSingleTapGestureRecognizer.get()];
624
625     _layerTreeTransactionIdAtLastTouchStart = 0;
626
627 #if ENABLE(DATA_INTERACTION)
628     [self teardownDataInteractionDelegates];
629 #endif
630
631     _inspectorNodeSearchEnabled = NO;
632     if (_inspectorNodeSearchGestureRecognizer) {
633         [_inspectorNodeSearchGestureRecognizer setDelegate:nil];
634         [self removeGestureRecognizer:_inspectorNodeSearchGestureRecognizer.get()];
635         _inspectorNodeSearchGestureRecognizer = nil;
636     }
637
638 #if HAVE(LINK_PREVIEW)
639     [self _unregisterPreview];
640 #endif
641
642     if (_fileUploadPanel) {
643         [_fileUploadPanel setDelegate:nil];
644         [_fileUploadPanel dismiss];
645         _fileUploadPanel = nil;
646     }
647     
648     _inputViewUpdateDeferrer = nullptr;
649 }
650
651 - (void)_removeDefaultGestureRecognizers
652 {
653     [self removeGestureRecognizer:_touchEventGestureRecognizer.get()];
654     [self removeGestureRecognizer:_singleTapGestureRecognizer.get()];
655     [self removeGestureRecognizer:_highlightLongPressGestureRecognizer.get()];
656     [self removeGestureRecognizer:_doubleTapGestureRecognizer.get()];
657     [self removeGestureRecognizer:_nonBlockingDoubleTapGestureRecognizer.get()];
658     [self removeGestureRecognizer:_twoFingerDoubleTapGestureRecognizer.get()];
659     [self removeGestureRecognizer:_twoFingerSingleTapGestureRecognizer.get()];
660 }
661
662 - (void)_addDefaultGestureRecognizers
663 {
664     [self addGestureRecognizer:_touchEventGestureRecognizer.get()];
665     [self addGestureRecognizer:_singleTapGestureRecognizer.get()];
666     [self addGestureRecognizer:_highlightLongPressGestureRecognizer.get()];
667     [self addGestureRecognizer:_doubleTapGestureRecognizer.get()];
668     [self addGestureRecognizer:_nonBlockingDoubleTapGestureRecognizer.get()];
669     [self addGestureRecognizer:_twoFingerDoubleTapGestureRecognizer.get()];
670     [self addGestureRecognizer:_twoFingerSingleTapGestureRecognizer.get()];
671 }
672
673 - (UIView*)unscaledView
674 {
675     return _interactionViewsContainerView.get();
676 }
677
678 - (CGFloat)inverseScale
679 {
680     return 1 / [[self layer] transform].m11;
681 }
682
683 - (UIScrollView *)_scroller
684 {
685     return [_webView scrollView];
686 }
687
688 - (CGRect)unobscuredContentRect
689 {
690     return _page->unobscuredContentRect();
691 }
692
693 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
694 {
695     ASSERT([keyPath isEqualToString:@"transform"]);
696     ASSERT(object == self.layer);
697
698     if ([UIView _isInAnimationBlock] && _page->editorState().selectionIsNone) {
699         // If the utility views are not already visible, we don't want them to become visible during the animation since
700         // they could not start from a reasonable state.
701         // This is not perfect since views could also get updated during the animation, in practice this is rare and the end state
702         // remains correct.
703         [self _cancelInteraction];
704         [_interactionViewsContainerView setHidden:YES];
705         [UIView _addCompletion:^(BOOL){ [_interactionViewsContainerView setHidden:NO]; }];
706     }
707
708     _selectionNeedsUpdate = YES;
709     [self _updateChangedSelection:YES];
710     [self _updateTapHighlight];
711 }
712
713 - (void)_enableInspectorNodeSearch
714 {
715     _inspectorNodeSearchEnabled = YES;
716
717     [self _cancelInteraction];
718
719     [self _removeDefaultGestureRecognizers];
720     _inspectorNodeSearchGestureRecognizer = adoptNS([[WKInspectorNodeSearchGestureRecognizer alloc] initWithTarget:self action:@selector(_inspectorNodeSearchRecognized:)]);
721     [self addGestureRecognizer:_inspectorNodeSearchGestureRecognizer.get()];
722 }
723
724 - (void)_disableInspectorNodeSearch
725 {
726     _inspectorNodeSearchEnabled = NO;
727
728     [self _addDefaultGestureRecognizers];
729     [self removeGestureRecognizer:_inspectorNodeSearchGestureRecognizer.get()];
730     _inspectorNodeSearchGestureRecognizer = nil;
731 }
732
733 - (UIView *)hitTest:(CGPoint)point withEvent:(::UIEvent *)event
734 {
735     for (UIView *subView in [_interactionViewsContainerView.get() subviews]) {
736         UIView *hitView = [subView hitTest:[subView convertPoint:point fromView:self] withEvent:event];
737         if (hitView)
738             return hitView;
739     }
740     return [super hitTest:point withEvent:event];
741 }
742
743 - (const InteractionInformationAtPosition&)positionInformation
744 {
745     return _positionInformation;
746 }
747
748 - (void)setInputDelegate:(id <UITextInputDelegate>)inputDelegate
749 {
750     _inputDelegate = inputDelegate;
751 }
752
753 - (id <UITextInputDelegate>)inputDelegate
754 {
755     return _inputDelegate;
756 }
757
758 - (CGPoint)lastInteractionLocation
759 {
760     return _lastInteractionLocation;
761 }
762
763 - (BOOL)shouldHideSelectionWhenScrolling
764 {
765     if (_isEditable)
766         return _assistedNodeInformation.insideFixedPosition;
767
768     auto& editorState = _page->editorState();
769     return !editorState.isMissingPostLayoutData && editorState.postLayoutData().insideFixedPosition;
770 }
771
772 - (BOOL)isEditable
773 {
774     return _isEditable;
775 }
776
777 - (BOOL)setIsEditable:(BOOL)isEditable
778 {
779     if (isEditable == _isEditable)
780         return NO;
781
782     _isEditable = isEditable;
783     return YES;
784 }
785
786 - (BOOL)canBecomeFirstResponder
787 {
788     return _becomingFirstResponder;
789 }
790
791 - (BOOL)canBecomeFirstResponderForWebView
792 {
793     if (_resigningFirstResponder)
794         return NO;
795     // We might want to return something else
796     // if we decide to enable/disable interaction programmatically.
797     return YES;
798 }
799
800 - (BOOL)becomeFirstResponder
801 {
802     return [_webView becomeFirstResponder];
803 }
804
805 - (BOOL)becomeFirstResponderForWebView
806 {
807     if (_resigningFirstResponder)
808         return NO;
809
810     BOOL didBecomeFirstResponder;
811     {
812         SetForScope<BOOL> becomingFirstResponder { _becomingFirstResponder, YES };
813         didBecomeFirstResponder = [super becomeFirstResponder];
814     }
815     if (didBecomeFirstResponder && !self.suppressAssistantSelectionView)
816         [_textSelectionAssistant activateSelection];
817
818     return didBecomeFirstResponder;
819 }
820
821 - (BOOL)resignFirstResponder
822 {
823     return [_webView resignFirstResponder];
824 }
825
826 - (BOOL)resignFirstResponderForWebView
827 {
828     // FIXME: Maybe we should call resignFirstResponder on the superclass
829     // and do nothing if the return value is NO.
830
831     _resigningFirstResponder = YES;
832
833     if (!_webView->_activeFocusedStateRetainCount) {
834         // We need to complete the editing operation before we blur the element.
835         [_inputPeripheral endEditing];
836         _page->blurAssistedNode();
837     }
838
839     [self _cancelInteraction];
840     [_webSelectionAssistant resignedFirstResponder];
841     [_textSelectionAssistant deactivateSelection];
842     
843     _inputViewUpdateDeferrer = nullptr;
844
845     bool superDidResign = [super resignFirstResponder];
846
847     _resigningFirstResponder = NO;
848
849     return superDidResign;
850 }
851
852 - (void)_webTouchEventsRecognized:(UIWebTouchEventsGestureRecognizer *)gestureRecognizer
853 {
854     if (!_page->isValid())
855         return;
856
857     const _UIWebTouchEvent* lastTouchEvent = gestureRecognizer.lastTouchEvent;
858
859     _lastInteractionLocation = lastTouchEvent->locationInDocumentCoordinates;
860     if (lastTouchEvent->type == UIWebTouchEventTouchBegin)
861         _layerTreeTransactionIdAtLastTouchStart = downcast<RemoteLayerTreeDrawingAreaProxy>(*_page->drawingArea()).lastCommittedLayerTreeTransactionID();
862
863 #if ENABLE(TOUCH_EVENTS)
864     NativeWebTouchEvent nativeWebTouchEvent(lastTouchEvent);
865     nativeWebTouchEvent.setCanPreventNativeGestures(!_canSendTouchEventsAsynchronously || [gestureRecognizer isDefaultPrevented]);
866
867     if (_canSendTouchEventsAsynchronously)
868         _page->handleTouchEventAsynchronously(nativeWebTouchEvent);
869     else
870         _page->handleTouchEventSynchronously(nativeWebTouchEvent);
871
872     if (nativeWebTouchEvent.allTouchPointsAreReleased())
873         _canSendTouchEventsAsynchronously = NO;
874 #endif
875 }
876
877 - (void)_inspectorNodeSearchRecognized:(UIGestureRecognizer *)gestureRecognizer
878 {
879     ASSERT(_inspectorNodeSearchEnabled);
880     [self _resetIsDoubleTapPending];
881
882     CGPoint point = [gestureRecognizer locationInView:self];
883
884     switch (gestureRecognizer.state) {
885     case UIGestureRecognizerStateBegan:
886     case UIGestureRecognizerStateChanged:
887         _page->inspectorNodeSearchMovedToPosition(point);
888         break;
889     case UIGestureRecognizerStateEnded:
890     case UIGestureRecognizerStateCancelled:
891     default: // To ensure we turn off node search.
892         _page->inspectorNodeSearchEndedAtPosition(point);
893         break;
894     }
895 }
896
897 static FloatQuad inflateQuad(const FloatQuad& quad, float inflateSize)
898 {
899     // We sort the output points like this (as expected by the highlight view):
900     //  p2------p3
901     //  |       |
902     //  p1------p4
903
904     // 1) Sort the points horizontally.
905     FloatPoint points[4] = { quad.p1(), quad.p4(), quad.p2(), quad.p3() };
906     if (points[0].x() > points[1].x())
907         std::swap(points[0], points[1]);
908     if (points[2].x() > points[3].x())
909         std::swap(points[2], points[3]);
910
911     if (points[0].x() > points[2].x())
912         std::swap(points[0], points[2]);
913     if (points[1].x() > points[3].x())
914         std::swap(points[1], points[3]);
915
916     if (points[1].x() > points[2].x())
917         std::swap(points[1], points[2]);
918
919     // 2) Swap them vertically to have the output points [p2, p1, p3, p4].
920     if (points[1].y() < points[0].y())
921         std::swap(points[0], points[1]);
922     if (points[3].y() < points[2].y())
923         std::swap(points[2], points[3]);
924
925     // 3) Adjust the positions.
926     points[0].move(-inflateSize, -inflateSize);
927     points[1].move(-inflateSize, inflateSize);
928     points[2].move(inflateSize, -inflateSize);
929     points[3].move(inflateSize, inflateSize);
930
931     return FloatQuad(points[1], points[0], points[2], points[3]);
932 }
933
934 #if ENABLE(TOUCH_EVENTS)
935 - (void)_webTouchEvent:(const WebKit::NativeWebTouchEvent&)touchEvent preventsNativeGestures:(BOOL)preventsNativeGesture
936 {
937     if (preventsNativeGesture) {
938         _highlightLongPressCanClick = NO;
939
940         _canSendTouchEventsAsynchronously = YES;
941         [_touchEventGestureRecognizer setDefaultPrevented:YES];
942     }
943 }
944 #endif
945
946 static inline bool highlightedQuadsAreSmallerThanRect(const Vector<FloatQuad>& quads, const FloatRect& rect)
947 {
948     for (size_t i = 0; i < quads.size(); ++i) {
949         FloatRect boundingBox = quads[i].boundingBox();
950         if (boundingBox.width() > rect.width() || boundingBox.height() > rect.height())
951             return false;
952     }
953     return true;
954 }
955
956 static NSValue *nsSizeForTapHighlightBorderRadius(WebCore::IntSize borderRadius, CGFloat borderRadiusScale)
957 {
958     return [NSValue valueWithCGSize:CGSizeMake((borderRadius.width() * borderRadiusScale) + minimumTapHighlightRadius, (borderRadius.height() * borderRadiusScale) + minimumTapHighlightRadius)];
959 }
960
961 - (void)_updateTapHighlight
962 {
963     if (![_highlightView superview])
964         return;
965
966     {
967         RetainPtr<UIColor> highlightUIKitColor = adoptNS([[UIColor alloc] initWithCGColor:cachedCGColor(_tapHighlightInformation.color)]);
968         [_highlightView setColor:highlightUIKitColor.get()];
969     }
970
971     CGFloat selfScale = self.layer.transform.m11;
972     bool allHighlightRectsAreRectilinear = true;
973     float deviceScaleFactor = _page->deviceScaleFactor();
974     const Vector<WebCore::FloatQuad>& highlightedQuads = _tapHighlightInformation.quads;
975     const size_t quadCount = highlightedQuads.size();
976     RetainPtr<NSMutableArray> rects = adoptNS([[NSMutableArray alloc] initWithCapacity:static_cast<const NSUInteger>(quadCount)]);
977     for (size_t i = 0; i < quadCount; ++i) {
978         const FloatQuad& quad = highlightedQuads[i];
979         if (quad.isRectilinear()) {
980             FloatRect boundingBox = quad.boundingBox();
981             boundingBox.scale(selfScale);
982             boundingBox.inflate(minimumTapHighlightRadius);
983             CGRect pixelAlignedRect = static_cast<CGRect>(encloseRectToDevicePixels(boundingBox, deviceScaleFactor));
984             [rects addObject:[NSValue valueWithCGRect:pixelAlignedRect]];
985         } else {
986             allHighlightRectsAreRectilinear = false;
987             rects.clear();
988             break;
989         }
990     }
991
992     if (allHighlightRectsAreRectilinear)
993         [_highlightView setFrames:rects.get() boundaryRect:_page->exposedContentRect()];
994     else {
995         RetainPtr<NSMutableArray> quads = adoptNS([[NSMutableArray alloc] initWithCapacity:static_cast<const NSUInteger>(quadCount)]);
996         for (size_t i = 0; i < quadCount; ++i) {
997             FloatQuad quad = highlightedQuads[i];
998             quad.scale(selfScale);
999             FloatQuad extendedQuad = inflateQuad(quad, minimumTapHighlightRadius);
1000             [quads addObject:[NSValue valueWithCGPoint:extendedQuad.p1()]];
1001             [quads addObject:[NSValue valueWithCGPoint:extendedQuad.p2()]];
1002             [quads addObject:[NSValue valueWithCGPoint:extendedQuad.p3()]];
1003             [quads addObject:[NSValue valueWithCGPoint:extendedQuad.p4()]];
1004         }
1005         [_highlightView setQuads:quads.get() boundaryRect:_page->exposedContentRect()];
1006     }
1007
1008     RetainPtr<NSMutableArray> borderRadii = adoptNS([[NSMutableArray alloc] initWithCapacity:4]);
1009     [borderRadii addObject:nsSizeForTapHighlightBorderRadius(_tapHighlightInformation.topLeftRadius, selfScale)];
1010     [borderRadii addObject:nsSizeForTapHighlightBorderRadius(_tapHighlightInformation.topRightRadius, selfScale)];
1011     [borderRadii addObject:nsSizeForTapHighlightBorderRadius(_tapHighlightInformation.bottomLeftRadius, selfScale)];
1012     [borderRadii addObject:nsSizeForTapHighlightBorderRadius(_tapHighlightInformation.bottomRightRadius, selfScale)];
1013     [_highlightView setCornerRadii:borderRadii.get()];
1014 }
1015
1016 - (void)_showTapHighlight
1017 {
1018     if (!highlightedQuadsAreSmallerThanRect(_tapHighlightInformation.quads, _page->unobscuredContentRect()) && !_showDebugTapHighlightsForFastClicking)
1019         return;
1020
1021     if (!_highlightView) {
1022         _highlightView = adoptNS([[_UIHighlightView alloc] initWithFrame:CGRectZero]);
1023         [_highlightView setUserInteractionEnabled:NO];
1024         [_highlightView setOpaque:NO];
1025         [_highlightView setCornerRadius:minimumTapHighlightRadius];
1026     }
1027     [_highlightView layer].opacity = 1;
1028     [_interactionViewsContainerView addSubview:_highlightView.get()];
1029     [self _updateTapHighlight];
1030 }
1031
1032 - (void)_didGetTapHighlightForRequest:(uint64_t)requestID color:(const WebCore::Color&)color quads:(const Vector<WebCore::FloatQuad>&)highlightedQuads topLeftRadius:(const WebCore::IntSize&)topLeftRadius topRightRadius:(const WebCore::IntSize&)topRightRadius bottomLeftRadius:(const WebCore::IntSize&)bottomLeftRadius bottomRightRadius:(const WebCore::IntSize&)bottomRightRadius
1033 {
1034     if (!_isTapHighlightIDValid || _latestTapID != requestID)
1035         return;
1036
1037     _isTapHighlightIDValid = NO;
1038
1039     _tapHighlightInformation.quads = highlightedQuads;
1040     _tapHighlightInformation.topLeftRadius = topLeftRadius;
1041     _tapHighlightInformation.topRightRadius = topRightRadius;
1042     _tapHighlightInformation.bottomLeftRadius = bottomLeftRadius;
1043     _tapHighlightInformation.bottomRightRadius = bottomRightRadius;
1044     if (_showDebugTapHighlightsForFastClicking)
1045         _tapHighlightInformation.color = [self _tapHighlightColorForFastClick:![_doubleTapGestureRecognizer isEnabled]];
1046     else
1047         _tapHighlightInformation.color = color;
1048
1049     if (_potentialTapInProgress) {
1050         _hasTapHighlightForPotentialTap = YES;
1051         return;
1052     }
1053
1054     [self _showTapHighlight];
1055     if (_isExpectingFastSingleTapCommit) {
1056         [self _finishInteraction];
1057         if (!_potentialTapInProgress)
1058             _isExpectingFastSingleTapCommit = NO;
1059     }
1060 }
1061
1062 - (BOOL)_mayDisableDoubleTapGesturesDuringSingleTap
1063 {
1064     return _potentialTapInProgress;
1065 }
1066
1067 - (void)_disableDoubleTapGesturesDuringTapIfNecessary:(uint64_t)requestID
1068 {
1069     if (_latestTapID != requestID)
1070         return;
1071
1072     [self _setDoubleTapGesturesEnabled:NO];
1073 }
1074
1075 - (void)_cancelLongPressGestureRecognizer
1076 {
1077     [_highlightLongPressGestureRecognizer cancel];
1078 }
1079
1080 - (void)_didScroll
1081 {
1082     [self _cancelLongPressGestureRecognizer];
1083     [self _cancelInteraction];
1084 }
1085
1086 - (void)_overflowScrollingWillBegin
1087 {
1088     [_webSelectionAssistant willStartScrollingOverflow];
1089     [_textSelectionAssistant willStartScrollingOverflow];    
1090 }
1091
1092 - (void)_overflowScrollingDidEnd
1093 {
1094     // If scrolling ends before we've received a selection update,
1095     // we postpone showing the selection until the update is received.
1096     if (!_selectionNeedsUpdate) {
1097         _shouldRestoreSelection = YES;
1098         return;
1099     }
1100     [self _updateChangedSelection];
1101     [_webSelectionAssistant didEndScrollingOverflow];
1102     [_textSelectionAssistant didEndScrollingOverflow];
1103 }
1104
1105 - (BOOL)_requiresKeyboardWhenFirstResponder
1106 {
1107     // FIXME: We should add the logic to handle keyboard visibility during focus redirects.
1108     switch (_assistedNodeInformation.elementType) {
1109     case InputType::None:
1110         return NO;
1111     case InputType::Select:
1112         return !UICurrentUserInterfaceIdiomIsPad();
1113     case InputType::Date:
1114     case InputType::Month:
1115     case InputType::DateTimeLocal:
1116     case InputType::Time:
1117         return !UICurrentUserInterfaceIdiomIsPad();
1118     default:
1119         return !_assistedNodeInformation.isReadOnly;
1120     }
1121     return NO;
1122 }
1123
1124 - (BOOL)_requiresKeyboardResetOnReload
1125 {
1126     return YES;
1127 }
1128
1129 - (void)_displayFormNodeInputView
1130 {
1131     // In case user scaling is force enabled, do not use that scaling when zooming in with an input field.
1132     // Zooming above the page's default scale factor should only happen when the user performs it.
1133     [self _zoomToFocusRect:_assistedNodeInformation.elementRect
1134              selectionRect:_didAccessoryTabInitiateFocus ? IntRect() : _assistedNodeInformation.selectionRect
1135                insideFixed:_assistedNodeInformation.insideFixedPosition
1136                   fontSize:_assistedNodeInformation.nodeFontSize
1137               minimumScale:_assistedNodeInformation.minimumScaleFactor
1138               maximumScale:_assistedNodeInformation.maximumScaleFactorIgnoringAlwaysScalable
1139               allowScaling:(_assistedNodeInformation.allowsUserScalingIgnoringAlwaysScalable && !UICurrentUserInterfaceIdiomIsPad())
1140                forceScroll:[self requiresAccessoryView]];
1141
1142     _didAccessoryTabInitiateFocus = NO;
1143     [self _ensureFormAccessoryView];
1144     [self _updateAccessory];
1145 }
1146
1147 - (UIView *)inputView
1148 {
1149     if (_assistedNodeInformation.elementType == InputType::None)
1150         return nil;
1151
1152     if (!_inputPeripheral)
1153         _inputPeripheral = adoptNS(_assistedNodeInformation.elementType == InputType::Select ? [[WKFormSelectControl alloc] initWithView:self] : [[WKFormInputControl alloc] initWithView:self]);
1154     else
1155         [self _displayFormNodeInputView];
1156
1157     return [_formInputSession customInputView] ?: [_inputPeripheral assistantView];
1158 }
1159
1160 - (CGRect)_selectionClipRect
1161 {
1162     if (_assistedNodeInformation.elementType == InputType::None)
1163         return CGRectNull;
1164     return _page->editorState().postLayoutData().selectionClipRect;
1165 }
1166
1167 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)preventingGestureRecognizer canPreventGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer
1168 {
1169     // A long-press gesture can not be recognized while panning, but a pan can be recognized
1170     // during a long-press gesture.
1171     BOOL shouldNotPreventScrollViewGestures = preventingGestureRecognizer == _highlightLongPressGestureRecognizer || preventingGestureRecognizer == _longPressGestureRecognizer;
1172     return !(shouldNotPreventScrollViewGestures
1173         && ([preventedGestureRecognizer isKindOfClass:NSClassFromString(@"UIScrollViewPanGestureRecognizer")] || [preventedGestureRecognizer isKindOfClass:NSClassFromString(@"UIScrollViewPinchGestureRecognizer")]));
1174 }
1175
1176 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer canBePreventedByGestureRecognizer:(UIGestureRecognizer *)preventingGestureRecognizer {
1177     // Don't allow the highlight to be prevented by a selection gesture. Press-and-hold on a link should highlight the link, not select it.
1178     if ((preventingGestureRecognizer == _textSelectionAssistant.get().loupeGesture || [_webSelectionAssistant isSelectionGestureRecognizer:preventingGestureRecognizer])
1179         && (preventedGestureRecognizer == _highlightLongPressGestureRecognizer || preventedGestureRecognizer == _longPressGestureRecognizer)) {
1180         return NO;
1181     }
1182
1183     return YES;
1184 }
1185
1186 static inline bool isSamePair(UIGestureRecognizer *a, UIGestureRecognizer *b, UIGestureRecognizer *x, UIGestureRecognizer *y)
1187 {
1188     return (a == x && b == y) || (b == x && a == y);
1189 }
1190
1191 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
1192 {
1193     if (isSamePair(gestureRecognizer, otherGestureRecognizer, _highlightLongPressGestureRecognizer.get(), _longPressGestureRecognizer.get()))
1194         return YES;
1195
1196     if (isSamePair(gestureRecognizer, otherGestureRecognizer, _highlightLongPressGestureRecognizer.get(), _webSelectionAssistant.get().selectionLongPressRecognizer))
1197         return YES;
1198
1199     if (isSamePair(gestureRecognizer, otherGestureRecognizer, _singleTapGestureRecognizer.get(), _textSelectionAssistant.get().singleTapGesture))
1200         return YES;
1201
1202     if (isSamePair(gestureRecognizer, otherGestureRecognizer, _singleTapGestureRecognizer.get(), _nonBlockingDoubleTapGestureRecognizer.get()))
1203         return YES;
1204
1205     if (isSamePair(gestureRecognizer, otherGestureRecognizer, _highlightLongPressGestureRecognizer.get(), _nonBlockingDoubleTapGestureRecognizer.get()))
1206         return YES;
1207
1208     if (isSamePair(gestureRecognizer, otherGestureRecognizer, _highlightLongPressGestureRecognizer.get(), _previewSecondaryGestureRecognizer.get()))
1209         return YES;
1210
1211     if (isSamePair(gestureRecognizer, otherGestureRecognizer, _highlightLongPressGestureRecognizer.get(), _previewGestureRecognizer.get()))
1212         return YES;
1213
1214     return NO;
1215 }
1216
1217 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
1218 {
1219     if (gestureRecognizer == _touchEventGestureRecognizer && [_webView _isNavigationSwipeGestureRecognizer:otherGestureRecognizer])
1220         return YES;
1221
1222     return NO;
1223 }
1224
1225 - (void)_showImageSheet
1226 {
1227     [_actionSheetAssistant showImageSheet];
1228 }
1229
1230 - (void)_showAttachmentSheet
1231 {
1232     id <WKUIDelegatePrivate> uiDelegate = static_cast<id <WKUIDelegatePrivate>>([_webView UIDelegate]);
1233     if (![uiDelegate respondsToSelector:@selector(_webView:showCustomSheetForElement:)])
1234         return;
1235
1236     auto element = adoptNS([[_WKActivatedElementInfo alloc] _initWithType:_WKActivatedElementTypeAttachment URL:(NSURL *)_positionInformation.url location:_positionInformation.request.point title:_positionInformation.title ID:_positionInformation.idAttribute rect:_positionInformation.bounds image:nil]);
1237     [uiDelegate _webView:_webView showCustomSheetForElement:element.get()];
1238 }
1239
1240 - (void)_showLinkSheet
1241 {
1242     [_actionSheetAssistant showLinkSheet];
1243 }
1244
1245 - (void)_showDataDetectorsSheet
1246 {
1247     [_actionSheetAssistant showDataDetectorsSheet];
1248 }
1249
1250 - (SEL)_actionForLongPressFromPositionInformation:(const InteractionInformationAtPosition&)positionInformation
1251 {
1252     if (!positionInformation.touchCalloutEnabled)
1253         return nil;
1254
1255     if (positionInformation.isImage)
1256         return @selector(_showImageSheet);
1257
1258     if (positionInformation.isLink) {
1259 #if ENABLE(DATA_DETECTION)
1260         NSURL *targetURL = [NSURL URLWithString:positionInformation.url];
1261         if ([[getDDDetectionControllerClass() tapAndHoldSchemes] containsObject:targetURL.scheme.lowercaseString])
1262             return @selector(_showDataDetectorsSheet);
1263 #endif
1264         return @selector(_showLinkSheet);
1265     }
1266     if (positionInformation.isAttachment)
1267         return @selector(_showAttachmentSheet);
1268
1269     return nil;
1270 }
1271
1272 - (SEL)_actionForLongPress
1273 {
1274     return [self _actionForLongPressFromPositionInformation:_positionInformation];
1275 }
1276
1277 - (InteractionInformationAtPosition)currentPositionInformation
1278 {
1279     return _positionInformation;
1280 }
1281
1282 - (void)doAfterPositionInformationUpdate:(void (^)(InteractionInformationAtPosition))action forRequest:(InteractionInformationRequest)request
1283 {
1284     if ([self _currentPositionInformationIsValidForRequest:request]) {
1285         // If the most recent position information is already valid, invoke the given action block immediately.
1286         action(_positionInformation);
1287         return;
1288     }
1289
1290     _pendingPositionInformationHandlers.append(InteractionInformationRequestAndCallback(request, action));
1291
1292     if (![self _hasValidOutstandingPositionInformationRequest:request])
1293         [self requestAsynchronousPositionInformationUpdate:request];
1294 }
1295
1296 - (BOOL)ensurePositionInformationIsUpToDate:(WebKit::InteractionInformationRequest)request
1297 {
1298     if ([self _currentPositionInformationIsValidForRequest:request])
1299         return YES;
1300
1301     auto* connection = _page->process().connection();
1302     if (!connection)
1303         return NO;
1304
1305     if ([self _hasValidOutstandingPositionInformationRequest:request]) {
1306         return connection->waitForAndDispatchImmediately<Messages::WebPageProxy::DidReceivePositionInformation>(_page->pageID(), Seconds::infinity(), IPC::WaitForOption::InterruptWaitingIfSyncMessageArrives);
1307     }
1308
1309     _page->process().sendSync(Messages::WebPage::GetPositionInformation(request), Messages::WebPage::GetPositionInformation::Reply(_positionInformation), _page->pageID());
1310
1311     _hasValidPositionInformation = YES;
1312     [self _invokeAndRemovePendingHandlersValidForCurrentPositionInformation];
1313
1314     return YES;
1315 }
1316
1317 - (void)requestAsynchronousPositionInformationUpdate:(WebKit::InteractionInformationRequest)request
1318 {
1319     if ([self _currentPositionInformationIsValidForRequest:request])
1320         return;
1321
1322     _outstandingPositionInformationRequest = request;
1323
1324     _page->requestPositionInformation(request);
1325 }
1326
1327 - (BOOL)_currentPositionInformationIsValidForRequest:(const InteractionInformationRequest&)request
1328 {
1329     return _hasValidPositionInformation && _positionInformation.request.isValidForRequest(request);
1330 }
1331
1332 - (BOOL)_hasValidOutstandingPositionInformationRequest:(const InteractionInformationRequest&)request
1333 {
1334     return _outstandingPositionInformationRequest && _outstandingPositionInformationRequest->isValidForRequest(request);
1335 }
1336
1337 - (void)_invokeAndRemovePendingHandlersValidForCurrentPositionInformation
1338 {
1339     ASSERT(_hasValidPositionInformation);
1340
1341     ++_positionInformationCallbackDepth;
1342     auto updatedPositionInformation = _positionInformation;
1343
1344     for (size_t index = 0; index < _pendingPositionInformationHandlers.size(); ++index) {
1345         auto requestAndHandler = _pendingPositionInformationHandlers[index];
1346         if (!requestAndHandler)
1347             continue;
1348
1349         if (![self _currentPositionInformationIsValidForRequest:requestAndHandler->first])
1350             continue;
1351
1352         _pendingPositionInformationHandlers[index] = std::nullopt;
1353
1354         if (requestAndHandler->second)
1355             requestAndHandler->second(updatedPositionInformation);
1356     }
1357
1358     if (--_positionInformationCallbackDepth)
1359         return;
1360
1361     for (int index = _pendingPositionInformationHandlers.size() - 1; index >= 0; --index) {
1362         if (!_pendingPositionInformationHandlers[index])
1363             _pendingPositionInformationHandlers.remove(index);
1364     }
1365 }
1366
1367 #if ENABLE(DATA_DETECTION)
1368 - (NSArray *)_dataDetectionResults
1369 {
1370     return _page->dataDetectionResults();
1371 }
1372 #endif
1373
1374 - (NSArray<NSValue *> *)_uiTextSelectionRects
1375 {
1376     NSMutableArray *textSelectionRects = [NSMutableArray array];
1377
1378     if (_textSelectionAssistant) {
1379         for (WKTextSelectionRect *selectionRect in [_textSelectionAssistant valueForKeyPath:@"selectionView.selection.selectionRects"])
1380             [textSelectionRects addObject:[NSValue valueWithCGRect:selectionRect.webRect.rect]];
1381     } else if (_webSelectionAssistant) {
1382         for (WebSelectionRect *selectionRect in [_webSelectionAssistant valueForKeyPath:@"selectionView.selectionRects"])
1383             [textSelectionRects addObject:[NSValue valueWithCGRect:selectionRect.rect]];
1384     }
1385
1386     return textSelectionRects;
1387 }
1388
1389 - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
1390 {
1391     CGPoint point = [gestureRecognizer locationInView:self];
1392
1393     if (gestureRecognizer == _highlightLongPressGestureRecognizer
1394         || gestureRecognizer == _doubleTapGestureRecognizer
1395         || gestureRecognizer == _nonBlockingDoubleTapGestureRecognizer
1396         || gestureRecognizer == _twoFingerDoubleTapGestureRecognizer
1397         || gestureRecognizer == _singleTapGestureRecognizer) {
1398
1399         if (_textSelectionAssistant) {
1400             // Request information about the position with sync message.
1401             // If the assisted node is the same, prevent the gesture.
1402             if (![self ensurePositionInformationIsUpToDate:InteractionInformationRequest(roundedIntPoint(point))])
1403                 return NO;
1404             if (_positionInformation.nodeAtPositionIsAssistedNode)
1405                 return NO;
1406         }
1407     }
1408
1409     if (gestureRecognizer == _highlightLongPressGestureRecognizer) {
1410         if (_textSelectionAssistant) {
1411             // This is a different node than the assisted one.
1412             // Prevent the gesture if there is no node.
1413             // Allow the gesture if it is a node that wants highlight or if there is an action for it.
1414             if (!_positionInformation.isElement)
1415                 return NO;
1416             return [self _actionForLongPress] != nil;
1417         } else {
1418             // We still have no idea about what is at the location.
1419             // Send and async message to find out.
1420             _hasValidPositionInformation = NO;
1421             InteractionInformationRequest request(roundedIntPoint(point));
1422
1423             // If 3D Touch is enabled, asynchronously collect snapshots in the hopes that
1424             // they'll arrive before we have to synchronously request them in
1425             // _interactionShouldBeginFromPreviewItemController.
1426             if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
1427                 request.includeSnapshot = true;
1428                 request.includeLinkIndicator = true;
1429             }
1430
1431             [self requestAsynchronousPositionInformationUpdate:request];
1432             return YES;
1433         }
1434     }
1435
1436     if (gestureRecognizer == _longPressGestureRecognizer) {
1437         // Use the information retrieved with one of the previous calls
1438         // to gestureRecognizerShouldBegin.
1439         // Force a sync call if not ready yet.
1440         InteractionInformationRequest request(roundedIntPoint(point));
1441         if (![self ensurePositionInformationIsUpToDate:request])
1442             return NO;
1443
1444         if (_textSelectionAssistant) {
1445             // Prevent the gesture if it is the same node.
1446             if (_positionInformation.nodeAtPositionIsAssistedNode)
1447                 return NO;
1448         } else {
1449             // Prevent the gesture if there is no action for the node.
1450             return [self _actionForLongPress] != nil;
1451         }
1452     }
1453
1454     return YES;
1455 }
1456
1457 - (void)_cancelInteraction
1458 {
1459     _isTapHighlightIDValid = NO;
1460     [_highlightView removeFromSuperview];
1461 }
1462
1463 - (void)_finishInteraction
1464 {
1465     _isTapHighlightIDValid = NO;
1466     CGFloat tapHighlightFadeDuration = _showDebugTapHighlightsForFastClicking ? 0.25 : 0.1;
1467     [UIView animateWithDuration:tapHighlightFadeDuration
1468                      animations:^{
1469                          [_highlightView layer].opacity = 0;
1470                      }
1471                      completion:^(BOOL finished){
1472                          if (finished)
1473                              [_highlightView removeFromSuperview];
1474                      }];
1475 }
1476
1477 - (BOOL)hasSelectablePositionAtPoint:(CGPoint)point
1478 {
1479     if (_inspectorNodeSearchEnabled)
1480         return NO;
1481
1482     InteractionInformationRequest request(roundedIntPoint(point));
1483     if (![self ensurePositionInformationIsUpToDate:request])
1484         return NO;
1485
1486 #if ENABLE(DATA_INTERACTION)
1487     if (_positionInformation.hasSelectionAtPosition) {
1488         // If the position might initiate a data interaction, we don't want to consider the content at this position to be selectable.
1489         // FIXME: This should be renamed to something more precise, such as textSelectionShouldRecognizeGestureAtPoint:
1490         return NO;
1491     }
1492 #endif
1493
1494     return _positionInformation.isSelectable;
1495 }
1496
1497 - (BOOL)pointIsNearMarkedText:(CGPoint)point
1498 {
1499     InteractionInformationRequest request(roundedIntPoint(point));
1500     if (![self ensurePositionInformationIsUpToDate:request])
1501         return NO;
1502     return _positionInformation.isNearMarkedText;
1503 }
1504
1505 - (BOOL)pointIsInAssistedNode:(CGPoint)point
1506 {
1507     // This method is still implemented for backwards compatibility with older UIKit versions.
1508     return [self textInteractionGesture:UIWKGestureLoupe shouldBeginAtPoint:point];
1509 }
1510
1511 - (BOOL)textInteractionGesture:(UIWKGestureType)gesture shouldBeginAtPoint:(CGPoint)point
1512 {
1513     InteractionInformationRequest request(roundedIntPoint(point));
1514     if (![self ensurePositionInformationIsUpToDate:request])
1515         return NO;
1516
1517 #if ENABLE(DATA_INTERACTION)
1518     if (_positionInformation.hasSelectionAtPosition && gesture == UIWKGestureLoupe) {
1519         // If the position might initiate data interaction, we don't want to change the selection.
1520         return NO;
1521     }
1522 #endif
1523
1524     // If we're currently editing an assisted node, only allow the selection to move within that assisted node.
1525     if (self.isAssistingNode)
1526         return _positionInformation.nodeAtPositionIsAssistedNode;
1527
1528     // Otherwise, if we're using a text interaction assistant outside of editing purposes (e.g. the selection mode
1529     // is character granularity) then allow text selection.
1530     return YES;
1531 }
1532
1533 - (NSArray *)webSelectionRectsForSelectionRects:(const Vector<WebCore::SelectionRect>&)selectionRects
1534 {
1535     unsigned size = selectionRects.size();
1536     if (!size)
1537         return nil;
1538
1539     NSMutableArray *webRects = [NSMutableArray arrayWithCapacity:size];
1540     for (unsigned i = 0; i < size; i++) {
1541         const WebCore::SelectionRect& coreRect = selectionRects[i];
1542         WebSelectionRect *webRect = [WebSelectionRect selectionRect];
1543         webRect.rect = coreRect.rect();
1544         webRect.writingDirection = coreRect.direction() == LTR ? WKWritingDirectionLeftToRight : WKWritingDirectionRightToLeft;
1545         webRect.isLineBreak = coreRect.isLineBreak();
1546         webRect.isFirstOnLine = coreRect.isFirstOnLine();
1547         webRect.isLastOnLine = coreRect.isLastOnLine();
1548         webRect.containsStart = coreRect.containsStart();
1549         webRect.containsEnd = coreRect.containsEnd();
1550         webRect.isInFixedPosition = coreRect.isInFixedPosition();
1551         webRect.isHorizontal = coreRect.isHorizontal();
1552         [webRects addObject:webRect];
1553     }
1554
1555     return webRects;
1556 }
1557
1558 - (NSArray *)webSelectionRects
1559 {
1560     if (_page->editorState().selectionIsNone)
1561         return nil;
1562     const auto& selectionRects = _page->editorState().postLayoutData().selectionRects;
1563     return [self webSelectionRectsForSelectionRects:selectionRects];
1564 }
1565
1566 - (void)_highlightLongPressRecognized:(UILongPressGestureRecognizer *)gestureRecognizer
1567 {
1568     ASSERT(gestureRecognizer == _highlightLongPressGestureRecognizer);
1569     [self _resetIsDoubleTapPending];
1570
1571     _lastInteractionLocation = gestureRecognizer.startPoint;
1572
1573     switch ([gestureRecognizer state]) {
1574     case UIGestureRecognizerStateBegan:
1575         _highlightLongPressCanClick = YES;
1576         cancelPotentialTapIfNecessary(self);
1577         _page->tapHighlightAtPosition([gestureRecognizer startPoint], ++_latestTapID);
1578         _isTapHighlightIDValid = YES;
1579         break;
1580     case UIGestureRecognizerStateEnded:
1581         if (_highlightLongPressCanClick && _positionInformation.isElement) {
1582             [self _attemptClickAtLocation:[gestureRecognizer startPoint]];
1583             [self _finishInteraction];
1584         } else
1585             [self _cancelInteraction];
1586         _highlightLongPressCanClick = NO;
1587         break;
1588     case UIGestureRecognizerStateCancelled:
1589         [self _cancelInteraction];
1590         _highlightLongPressCanClick = NO;
1591         break;
1592     default:
1593         break;
1594     }
1595 }
1596
1597 - (void)_twoFingerSingleTapGestureRecognized:(UITapGestureRecognizer *)gestureRecognizer
1598 {
1599     _isTapHighlightIDValid = YES;
1600     _isExpectingFastSingleTapCommit = YES;
1601     _page->handleTwoFingerTapAtPoint(roundedIntPoint(gestureRecognizer.centroid), ++_latestTapID);
1602 }
1603
1604 - (void)_longPressRecognized:(UILongPressGestureRecognizer *)gestureRecognizer
1605 {
1606     ASSERT(gestureRecognizer == _longPressGestureRecognizer);
1607     [self _resetIsDoubleTapPending];
1608
1609     _lastInteractionLocation = gestureRecognizer.startPoint;
1610
1611     if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
1612         SEL action = [self _actionForLongPress];
1613         if (action) {
1614             [self performSelector:action];
1615             [self _cancelLongPressGestureRecognizer];
1616         }
1617     }
1618 }
1619
1620 - (void)_endPotentialTapAndEnableDoubleTapGesturesIfNecessary
1621 {
1622     if (_webView._allowsDoubleTapGestures)
1623         [self _setDoubleTapGesturesEnabled:YES];
1624
1625     _potentialTapInProgress = NO;
1626 }
1627
1628 - (void)_singleTapRecognized:(UITapGestureRecognizer *)gestureRecognizer
1629 {
1630     ASSERT(gestureRecognizer == _singleTapGestureRecognizer);
1631     ASSERT(!_potentialTapInProgress);
1632     [self _resetIsDoubleTapPending];
1633
1634     _page->potentialTapAtPosition(gestureRecognizer.location, ++_latestTapID);
1635     _potentialTapInProgress = YES;
1636     _isTapHighlightIDValid = YES;
1637     _isExpectingFastSingleTapCommit = !_doubleTapGestureRecognizer.get().enabled;
1638 }
1639
1640 static void cancelPotentialTapIfNecessary(WKContentView* contentView)
1641 {
1642     if (contentView->_potentialTapInProgress) {
1643         [contentView _endPotentialTapAndEnableDoubleTapGesturesIfNecessary];
1644         [contentView _cancelInteraction];
1645         contentView->_page->cancelPotentialTap();
1646     }
1647 }
1648
1649 - (void)_singleTapDidReset:(UITapGestureRecognizer *)gestureRecognizer
1650 {
1651     ASSERT(gestureRecognizer == _singleTapGestureRecognizer);
1652     cancelPotentialTapIfNecessary(self);
1653 }
1654
1655 - (void)_commitPotentialTapFailed
1656 {
1657     [self _cancelInteraction];
1658     
1659     _inputViewUpdateDeferrer = nullptr;
1660 }
1661
1662 - (void)_didNotHandleTapAsClick:(const WebCore::IntPoint&)point
1663 {
1664     _inputViewUpdateDeferrer = nullptr;
1665
1666     // FIXME: we should also take into account whether or not the UI delegate
1667     // has handled this notification.
1668 #if ENABLE(DATA_DETECTION)
1669     if (_hasValidPositionInformation && point == _positionInformation.request.point && _positionInformation.isDataDetectorLink) {
1670         [self _showDataDetectorsSheet];
1671         return;
1672     }
1673 #endif
1674
1675     if (!_isDoubleTapPending)
1676         return;
1677
1678     _smartMagnificationController->handleSmartMagnificationGesture(_lastInteractionLocation);
1679     _isDoubleTapPending = NO;
1680 }
1681
1682 - (void)_didCompleteSyntheticClick
1683 {
1684     _inputViewUpdateDeferrer = nullptr;
1685 }
1686
1687 - (void)_singleTapCommited:(UITapGestureRecognizer *)gestureRecognizer
1688 {
1689     ASSERT(gestureRecognizer == _singleTapGestureRecognizer);
1690
1691     if (![self isFirstResponder]) {
1692         if (!_inputViewUpdateDeferrer)
1693             _inputViewUpdateDeferrer = std::make_unique<InputViewUpdateDeferrer>();
1694         [self becomeFirstResponder];
1695     }
1696
1697     if (_webSelectionAssistant && ![_webSelectionAssistant shouldHandleSingleTapAtPoint:gestureRecognizer.location]) {
1698         [self _singleTapDidReset:gestureRecognizer];
1699         return;
1700     }
1701
1702     ASSERT(_potentialTapInProgress);
1703
1704     // We don't want to clear the selection if it is in editable content.
1705     // The selection could have been set by autofocusing on page load and not
1706     // reflected in the UI process since the user was not interacting with the page.
1707     if (!_page->editorState().isContentEditable)
1708         [_webSelectionAssistant clearSelection];
1709
1710     _lastInteractionLocation = gestureRecognizer.location;
1711
1712     [self _endPotentialTapAndEnableDoubleTapGesturesIfNecessary];
1713
1714     if (_hasTapHighlightForPotentialTap) {
1715         [self _showTapHighlight];
1716         _hasTapHighlightForPotentialTap = NO;
1717     }
1718
1719     [_inputPeripheral endEditing];
1720     _page->commitPotentialTap(_layerTreeTransactionIdAtLastTouchStart);
1721
1722     if (!_isExpectingFastSingleTapCommit)
1723         [self _finishInteraction];
1724 }
1725
1726 - (void)_doubleTapRecognized:(UITapGestureRecognizer *)gestureRecognizer
1727 {
1728     [self _resetIsDoubleTapPending];
1729     _lastInteractionLocation = gestureRecognizer.location;
1730
1731     _smartMagnificationController->handleSmartMagnificationGesture(gestureRecognizer.location);
1732 }
1733
1734 - (void)_resetIsDoubleTapPending
1735 {
1736     _isDoubleTapPending = NO;
1737 }
1738
1739 - (void)_nonBlockingDoubleTapRecognized:(UITapGestureRecognizer *)gestureRecognizer
1740 {
1741     _lastInteractionLocation = gestureRecognizer.location;
1742     _isDoubleTapPending = YES;
1743 }
1744
1745 - (void)_twoFingerDoubleTapRecognized:(UITapGestureRecognizer *)gestureRecognizer
1746 {
1747     [self _resetIsDoubleTapPending];
1748     _lastInteractionLocation = gestureRecognizer.location;
1749
1750     _smartMagnificationController->handleResetMagnificationGesture(gestureRecognizer.location);
1751 }
1752
1753 - (void)_attemptClickAtLocation:(CGPoint)location
1754 {
1755     if (![self isFirstResponder]) {
1756         if (!_inputViewUpdateDeferrer)
1757             _inputViewUpdateDeferrer = std::make_unique<InputViewUpdateDeferrer>();
1758         [self becomeFirstResponder];
1759     }
1760
1761     [_inputPeripheral endEditing];
1762     _page->handleTap(location, _layerTreeTransactionIdAtLastTouchStart);
1763 }
1764
1765 - (void)useSelectionAssistantWithGranularity:(WKSelectionGranularity)selectionGranularity
1766 {
1767     if (selectionGranularity == WKSelectionGranularityDynamic) {
1768         if (_textSelectionAssistant) {
1769             [_textSelectionAssistant deactivateSelection];
1770             _textSelectionAssistant = nil;
1771         }
1772         if (!_webSelectionAssistant)
1773             _webSelectionAssistant = adoptNS([[UIWKSelectionAssistant alloc] initWithView:self]);
1774     } else if (selectionGranularity == WKSelectionGranularityCharacter) {
1775         if (_webSelectionAssistant)
1776             _webSelectionAssistant = nil;
1777
1778         if (!_textSelectionAssistant)
1779             _textSelectionAssistant = adoptNS([[UIWKTextInteractionAssistant alloc] initWithView:self]);
1780         else {
1781             // Reset the gesture recognizers in case editibility has changed.
1782             [_textSelectionAssistant setGestureRecognizers];
1783         }
1784
1785         if (self.isFirstResponder && !self.suppressAssistantSelectionView)
1786             [_textSelectionAssistant activateSelection];
1787     }
1788 }
1789
1790 - (void)clearSelection
1791 {
1792     _page->clearSelection();
1793 }
1794
1795 - (void)_positionInformationDidChange:(const InteractionInformationAtPosition&)info
1796 {
1797     _outstandingPositionInformationRequest = std::nullopt;
1798
1799     InteractionInformationAtPosition newInfo = info;
1800     newInfo.mergeCompatibleOptionalInformation(_positionInformation);
1801
1802     _positionInformation = newInfo;
1803     _hasValidPositionInformation = YES;
1804     if (_actionSheetAssistant)
1805         [_actionSheetAssistant updateSheetPosition];
1806     [self _invokeAndRemovePendingHandlersValidForCurrentPositionInformation];
1807 }
1808
1809 - (void)_willStartScrollingOrZooming
1810 {
1811     [_webSelectionAssistant willStartScrollingOrZoomingPage];
1812     [_textSelectionAssistant willStartScrollingOverflow];
1813     _page->setIsScrollingOrZooming(true);
1814 }
1815
1816 - (void)scrollViewWillStartPanOrPinchGesture
1817 {
1818     _page->hideValidationMessage();
1819
1820     _canSendTouchEventsAsynchronously = YES;
1821 }
1822
1823 - (void)_didEndScrollingOrZooming
1824 {
1825     if (!_needsDeferredEndScrollingSelectionUpdate) {
1826         [_webSelectionAssistant didEndScrollingOrZoomingPage];
1827         [_textSelectionAssistant didEndScrollingOverflow];
1828     }
1829     _page->setIsScrollingOrZooming(false);
1830 }
1831
1832 - (BOOL)requiresAccessoryView
1833 {
1834     if ([_formInputSession accessoryViewShouldNotShow])
1835         return NO;
1836
1837     switch (_assistedNodeInformation.elementType) {
1838     case InputType::None:
1839         return NO;
1840     case InputType::Text:
1841     case InputType::Password:
1842     case InputType::Search:
1843     case InputType::Email:
1844     case InputType::URL:
1845     case InputType::Phone:
1846     case InputType::Number:
1847     case InputType::NumberPad:
1848     case InputType::ContentEditable:
1849     case InputType::TextArea:
1850     case InputType::Select:
1851     case InputType::Date:
1852     case InputType::DateTime:
1853     case InputType::DateTimeLocal:
1854     case InputType::Month:
1855     case InputType::Week:
1856     case InputType::Time:
1857         return !UICurrentUserInterfaceIdiomIsPad();
1858     }
1859 }
1860
1861 - (void)_ensureFormAccessoryView
1862 {
1863     if (_formAccessoryView)
1864         return;
1865
1866     _formAccessoryView = adoptNS([[UIWebFormAccessory alloc] initWithInputAssistantItem:self.inputAssistantItem]);
1867     [_formAccessoryView setDelegate:self];
1868 }
1869
1870 - (UIView *)inputAccessoryView
1871 {
1872     if (![self requiresAccessoryView])
1873         return nil;
1874
1875     return self.formAccessoryView;
1876 }
1877
1878 - (NSArray *)supportedPasteboardTypesForCurrentSelection
1879 {
1880     if (_page->editorState().selectionIsNone)
1881         return nil;
1882     
1883     static NSMutableArray *richTypes = nil;
1884     static NSMutableArray *plainTextTypes = nil;
1885     if (!plainTextTypes) {
1886         plainTextTypes = [[NSMutableArray alloc] init];
1887         [plainTextTypes addObject:(id)kUTTypeURL];
1888         [plainTextTypes addObjectsFromArray:UIPasteboardTypeListString];
1889
1890         richTypes = [[NSMutableArray alloc] init];
1891         [richTypes addObject:WebArchivePboardType];
1892         [richTypes addObjectsFromArray:UIPasteboardTypeListImage];
1893         [richTypes addObjectsFromArray:plainTextTypes];
1894     }
1895
1896     return (_page->editorState().isContentRichlyEditable) ? richTypes : plainTextTypes;
1897 }
1898
1899 #define FORWARD_ACTION_TO_WKWEBVIEW(_action) \
1900     - (void)_action:(id)sender \
1901     { \
1902         [_webView _action:sender]; \
1903     }
1904
1905 FOR_EACH_WKCONTENTVIEW_ACTION(FORWARD_ACTION_TO_WKWEBVIEW)
1906
1907 #undef FORWARD_ACTION_TO_WKWEBVIEW
1908
1909 - (void)_lookupForWebView:(id)sender
1910 {
1911     RetainPtr<WKContentView> view = self;
1912     _page->getSelectionContext([view](const String& selectedText, const String& textBefore, const String& textAfter, CallbackBase::Error error) {
1913         if (error != CallbackBase::Error::None)
1914             return;
1915         if (!selectedText)
1916             return;
1917         
1918         CGRect presentationRect = view->_page->editorState().selectionIsRange ? view->_page->editorState().postLayoutData().selectionRects[0].rect() : view->_page->editorState().postLayoutData().caretRectAtStart;
1919         
1920         String selectionContext = textBefore + selectedText + textAfter;
1921         if (view->_textSelectionAssistant) {
1922             [view->_textSelectionAssistant lookup:selectionContext withRange:NSMakeRange(textBefore.length(), selectedText.length()) fromRect:presentationRect];
1923         } else {
1924             [view->_webSelectionAssistant lookup:selectionContext withRange:NSMakeRange(textBefore.length(), selectedText.length()) fromRect:presentationRect];
1925         }
1926     });
1927 }
1928
1929 - (void)_shareForWebView:(id)sender
1930 {
1931     RetainPtr<WKContentView> view = self;
1932     _page->getSelectionOrContentsAsString([view](const String& string, CallbackBase::Error error) {
1933         if (error != CallbackBase::Error::None)
1934             return;
1935         if (!string)
1936             return;
1937
1938         CGRect presentationRect = view->_page->editorState().postLayoutData().selectionRects[0].rect();
1939
1940         if (view->_textSelectionAssistant)
1941             [view->_textSelectionAssistant showShareSheetFor:string fromRect:presentationRect];
1942         else if (view->_webSelectionAssistant)
1943             [view->_webSelectionAssistant showShareSheetFor:string fromRect:presentationRect];
1944     });
1945 }
1946
1947 - (void)_addShortcutForWebView:(id)sender
1948 {
1949     if (_textSelectionAssistant)
1950         [_textSelectionAssistant showTextServiceFor:[self selectedText] fromRect:_page->editorState().postLayoutData().selectionRects[0].rect()];
1951     else if (_webSelectionAssistant)
1952         [_webSelectionAssistant showTextServiceFor:[self selectedText] fromRect:_page->editorState().postLayoutData().selectionRects[0].rect()];
1953 }
1954
1955 - (NSString *)selectedText
1956 {
1957     return (NSString *)_page->editorState().postLayoutData().wordAtSelection;
1958 }
1959
1960 - (BOOL)isReplaceAllowed
1961 {
1962     return _page->editorState().postLayoutData().isReplaceAllowed;
1963 }
1964
1965 - (void)replaceText:(NSString *)text withText:(NSString *)word
1966 {
1967     _page->replaceSelectedText(text, word);
1968 }
1969
1970 - (void)selectWordBackward
1971 {
1972     _page->selectWordBackward();
1973 }
1974
1975 - (void)_promptForReplaceForWebView:(id)sender
1976 {
1977     const auto& wordAtSelection = _page->editorState().postLayoutData().wordAtSelection;
1978     if (wordAtSelection.isEmpty())
1979         return;
1980
1981     [_textSelectionAssistant scheduleReplacementsForText:wordAtSelection];
1982 }
1983
1984 - (void)_transliterateChineseForWebView:(id)sender
1985 {
1986     [_textSelectionAssistant scheduleChineseTransliterationForText:_page->editorState().postLayoutData().wordAtSelection];
1987 }
1988
1989 - (void)_reanalyzeForWebView:(id)sender
1990 {
1991     [_textSelectionAssistant scheduleReanalysis];
1992 }
1993
1994 - (void)replaceForWebView:(id)sender
1995 {
1996     [[UIKeyboardImpl sharedInstance] replaceText:sender];
1997 }
1998
1999 - (NSDictionary *)textStylingAtPosition:(UITextPosition *)position inDirection:(UITextStorageDirection)direction
2000 {
2001     if (!position || !_page->editorState().isContentRichlyEditable)
2002         return nil;
2003
2004     NSMutableDictionary* result = [NSMutableDictionary dictionary];
2005
2006     auto typingAttributes = _page->editorState().postLayoutData().typingAttributes;
2007     CTFontSymbolicTraits symbolicTraits = 0;
2008     if (typingAttributes & AttributeBold)
2009         symbolicTraits |= kCTFontBoldTrait;
2010     if (typingAttributes & AttributeItalics)
2011         symbolicTraits |= kCTFontTraitItalic;
2012
2013     // We chose a random font family and size.
2014     // What matters are the traits but the caller expects a font object
2015     // in the dictionary for NSFontAttributeName.
2016     RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateWithNameAndSize(CFSTR("Helvetica"), 10));
2017     if (symbolicTraits)
2018         fontDescriptor = adoptCF(CTFontDescriptorCreateCopyWithSymbolicTraits(fontDescriptor.get(), symbolicTraits, symbolicTraits));
2019     
2020     RetainPtr<CTFontRef> font = adoptCF(CTFontCreateWithFontDescriptor(fontDescriptor.get(), 10, nullptr));
2021     if (font)
2022         [result setObject:(id)font.get() forKey:NSFontAttributeName];
2023     
2024     if (typingAttributes & AttributeUnderline)
2025         [result setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
2026
2027     return result;
2028 }
2029
2030 - (UIColor *)insertionPointColor
2031 {
2032     return [UIColor insertionPointColor];
2033 }
2034
2035 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
2036 {
2037     return [_webView canPerformAction:action withSender:sender];
2038 }
2039
2040 - (BOOL)canPerformActionForWebView:(SEL)action withSender:(id)sender
2041 {
2042     BOOL hasWebSelection = _webSelectionAssistant && !CGRectIsEmpty(_webSelectionAssistant.get().selectionFrame);
2043
2044     if (action == @selector(_arrowKey:))
2045         return [self isFirstResponder];
2046         
2047     if (action == @selector(_showTextStyleOptions:))
2048         return _page->editorState().isContentRichlyEditable && _page->editorState().selectionIsRange && !_showingTextStyleOptions;
2049     if (_showingTextStyleOptions)
2050         return (action == @selector(toggleBoldface:) || action == @selector(toggleItalics:) || action == @selector(toggleUnderline:));
2051     if (action == @selector(toggleBoldface:) || action == @selector(toggleItalics:) || action == @selector(toggleUnderline:))
2052         return _page->editorState().isContentRichlyEditable;
2053     if (action == @selector(cut:))
2054         return !_page->editorState().isInPasswordField && _page->editorState().isContentEditable && _page->editorState().selectionIsRange;
2055     
2056     if (action == @selector(paste:)) {
2057         if (_page->editorState().selectionIsNone || !_page->editorState().isContentEditable)
2058             return NO;
2059         UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
2060         NSArray *types = [self supportedPasteboardTypesForCurrentSelection];
2061         NSIndexSet *indices = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [pasteboard numberOfItems])];
2062         return [pasteboard containsPasteboardTypes:types inItemSet:indices];
2063     }
2064
2065     if (action == @selector(copy:)) {
2066         if (_page->editorState().isInPasswordField)
2067             return NO;
2068         return hasWebSelection || _page->editorState().selectionIsRange;
2069     }
2070
2071     if (action == @selector(_define:)) {
2072         if (_page->editorState().isInPasswordField || !(hasWebSelection || _page->editorState().selectionIsRange))
2073             return NO;
2074
2075         NSUInteger textLength = _page->editorState().postLayoutData().selectedTextLength;
2076         // FIXME: We should be calling UIReferenceLibraryViewController to check if the length is
2077         // acceptable, but the interface takes a string.
2078         // <rdar://problem/15254406>
2079         if (!textLength || textLength > 200)
2080             return NO;
2081
2082         if ([[getMCProfileConnectionClass() sharedConnection] effectiveBoolValueForSetting:MCFeatureDefinitionLookupAllowed] == MCRestrictedBoolExplicitNo)
2083             return NO;
2084             
2085         return YES;
2086     }
2087
2088     if (action == @selector(_lookup:)) {
2089         if (_page->editorState().isInPasswordField)
2090             return NO;
2091         
2092         if ([[getMCProfileConnectionClass() sharedConnection] effectiveBoolValueForSetting:MCFeatureDefinitionLookupAllowed] == MCRestrictedBoolExplicitNo)
2093             return NO;
2094         
2095         return YES;
2096     }
2097
2098     if (action == @selector(_share:)) {
2099         if (_page->editorState().isInPasswordField || !(hasWebSelection || _page->editorState().selectionIsRange))
2100             return NO;
2101
2102         return _page->editorState().postLayoutData().selectedTextLength > 0;
2103     }
2104
2105     if (action == @selector(_addShortcut:)) {
2106         if (_page->editorState().isInPasswordField || !(hasWebSelection || _page->editorState().selectionIsRange))
2107             return NO;
2108
2109         NSString *selectedText = [self selectedText];
2110         if (![selectedText length])
2111             return NO;
2112
2113         if (!UIKeyboardEnabledInputModesAllowOneToManyShortcuts())
2114             return NO;
2115         if (![selectedText _containsCJScripts])
2116             return NO;
2117         return YES;
2118     }
2119
2120     if (action == @selector(_promptForReplace:)) {
2121         if (!_page->editorState().selectionIsRange || !_page->editorState().postLayoutData().isReplaceAllowed || ![[UIKeyboardImpl activeInstance] autocorrectSpellingEnabled])
2122             return NO;
2123         if ([[self selectedText] _containsCJScriptsOnly])
2124             return NO;
2125         return YES;
2126     }
2127
2128     if (action == @selector(_transliterateChinese:)) {
2129         if (!_page->editorState().selectionIsRange || !_page->editorState().postLayoutData().isReplaceAllowed || ![[UIKeyboardImpl activeInstance] autocorrectSpellingEnabled])
2130             return NO;
2131         return UIKeyboardEnabledInputModesAllowChineseTransliterationForText([self selectedText]);
2132     }
2133
2134     if (action == @selector(_reanalyze:)) {
2135         if (!_page->editorState().selectionIsRange || !_page->editorState().postLayoutData().isReplaceAllowed || ![[UIKeyboardImpl activeInstance] autocorrectSpellingEnabled])
2136             return NO;
2137         return UIKeyboardCurrentInputModeAllowsChineseOrJapaneseReanalysisForText([self selectedText]);
2138     }
2139
2140     if (action == @selector(select:)) {
2141         // Disable select in password fields so that you can't see word boundaries.
2142         return !_page->editorState().isInPasswordField && [self hasContent] && !_page->editorState().selectionIsNone && !_page->editorState().selectionIsRange;
2143     }
2144
2145     if (action == @selector(selectAll:)) {
2146         if (_page->editorState().selectionIsNone || ![self hasContent])
2147             return NO;
2148         if (!_page->editorState().selectionIsRange)
2149             return YES;
2150         // Enable selectAll for non-editable text, where the user can't access
2151         // this command via long-press to get a caret.
2152         if (_page->editorState().isContentEditable)
2153             return NO;
2154         // Don't attempt selectAll with general web content.
2155         if (hasWebSelection)
2156             return NO;
2157         // FIXME: Only enable if the selection doesn't already span the entire document.
2158         return YES;
2159     }
2160
2161     if (action == @selector(replace:))
2162         return _page->editorState().isContentEditable && !_page->editorState().isInPasswordField;
2163
2164     return [super canPerformAction:action withSender:sender];
2165 }
2166
2167 - (void)_resetShowingTextStyle:(NSNotification *)notification
2168 {
2169     _showingTextStyleOptions = NO;
2170     [_textSelectionAssistant hideTextStyleOptions];
2171 }
2172
2173 - (void)copyForWebView:(id)sender
2174 {
2175     _page->executeEditCommand(ASCIILiteral("copy"));
2176 }
2177
2178 - (void)cutForWebView:(id)sender
2179 {
2180     _page->executeEditCommand(ASCIILiteral("cut"));
2181 }
2182
2183 - (void)pasteForWebView:(id)sender
2184 {
2185     _page->executeEditCommand(ASCIILiteral("paste"));
2186 }
2187
2188 - (void)selectForWebView:(id)sender
2189 {
2190     [_textSelectionAssistant selectWord];
2191     // We cannot use selectWord command, because we want to be able to select the word even when it is the last in the paragraph.
2192     _page->extendSelection(WordGranularity);
2193 }
2194
2195 - (void)selectAllForWebView:(id)sender
2196 {
2197     [_textSelectionAssistant selectAll:sender];
2198     _page->executeEditCommand(ASCIILiteral("selectAll"));
2199 }
2200
2201 - (void)toggleBoldfaceForWebView:(id)sender
2202 {
2203     if (!_page->editorState().isContentRichlyEditable)
2204         return;
2205
2206     [self executeEditCommandWithCallback:@"toggleBold"];
2207 }
2208
2209 - (void)toggleItalicsForWebView:(id)sender
2210 {
2211     if (!_page->editorState().isContentRichlyEditable)
2212         return;
2213
2214     [self executeEditCommandWithCallback:@"toggleItalic"];
2215 }
2216
2217 - (void)toggleUnderlineForWebView:(id)sender
2218 {
2219     if (!_page->editorState().isContentRichlyEditable)
2220         return;
2221
2222     [self executeEditCommandWithCallback:@"toggleUnderline"];
2223 }
2224
2225 - (void)_showTextStyleOptionsForWebView:(id)sender
2226 {
2227     _showingTextStyleOptions = YES;
2228     [_textSelectionAssistant showTextStyleOptions];
2229 }
2230
2231 - (void)_showDictionary:(NSString *)text
2232 {
2233     CGRect presentationRect = _page->editorState().postLayoutData().selectionRects[0].rect();
2234     if (_textSelectionAssistant)
2235         [_textSelectionAssistant showDictionaryFor:text fromRect:presentationRect];
2236     else
2237         [_webSelectionAssistant showDictionaryFor:text fromRect:presentationRect];
2238 }
2239
2240 - (void)_defineForWebView:(id)sender
2241 {
2242     if ([[getMCProfileConnectionClass() sharedConnection] effectiveBoolValueForSetting:MCFeatureDefinitionLookupAllowed] == MCRestrictedBoolExplicitNo)
2243         return;
2244
2245     RetainPtr<WKContentView> view = self;
2246     _page->getSelectionOrContentsAsString([view](const String& string, WebKit::CallbackBase::Error error) {
2247         if (error != WebKit::CallbackBase::Error::None)
2248             return;
2249         if (!string)
2250             return;
2251
2252         [view _showDictionary:string];
2253     });
2254 }
2255
2256 - (void)accessibilityRetrieveSpeakSelectionContent
2257 {
2258     RetainPtr<WKContentView> view = self;
2259     RetainPtr<WKWebView> webView = _webView;
2260     _page->getSelectionOrContentsAsString([view, webView](const String& string, WebKit::CallbackBase::Error error) {
2261         if (error != WebKit::CallbackBase::Error::None)
2262             return;
2263         [webView _accessibilityDidGetSpeakSelectionContent:string];
2264         if ([view respondsToSelector:@selector(accessibilitySpeakSelectionSetContent:)])
2265             [view accessibilitySpeakSelectionSetContent:string];
2266     });
2267 }
2268
2269 - (void)_accessibilityRetrieveRectsEnclosingSelectionOffset:(NSInteger)offset withGranularity:(UITextGranularity)granularity
2270 {
2271     RetainPtr<WKContentView> view = self;
2272     _page->requestRectsForGranularityWithSelectionOffset(toWKTextGranularity(granularity), offset , [view, offset, granularity](const Vector<WebCore::SelectionRect>& selectionRects, CallbackBase::Error error) {
2273         if (error != WebKit::CallbackBase::Error::None)
2274             return;
2275         if ([view respondsToSelector:@selector(_accessibilityDidGetSelectionRects:withGranularity:atOffset:)])
2276             [view _accessibilityDidGetSelectionRects:[view webSelectionRectsForSelectionRects:selectionRects] withGranularity:granularity atOffset:offset];
2277     });
2278 }
2279
2280 - (void)_accessibilityRetrieveRectsAtSelectionOffset:(NSInteger)offset withText:(NSString *)text
2281 {
2282     RetainPtr<WKContentView> view = self;
2283     _page->requestRectsAtSelectionOffsetWithText(offset, text, [view, offset](const Vector<WebCore::SelectionRect>& selectionRects, CallbackBase::Error error) {
2284         if (error != WebKit::CallbackBase::Error::None)
2285             return;
2286         if ([view respondsToSelector:@selector(_accessibilityDidGetSelectionRects:withGranularity:atOffset:)])
2287             [view _accessibilityDidGetSelectionRects:[view webSelectionRectsForSelectionRects:selectionRects] withGranularity:UITextGranularityWord atOffset:offset];
2288     });
2289 }
2290
2291 // UIWKInteractionViewProtocol
2292
2293 static inline GestureType toGestureType(UIWKGestureType gestureType)
2294 {
2295     switch (gestureType) {
2296     case UIWKGestureLoupe:
2297         return GestureType::Loupe;
2298     case UIWKGestureOneFingerTap:
2299         return GestureType::OneFingerTap;
2300     case UIWKGestureTapAndAHalf:
2301         return GestureType::TapAndAHalf;
2302     case UIWKGestureDoubleTap:
2303         return GestureType::DoubleTap;
2304     case UIWKGestureTapAndHalf:
2305         return GestureType::TapAndHalf;
2306     case UIWKGestureDoubleTapInUneditable:
2307         return GestureType::DoubleTapInUneditable;
2308     case UIWKGestureOneFingerTapInUneditable:
2309         return GestureType::OneFingerTapInUneditable;
2310     case UIWKGestureOneFingerTapSelectsAll:
2311         return GestureType::OneFingerTapSelectsAll;
2312     case UIWKGestureOneFingerDoubleTap:
2313         return GestureType::OneFingerDoubleTap;
2314     case UIWKGestureOneFingerTripleTap:
2315         return GestureType::OneFingerTripleTap;
2316     case UIWKGestureTwoFingerSingleTap:
2317         return GestureType::TwoFingerSingleTap;
2318     case UIWKGestureTwoFingerRangedSelectGesture:
2319         return GestureType::TwoFingerRangedSelectGesture;
2320     case UIWKGestureTapOnLinkWithGesture:
2321         return GestureType::TapOnLinkWithGesture;
2322     case UIWKGestureMakeWebSelection:
2323         return GestureType::MakeWebSelection;
2324     case UIWKGesturePhraseBoundary:
2325         return GestureType::PhraseBoundary;
2326     }
2327     ASSERT_NOT_REACHED();
2328     return GestureType::Loupe;
2329 }
2330
2331 static inline UIWKGestureType toUIWKGestureType(GestureType gestureType)
2332 {
2333     switch (gestureType) {
2334     case GestureType::Loupe:
2335         return UIWKGestureLoupe;
2336     case GestureType::OneFingerTap:
2337         return UIWKGestureOneFingerTap;
2338     case GestureType::TapAndAHalf:
2339         return UIWKGestureTapAndAHalf;
2340     case GestureType::DoubleTap:
2341         return UIWKGestureDoubleTap;
2342     case GestureType::TapAndHalf:
2343         return UIWKGestureTapAndHalf;
2344     case GestureType::DoubleTapInUneditable:
2345         return UIWKGestureDoubleTapInUneditable;
2346     case GestureType::OneFingerTapInUneditable:
2347         return UIWKGestureOneFingerTapInUneditable;
2348     case GestureType::OneFingerTapSelectsAll:
2349         return UIWKGestureOneFingerTapSelectsAll;
2350     case GestureType::OneFingerDoubleTap:
2351         return UIWKGestureOneFingerDoubleTap;
2352     case GestureType::OneFingerTripleTap:
2353         return UIWKGestureOneFingerTripleTap;
2354     case GestureType::TwoFingerSingleTap:
2355         return UIWKGestureTwoFingerSingleTap;
2356     case GestureType::TwoFingerRangedSelectGesture:
2357         return UIWKGestureTwoFingerRangedSelectGesture;
2358     case GestureType::TapOnLinkWithGesture:
2359         return UIWKGestureTapOnLinkWithGesture;
2360     case GestureType::MakeWebSelection:
2361         return UIWKGestureMakeWebSelection;
2362     case GestureType::PhraseBoundary:
2363         return UIWKGesturePhraseBoundary;
2364     }
2365 }
2366
2367 static inline SelectionTouch toSelectionTouch(UIWKSelectionTouch touch)
2368 {
2369     switch (touch) {
2370     case UIWKSelectionTouchStarted:
2371         return SelectionTouch::Started;
2372     case UIWKSelectionTouchMoved:
2373         return SelectionTouch::Moved;
2374     case UIWKSelectionTouchEnded:
2375         return SelectionTouch::Ended;
2376     case UIWKSelectionTouchEndedMovingForward:
2377         return SelectionTouch::EndedMovingForward;
2378     case UIWKSelectionTouchEndedMovingBackward:
2379         return SelectionTouch::EndedMovingBackward;
2380     case UIWKSelectionTouchEndedNotMoving:
2381         return SelectionTouch::EndedNotMoving;
2382     }
2383     ASSERT_NOT_REACHED();
2384     return SelectionTouch::Ended;
2385 }
2386
2387 static inline UIWKSelectionTouch toUIWKSelectionTouch(SelectionTouch touch)
2388 {
2389     switch (touch) {
2390     case SelectionTouch::Started:
2391         return UIWKSelectionTouchStarted;
2392     case SelectionTouch::Moved:
2393         return UIWKSelectionTouchMoved;
2394     case SelectionTouch::Ended:
2395         return UIWKSelectionTouchEnded;
2396     case SelectionTouch::EndedMovingForward:
2397         return UIWKSelectionTouchEndedMovingForward;
2398     case SelectionTouch::EndedMovingBackward:
2399         return UIWKSelectionTouchEndedMovingBackward;
2400     case SelectionTouch::EndedNotMoving:
2401         return UIWKSelectionTouchEndedNotMoving;
2402     }
2403 }
2404
2405 static inline GestureRecognizerState toGestureRecognizerState(UIGestureRecognizerState state)
2406 {
2407     switch (state) {
2408     case UIGestureRecognizerStatePossible:
2409         return GestureRecognizerState::Possible;
2410     case UIGestureRecognizerStateBegan:
2411         return GestureRecognizerState::Began;
2412     case UIGestureRecognizerStateChanged:
2413         return GestureRecognizerState::Changed;
2414     case UIGestureRecognizerStateCancelled:
2415         return GestureRecognizerState::Cancelled;
2416     case UIGestureRecognizerStateEnded:
2417         return GestureRecognizerState::Ended;
2418     case UIGestureRecognizerStateFailed:
2419         return GestureRecognizerState::Failed;
2420     }
2421 }
2422
2423 static inline UIGestureRecognizerState toUIGestureRecognizerState(GestureRecognizerState state)
2424 {
2425     switch (state) {
2426     case GestureRecognizerState::Possible:
2427         return UIGestureRecognizerStatePossible;
2428     case GestureRecognizerState::Began:
2429         return UIGestureRecognizerStateBegan;
2430     case GestureRecognizerState::Changed:
2431         return UIGestureRecognizerStateChanged;
2432     case GestureRecognizerState::Cancelled:
2433         return UIGestureRecognizerStateCancelled;
2434     case GestureRecognizerState::Ended:
2435         return UIGestureRecognizerStateEnded;
2436     case GestureRecognizerState::Failed:
2437         return UIGestureRecognizerStateFailed;
2438     }
2439 }
2440
2441 static inline UIWKSelectionFlags toUIWKSelectionFlags(SelectionFlags flags)
2442 {
2443     NSInteger uiFlags = UIWKNone;
2444     if (flags & WordIsNearTap)
2445         uiFlags |= UIWKWordIsNearTap;
2446     if (flags & IsBlockSelection)
2447         uiFlags |= UIWKIsBlockSelection;
2448     if (flags & PhraseBoundaryChanged)
2449         uiFlags |= UIWKPhraseBoundaryChanged;
2450
2451     return static_cast<UIWKSelectionFlags>(uiFlags);
2452 }
2453
2454 static inline SelectionHandlePosition toSelectionHandlePosition(UIWKHandlePosition position)
2455 {
2456     switch (position) {
2457     case UIWKHandleTop:
2458         return SelectionHandlePosition::Top;
2459     case UIWKHandleRight:
2460         return SelectionHandlePosition::Right;
2461     case UIWKHandleBottom:
2462         return SelectionHandlePosition::Bottom;
2463     case UIWKHandleLeft:
2464         return SelectionHandlePosition::Left;
2465     }
2466 }
2467
2468 static inline WebCore::TextGranularity toWKTextGranularity(UITextGranularity granularity)
2469 {
2470     switch (granularity) {
2471     case UITextGranularityCharacter:
2472         return CharacterGranularity;
2473     case UITextGranularityWord:
2474         return WordGranularity;
2475     case UITextGranularitySentence:
2476         return SentenceGranularity;
2477     case UITextGranularityParagraph:
2478         return ParagraphGranularity;
2479     case UITextGranularityLine:
2480         return LineGranularity;
2481     case UITextGranularityDocument:
2482         return DocumentGranularity;
2483     }
2484 }
2485
2486 static inline WebCore::SelectionDirection toWKSelectionDirection(UITextDirection direction)
2487 {
2488     switch (direction) {
2489     case UITextLayoutDirectionDown:
2490     case UITextLayoutDirectionRight:
2491         return DirectionRight;
2492     case UITextLayoutDirectionUp:
2493     case UITextLayoutDirectionLeft:
2494         return DirectionLeft;
2495     default:
2496         // UITextDirection is not an enum, but we only want to accept values from UITextLayoutDirection.
2497         ASSERT_NOT_REACHED();
2498         return DirectionRight;
2499     }
2500 }
2501
2502 static void selectionChangedWithGesture(WKContentView *view, const WebCore::IntPoint& point, uint32_t gestureType, uint32_t gestureState, uint32_t flags, WebKit::CallbackBase::Error error)
2503 {
2504     if (error != WebKit::CallbackBase::Error::None) {
2505         ASSERT_NOT_REACHED();
2506         return;
2507     }
2508     if ([view webSelectionAssistant])
2509         [(UIWKSelectionAssistant *)[view webSelectionAssistant] selectionChangedWithGestureAt:(CGPoint)point withGesture:toUIWKGestureType((GestureType)gestureType) withState:toUIGestureRecognizerState(static_cast<GestureRecognizerState>(gestureState)) withFlags:(toUIWKSelectionFlags((SelectionFlags)flags))];
2510     else
2511         [(UIWKTextInteractionAssistant *)[view interactionAssistant] selectionChangedWithGestureAt:(CGPoint)point withGesture:toUIWKGestureType((GestureType)gestureType) withState:toUIGestureRecognizerState(static_cast<GestureRecognizerState>(gestureState)) withFlags:(toUIWKSelectionFlags((SelectionFlags)flags))];
2512 }
2513
2514 static void selectionChangedWithTouch(WKContentView *view, const WebCore::IntPoint& point, uint32_t touch, uint32_t flags, WebKit::CallbackBase::Error error)
2515 {
2516     if (error != WebKit::CallbackBase::Error::None) {
2517         ASSERT_NOT_REACHED();
2518         return;
2519     }
2520     if ([view webSelectionAssistant])
2521         [(UIWKSelectionAssistant *)[view webSelectionAssistant] selectionChangedWithTouchAt:(CGPoint)point withSelectionTouch:toUIWKSelectionTouch((SelectionTouch)touch) withFlags:static_cast<UIWKSelectionFlags>(flags)];
2522     else
2523         [(UIWKTextInteractionAssistant *)[view interactionAssistant] selectionChangedWithTouchAt:(CGPoint)point withSelectionTouch:toUIWKSelectionTouch((SelectionTouch)touch)];
2524 }
2525
2526 - (void)_didUpdateBlockSelectionWithTouch:(SelectionTouch)touch withFlags:(SelectionFlags)flags growThreshold:(CGFloat)growThreshold shrinkThreshold:(CGFloat)shrinkThreshold
2527 {
2528     [_webSelectionAssistant blockSelectionChangedWithTouch:toUIWKSelectionTouch(touch) withFlags:toUIWKSelectionFlags(flags) growThreshold:growThreshold shrinkThreshold:shrinkThreshold];
2529     if (touch != SelectionTouch::Started && touch != SelectionTouch::Moved)
2530         _usingGestureForSelection = NO;
2531 }
2532
2533 - (BOOL)_isInteractingWithAssistedNode
2534 {
2535     return _textSelectionAssistant != nil;
2536 }
2537
2538 - (void)changeSelectionWithGestureAt:(CGPoint)point withGesture:(UIWKGestureType)gestureType withState:(UIGestureRecognizerState)state
2539 {
2540     _usingGestureForSelection = YES;
2541     _page->selectWithGesture(WebCore::IntPoint(point), CharacterGranularity, static_cast<uint32_t>(toGestureType(gestureType)), static_cast<uint32_t>(toGestureRecognizerState(state)), [self _isInteractingWithAssistedNode], [self, state](const WebCore::IntPoint& point, uint32_t gestureType, uint32_t gestureState, uint32_t flags, WebKit::CallbackBase::Error error) {
2542         selectionChangedWithGesture(self, point, gestureType, gestureState, flags, error);
2543         if (state == UIGestureRecognizerStateEnded || state == UIGestureRecognizerStateCancelled)
2544             _usingGestureForSelection = NO;
2545     });
2546 }
2547
2548 - (void)changeSelectionWithTouchAt:(CGPoint)point withSelectionTouch:(UIWKSelectionTouch)touch baseIsStart:(BOOL)baseIsStart
2549 {
2550     _usingGestureForSelection = YES;
2551     _page->updateSelectionWithTouches(WebCore::IntPoint(point), static_cast<uint32_t>(toSelectionTouch(touch)), baseIsStart, [self, touch](const WebCore::IntPoint& point, uint32_t touch, uint32_t flags, WebKit::CallbackBase::Error error) {
2552         selectionChangedWithTouch(self, point, touch, flags, error);
2553         if (touch != UIWKSelectionTouchStarted && touch != UIWKSelectionTouchMoved)
2554             _usingGestureForSelection = NO;
2555     });
2556 }
2557
2558 - (void)changeSelectionWithTouchesFrom:(CGPoint)from to:(CGPoint)to withGesture:(UIWKGestureType)gestureType withState:(UIGestureRecognizerState)gestureState
2559 {
2560     _usingGestureForSelection = YES;
2561     _page->selectWithTwoTouches(WebCore::IntPoint(from), WebCore::IntPoint(to), static_cast<uint32_t>(toGestureType(gestureType)), static_cast<uint32_t>(toGestureRecognizerState(gestureState)), [self, gestureState](const WebCore::IntPoint& point, uint32_t gestureType, uint32_t gestureState, uint32_t flags, WebKit::CallbackBase::Error error) {
2562         selectionChangedWithGesture(self, point, gestureType, gestureState, flags, error);
2563         if (gestureState == UIGestureRecognizerStateEnded || gestureState == UIGestureRecognizerStateCancelled)
2564             _usingGestureForSelection = NO;
2565     });
2566 }
2567
2568 - (void)changeBlockSelectionWithTouchAt:(CGPoint)point withSelectionTouch:(UIWKSelectionTouch)touch forHandle:(UIWKHandlePosition)handle
2569 {
2570     _usingGestureForSelection = YES;
2571     _page->updateBlockSelectionWithTouch(WebCore::IntPoint(point), static_cast<uint32_t>(toSelectionTouch(touch)), static_cast<uint32_t>(toSelectionHandlePosition(handle)));
2572 }
2573
2574 - (void)moveByOffset:(NSInteger)offset
2575 {
2576     if (!offset)
2577         return;
2578     
2579     [self beginSelectionChange];
2580     RetainPtr<WKContentView> view = self;
2581     _page->moveSelectionByOffset(offset, [view](WebKit::CallbackBase::Error) {
2582         [view endSelectionChange];
2583     });
2584 }
2585
2586 - (const WKAutoCorrectionData&)autocorrectionData
2587 {
2588     return _autocorrectionData;
2589 }
2590
2591 // The completion handler can pass nil if input does not match the actual text preceding the insertion point.
2592 - (void)requestAutocorrectionRectsForString:(NSString *)input withCompletionHandler:(void (^)(UIWKAutocorrectionRects *rectsForInput))completionHandler
2593 {
2594     if (!input || ![input length]) {
2595         completionHandler(nil);
2596         return;
2597     }
2598
2599     RetainPtr<WKContentView> view = self;
2600     _autocorrectionData.autocorrectionHandler = [completionHandler copy];
2601     _page->requestAutocorrectionData(input, [view](const Vector<FloatRect>& rects, const String& fontName, double fontSize, uint64_t traits, WebKit::CallbackBase::Error) {
2602         CGRect firstRect = CGRectZero;
2603         CGRect lastRect = CGRectZero;
2604         if (rects.size()) {
2605             firstRect = rects[0];
2606             lastRect = rects[rects.size() - 1];
2607         }
2608         
2609         view->_autocorrectionData.fontName = fontName;
2610         view->_autocorrectionData.fontSize = fontSize;
2611         view->_autocorrectionData.fontTraits = traits;
2612         view->_autocorrectionData.textFirstRect = firstRect;
2613         view->_autocorrectionData.textLastRect = lastRect;
2614
2615         view->_autocorrectionData.autocorrectionHandler(rects.size() ? [WKAutocorrectionRects autocorrectionRectsWithRects:firstRect lastRect:lastRect] : nil);
2616         [view->_autocorrectionData.autocorrectionHandler release];
2617         view->_autocorrectionData.autocorrectionHandler = nil;
2618     });
2619 }
2620
2621 - (void)selectPositionAtPoint:(CGPoint)point completionHandler:(void (^)(void))completionHandler
2622 {
2623     _usingGestureForSelection = YES;
2624     UIWKSelectionCompletionHandler selectionHandler = [completionHandler copy];
2625     RetainPtr<WKContentView> view = self;
2626     
2627     _page->selectPositionAtPoint(WebCore::IntPoint(point), [self _isInteractingWithAssistedNode], [view, selectionHandler](WebKit::CallbackBase::Error error) {
2628         selectionHandler();
2629         view->_usingGestureForSelection = NO;
2630         [selectionHandler release];
2631     });
2632 }
2633
2634 - (void)selectPositionAtBoundary:(UITextGranularity)granularity inDirection:(UITextDirection)direction fromPoint:(CGPoint)point completionHandler:(void (^)(void))completionHandler
2635 {
2636     _usingGestureForSelection = YES;
2637     UIWKSelectionCompletionHandler selectionHandler = [completionHandler copy];
2638     RetainPtr<WKContentView> view = self;
2639     
2640     _page->selectPositionAtBoundaryWithDirection(WebCore::IntPoint(point), toWKTextGranularity(granularity), toWKSelectionDirection(direction), [self _isInteractingWithAssistedNode], [view, selectionHandler](WebKit::CallbackBase::Error error) {
2641         selectionHandler();
2642         view->_usingGestureForSelection = NO;
2643         [selectionHandler release];
2644     });
2645 }
2646
2647 - (void)moveSelectionAtBoundary:(UITextGranularity)granularity inDirection:(UITextDirection)direction completionHandler:(void (^)(void))completionHandler
2648 {
2649     _usingGestureForSelection = YES;
2650     UIWKSelectionCompletionHandler selectionHandler = [completionHandler copy];
2651     RetainPtr<WKContentView> view = self;
2652     
2653     _page->moveSelectionAtBoundaryWithDirection(toWKTextGranularity(granularity), toWKSelectionDirection(direction), [view, selectionHandler](WebKit::CallbackBase::Error error) {
2654         selectionHandler();
2655         view->_usingGestureForSelection = NO;
2656         [selectionHandler release];
2657     });
2658 }
2659
2660 - (void)selectTextWithGranularity:(UITextGranularity)granularity atPoint:(CGPoint)point completionHandler:(void (^)(void))completionHandler
2661 {
2662     _usingGestureForSelection = YES;
2663     UIWKSelectionCompletionHandler selectionHandler = [completionHandler copy];
2664     RetainPtr<WKContentView> view = self;
2665
2666     _page->selectTextWithGranularityAtPoint(WebCore::IntPoint(point), toWKTextGranularity(granularity), [self _isInteractingWithAssistedNode], [view, selectionHandler](WebKit::CallbackBase::Error error) {
2667         selectionHandler();
2668         view->_usingGestureForSelection = NO;
2669         [selectionHandler release];
2670     });
2671 }
2672
2673 - (void)beginSelectionInDirection:(UITextDirection)direction completionHandler:(void (^)(BOOL endIsMoving))completionHandler
2674 {
2675     UIWKSelectionWithDirectionCompletionHandler selectionHandler = [completionHandler copy];
2676
2677     _page->beginSelectionInDirection(toWKSelectionDirection(direction), [selectionHandler](bool endIsMoving, WebKit::CallbackBase::Error error) {
2678         selectionHandler(endIsMoving);
2679         [selectionHandler release];
2680     });
2681 }
2682
2683 - (void)updateSelectionWithExtentPoint:(CGPoint)point completionHandler:(void (^)(BOOL endIsMoving))completionHandler
2684 {
2685     UIWKSelectionWithDirectionCompletionHandler selectionHandler = [completionHandler copy];
2686     
2687     _page->updateSelectionWithExtentPoint(WebCore::IntPoint(point), [self _isInteractingWithAssistedNode], [selectionHandler](bool endIsMoving, WebKit::CallbackBase::Error error) {
2688         selectionHandler(endIsMoving);
2689         [selectionHandler release];
2690     });
2691 }
2692
2693 - (void)updateSelectionWithExtentPoint:(CGPoint)point withBoundary:(UITextGranularity)granularity completionHandler:(void (^)(BOOL selectionEndIsMoving))completionHandler
2694 {
2695     UIWKSelectionWithDirectionCompletionHandler selectionHandler = [completionHandler copy];
2696     
2697     _page->updateSelectionWithExtentPointAndBoundary(WebCore::IntPoint(point), toWKTextGranularity(granularity), [self _isInteractingWithAssistedNode], [selectionHandler](bool endIsMoving, WebKit::CallbackBase::Error error) {
2698         selectionHandler(endIsMoving);
2699         [selectionHandler release];
2700     });
2701 }
2702
2703 - (UTF32Char)_characterBeforeCaretSelection
2704 {
2705     return _page->editorState().postLayoutData().characterBeforeSelection;
2706 }
2707
2708 - (UTF32Char)_characterInRelationToCaretSelection:(int)amount
2709 {
2710     switch (amount) {
2711     case 0:
2712         return _page->editorState().postLayoutData().characterAfterSelection;
2713     case -1:
2714         return _page->editorState().postLayoutData().characterBeforeSelection;
2715     case -2:
2716         return _page->editorState().postLayoutData().twoCharacterBeforeSelection;
2717     default:
2718         return 0;
2719     }
2720 }
2721
2722 - (BOOL)_selectionAtDocumentStart
2723 {
2724     return !_page->editorState().postLayoutData().characterBeforeSelection;
2725 }
2726
2727 - (CGRect)textFirstRect
2728 {
2729     return (_page->editorState().hasComposition) ? _page->editorState().firstMarkedRect : _autocorrectionData.textFirstRect;
2730 }
2731
2732 - (CGRect)textLastRect
2733 {
2734     return (_page->editorState().hasComposition) ? _page->editorState().lastMarkedRect : _autocorrectionData.textLastRect;
2735 }
2736
2737 - (void)replaceDictatedText:(NSString*)oldText withText:(NSString *)newText
2738 {
2739     _page->replaceDictatedText(oldText, newText);
2740 }
2741
2742 - (void)requestDictationContext:(void (^)(NSString *selectedText, NSString *beforeText, NSString *afterText))completionHandler
2743 {
2744     UIWKDictationContextHandler dictationHandler = [completionHandler copy];
2745
2746     _page->requestDictationContext([dictationHandler](const String& selectedText, const String& beforeText, const String& afterText, WebKit::CallbackBase::Error) {
2747         dictationHandler(selectedText, beforeText, afterText);
2748         [dictationHandler release];
2749     });
2750 }
2751
2752 // The completion handler should pass the rect of the correction text after replacing the input text, or nil if the replacement could not be performed.
2753 - (void)applyAutocorrection:(NSString *)correction toString:(NSString *)input withCompletionHandler:(void (^)(UIWKAutocorrectionRects *rectsForCorrection))completionHandler
2754 {
2755     // FIXME: Remove the synchronous call when <rdar://problem/16207002> is fixed.
2756     const bool useSyncRequest = true;
2757
2758     if (useSyncRequest) {
2759         completionHandler(_page->applyAutocorrection(correction, input) ? [WKAutocorrectionRects autocorrectionRectsWithRects:_autocorrectionData.textFirstRect lastRect:_autocorrectionData.textLastRect] : nil);
2760         return;
2761     }
2762     _autocorrectionData.autocorrectionHandler = [completionHandler copy];
2763     RetainPtr<WKContentView> view = self;
2764     _page->applyAutocorrection(correction, input, [view](const String& string, WebKit::CallbackBase::Error error) {
2765         view->_autocorrectionData.autocorrectionHandler(!string.isNull() ? [WKAutocorrectionRects autocorrectionRectsWithRects:view->_autocorrectionData.textFirstRect lastRect:view->_autocorrectionData.textLastRect] : nil);
2766         [view->_autocorrectionData.autocorrectionHandler release];
2767         view->_autocorrectionData.autocorrectionHandler = nil;
2768     });
2769 }
2770
2771 - (void)requestAutocorrectionContextWithCompletionHandler:(void (^)(UIWKAutocorrectionContext *autocorrectionContext))completionHandler
2772 {
2773     // FIXME: Remove the synchronous call when <rdar://problem/16207002> is fixed.
2774     const bool useSyncRequest = true;
2775
2776     if (useSyncRequest) {
2777         String beforeText;
2778         String markedText;
2779         String selectedText;
2780         String afterText;
2781         uint64_t location;
2782         uint64_t length;
2783         _page->getAutocorrectionContext(beforeText, markedText, selectedText, afterText, location, length);
2784         completionHandler([WKAutocorrectionContext autocorrectionContextWithData:beforeText markedText:markedText selectedText:selectedText afterText:afterText selectedRangeInMarkedText:NSMakeRange(location, length)]);
2785     } else {
2786         _autocorrectionData.autocorrectionContextHandler = [completionHandler copy];
2787         RetainPtr<WKContentView> view = self;
2788         _page->requestAutocorrectionContext([view](const String& beforeText, const String& markedText, const String& selectedText, const String& afterText, uint64_t location, uint64_t length, WebKit::CallbackBase::Error) {
2789             view->_autocorrectionData.autocorrectionContextHandler([WKAutocorrectionContext autocorrectionContextWithData:beforeText markedText:markedText selectedText:selectedText afterText:afterText selectedRangeInMarkedText:NSMakeRange(location, length)]);
2790         });
2791     }
2792 }
2793
2794 // UIWebFormAccessoryDelegate
2795 - (void)accessoryDone
2796 {
2797     [self resignFirstResponder];
2798 }
2799
2800 - (NSArray *)keyCommands
2801 {
2802     static NSArray* nonEditableKeyCommands = [@[
2803        [UIKeyCommand keyCommandWithInput:UIKeyInputUpArrow modifierFlags:0 action:@selector(_arrowKey:)],
2804        [UIKeyCommand keyCommandWithInput:UIKeyInputDownArrow modifierFlags:0 action:@selector(_arrowKey:)],
2805        [UIKeyCommand keyCommandWithInput:UIKeyInputLeftArrow modifierFlags:0 action:@selector(_arrowKey:)],
2806        [UIKeyCommand keyCommandWithInput:UIKeyInputRightArrow modifierFlags:0 action:@selector(_arrowKey:)],
2807        
2808        [UIKeyCommand keyCommandWithInput:UIKeyInputUpArrow modifierFlags:UIKeyModifierCommand action:@selector(_arrowKey:)],
2809        [UIKeyCommand keyCommandWithInput:UIKeyInputDownArrow modifierFlags:UIKeyModifierCommand action:@selector(_arrowKey:)],
2810        
2811        [UIKeyCommand keyCommandWithInput:UIKeyInputUpArrow modifierFlags:UIKeyModifierShift action:@selector(_arrowKey:)],
2812        [UIKeyCommand keyCommandWithInput:UIKeyInputDownArrow modifierFlags:UIKeyModifierShift action:@selector(_arrowKey:)],
2813        [UIKeyCommand keyCommandWithInput:UIKeyInputLeftArrow modifierFlags:UIKeyModifierShift action:@selector(_arrowKey:)],
2814        [UIKeyCommand keyCommandWithInput:UIKeyInputRightArrow modifierFlags:UIKeyModifierShift action:@selector(_arrowKey:)],
2815        
2816        [UIKeyCommand keyCommandWithInput:UIKeyInputUpArrow modifierFlags:UIKeyModifierAlternate action:@selector(_arrowKey:)],
2817        [UIKeyCommand keyCommandWithInput:UIKeyInputDownArrow modifierFlags:UIKeyModifierAlternate action:@selector(_arrowKey:)],
2818        [UIKeyCommand keyCommandWithInput:UIKeyInputLeftArrow modifierFlags:UIKeyModifierAlternate action:@selector(_arrowKey:)],
2819        [UIKeyCommand keyCommandWithInput:UIKeyInputRightArrow modifierFlags:UIKeyModifierAlternate action:@selector(_arrowKey:)],
2820        
2821        [UIKeyCommand keyCommandWithInput:@" " modifierFlags:0 action:@selector(_arrowKey:)],
2822        [UIKeyCommand keyCommandWithInput:@" " modifierFlags:UIKeyModifierShift action:@selector(_arrowKey:)],
2823        
2824        [UIKeyCommand keyCommandWithInput:UIKeyInputPageDown modifierFlags:0 action:@selector(_arrowKey:)],
2825        [UIKeyCommand keyCommandWithInput:UIKeyInputPageDown modifierFlags:0 action:@selector(_arrowKey:)],
2826     ] retain];
2827
2828     static NSArray* editableKeyCommands = [@[
2829        [UIKeyCommand keyCommandWithInput:@"\t" modifierFlags:0 action:@selector(_nextAccessoryTab:)],
2830        [UIKeyCommand keyCommandWithInput:@"\t" modifierFlags:UIKeyModifierShift action:@selector(_prevAccessoryTab:)]
2831     ] retain];
2832     
2833     return (_page->editorState().isContentEditable) ? editableKeyCommands : nonEditableKeyCommands;
2834 }
2835
2836 - (void)_arrowKeyForWebView:(id)sender
2837 {
2838     UIKeyCommand* command = sender;
2839     [self handleKeyEvent:command._triggeringEvent];
2840 }
2841
2842 - (void)_nextAccessoryTab:(id)sender
2843 {
2844     [self accessoryTab:YES];
2845 }
2846
2847 - (void)_prevAccessoryTab:(id)sender
2848 {
2849     [self accessoryTab:NO];
2850 }
2851
2852 - (void)accessoryTab:(BOOL)isNext
2853 {
2854     [_inputPeripheral endEditing];
2855     _inputPeripheral = nil;
2856
2857     _didAccessoryTabInitiateFocus = YES; // Will be cleared in either -_displayFormNodeInputView or -cleanupInteraction.
2858     [self beginSelectionChange];
2859     RetainPtr<WKContentView> view = self;
2860     _page->focusNextAssistedNode(isNext, [view](WebKit::CallbackBase::Error) {
2861         [view endSelectionChange];
2862         [view reloadInputViews];
2863     });
2864
2865 }
2866
2867 - (void)_becomeFirstResponderWithSelectionMovingForward:(BOOL)selectingForward completionHandler:(void (^)(BOOL didBecomeFirstResponder))completionHandler
2868 {
2869     auto completionHandlerCopy = Block_copy(completionHandler);
2870     RetainPtr<WKContentView> view = self;
2871     _page->setInitialFocus(selectingForward, false, WebKit::WebKeyboardEvent(), [view, completionHandlerCopy](WebKit::CallbackBase::Error) {
2872         BOOL didBecomeFirstResponder = view->_assistedNodeInformation.elementType != InputType::None && [view becomeFirstResponder];
2873         completionHandlerCopy(didBecomeFirstResponder);
2874         Block_release(completionHandlerCopy);
2875     });
2876 }
2877
2878 - (WebCore::Color)_tapHighlightColorForFastClick:(BOOL)forFastClick
2879 {
2880     ASSERT(_showDebugTapHighlightsForFastClicking);
2881     return forFastClick ? WebCore::Color(0, 225, 0, 127) : WebCore::Color(225, 0, 0, 127);
2882 }
2883
2884 - (void)_setDoubleTapGesturesEnabled:(BOOL)enabled
2885 {
2886     if (enabled && ![_doubleTapGestureRecognizer isEnabled]) {
2887         // The first tap recognized after re-enabling double tap gestures will not wait for the
2888         // second tap before committing. To fix this, we use a new double tap gesture recognizer.
2889         [self removeGestureRecognizer:_doubleTapGestureRecognizer.get()];
2890         [_doubleTapGestureRecognizer setDelegate:nil];
2891         [self _createAndConfigureDoubleTapGestureRecognizer];
2892     }
2893
2894     if (_showDebugTapHighlightsForFastClicking && !enabled)
2895         _tapHighlightInformation.color = [self _tapHighlightColorForFastClick:YES];
2896
2897     [_doubleTapGestureRecognizer setEnabled:enabled];
2898     [_nonBlockingDoubleTapGestureRecognizer setEnabled:!enabled];
2899     [self _resetIsDoubleTapPending];
2900 }
2901
2902 - (void)accessoryAutoFill
2903 {
2904     id <_WKInputDelegate> inputDelegate = [_webView _inputDelegate];
2905     if ([inputDelegate respondsToSelector:@selector(_webView:accessoryViewCustomButtonTappedInFormInputSession:)])
2906         [inputDelegate _webView:_webView accessoryViewCustomButtonTappedInFormInputSession:_formInputSession.get()];
2907 }
2908
2909 - (void)accessoryClear
2910 {
2911     _page->setAssistedNodeValue(String());
2912 }
2913
2914 - (void)_updateAccessory
2915 {
2916     [_formAccessoryView setNextEnabled:_assistedNodeInformation.hasNextNode];
2917     [_formAccessoryView setPreviousEnabled:_assistedNodeInformation.hasPreviousNode];
2918
2919     if (UICurrentUserInterfaceIdiomIsPad())
2920         [_formAccessoryView setClearVisible:NO];
2921     else {
2922         switch (_assistedNodeInformation.elementType) {
2923         case InputType::Date:
2924         case InputType::Month:
2925         case InputType::DateTimeLocal:
2926         case InputType::Time:
2927             [_formAccessoryView setClearVisible:YES];
2928             break;
2929         default:
2930             [_formAccessoryView setClearVisible:NO];
2931             break;
2932         }
2933     }
2934
2935     // FIXME: hide or show the AutoFill button as needed.
2936 }
2937
2938 // Keyboard interaction
2939 // UITextInput protocol implementation
2940
2941 - (BOOL)_allowAnimatedUpdateSelectionRectViews
2942 {
2943     return NO;
2944 }
2945
2946 - (void)beginSelectionChange
2947 {
2948     [self.inputDelegate selectionWillChange:self];
2949 }
2950
2951 - (void)endSelectionChange
2952 {
2953     [self.inputDelegate selectionDidChange:self];
2954 }
2955     
2956 - (void)insertTextSuggestion:(UITextSuggestion *)textSuggestion
2957 {
2958     id <_WKInputDelegate> inputDelegate = [_webView _inputDelegate];
2959     if ([inputDelegate respondsToSelector:@selector(_webView:insertTextSuggestion:inInputSession:)])
2960         [inputDelegate _webView:_webView insertTextSuggestion:textSuggestion inInputSession:_formInputSession.get()];
2961 }
2962
2963 - (NSString *)textInRange:(UITextRange *)range
2964 {
2965     return nil;
2966 }
2967
2968 - (void)replaceRange:(UITextRange *)range withText:(NSString *)text
2969 {
2970 }
2971
2972 - (UITextRange *)selectedTextRange
2973 {
2974     if (_page->editorState().selectionIsNone)
2975         return nil;
2976     auto& postLayoutEditorStateData = _page->editorState().postLayoutData();
2977     FloatRect startRect = postLayoutEditorStateData.caretRectAtStart;
2978     FloatRect endRect = postLayoutEditorStateData.caretRectAtEnd;
2979     double inverseScale = [self inverseScale];
2980     // We want to keep the original caret width, while the height scales with
2981     // the content taking orientation into account.
2982     // We achieve this by scaling the width with the inverse
2983     // scale factor. This way, when it is converted from the content view
2984     // the width remains unchanged.
2985     if (startRect.width() < startRect.height())
2986         startRect.setWidth(startRect.width() * inverseScale);
2987     else
2988         startRect.setHeight(startRect.height() * inverseScale);
2989     if (endRect.width() < endRect.height()) {
2990         double delta = endRect.width();
2991         endRect.setWidth(endRect.width() * inverseScale);
2992         delta = endRect.width() - delta;
2993         endRect.move(delta, 0);
2994     } else {
2995         double delta = endRect.height();
2996         endRect.setHeight(endRect.height() * inverseScale);
2997         delta = endRect.height() - delta;
2998         endRect.move(0, delta);
2999     }
3000     return [WKTextRange textRangeWithState:_page->editorState().selectionIsNone
3001                                    isRange:_page->editorState().selectionIsRange
3002                                 isEditable:_page->editorState().isContentEditable
3003                                  startRect:startRect
3004                                    endRect:endRect
3005                             selectionRects:[self webSelectionRects]
3006                         selectedTextLength:postLayoutEditorStateData.selectedTextLength];
3007 }
3008
3009 - (CGRect)caretRectForPosition:(UITextPosition *)position
3010 {
3011     return ((WKTextPosition *)position).positionRect;
3012 }
3013
3014 - (NSArray *)selectionRectsForRange:(UITextRange *)range
3015 {
3016     return [WKTextSelectionRect textSelectionRectsWithWebRects:((WKTextRange *)range).selectionRects];
3017 }
3018
3019 - (void)setSelectedTextRange:(UITextRange *)range
3020 {
3021     if (_textSelectionAssistant && !range)
3022         [self clearSelection];
3023 }
3024
3025 - (BOOL)hasMarkedText
3026 {
3027     return [_markedText length];
3028 }
3029
3030 - (NSString *)markedText
3031 {
3032     return _markedText.get();
3033 }
3034
3035 - (UITextRange *)markedTextRange
3036 {
3037     return nil;
3038 }
3039
3040 - (NSDictionary *)markedTextStyle
3041 {
3042     return nil;
3043 }
3044
3045 - (void)setMarkedTextStyle:(NSDictionary *)styleDictionary
3046 {
3047 }
3048
3049 - (void)setMarkedText:(NSString *)markedText selectedRange:(NSRange)selectedRange
3050 {
3051     _markedText = markedText;
3052     _page->setCompositionAsync(markedText, Vector<WebCore::CompositionUnderline>(), selectedRange, EditingRange());
3053 }
3054
3055 - (void)unmarkText
3056 {
3057     _markedText = nil;
3058     _page->confirmCompositionAsync();
3059 }
3060
3061 - (UITextPosition *)beginningOfDocument
3062 {
3063     return nil;
3064 }
3065
3066 - (UITextPosition *)endOfDocument
3067 {
3068     return nil;
3069 }
3070
3071 - (UITextRange *)textRangeFromPosition:(UITextPosition *)fromPosition toPosition:(UITextPosition *)toPosition
3072 {
3073     return nil;
3074 }
3075
3076 - (UITextPosition *)positionFromPosition:(UITextPosition *)position offset:(NSInteger)offset
3077 {
3078     return nil;
3079 }
3080
3081 - (UITextPosition *)positionFromPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset
3082 {
3083     return nil;
3084 }
3085
3086 - (NSComparisonResult)comparePosition:(UITextPosition *)position toPosition:(UITextPosition *)other
3087 {
3088     return NSOrderedSame;
3089 }
3090
3091 - (NSInteger)offsetFromPosition:(UITextPosition *)from toPosition:(UITextPosition *)toPosition
3092 {
3093     return 0;
3094 }
3095
3096 - (id <UITextInputTokenizer>)tokenizer
3097 {
3098     return nil;
3099 }
3100
3101 - (UITextPosition *)positionWithinRange:(UITextRange *)range farthestInDirection:(UITextLayoutDirection)direction
3102 {
3103     return nil;
3104 }
3105
3106 - (UITextRange *)characterRangeByExtendingPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction
3107 {
3108     return nil;
3109 }
3110
3111 - (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition *)position inDirection:(UITextStorageDirection)direction
3112 {
3113     return UITextWritingDirectionLeftToRight;
3114 }
3115
3116 - (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection forRange:(UITextRange *)range
3117 {
3118 }
3119
3120 - (CGRect)firstRectForRange:(UITextRange *)range
3121 {
3122     return CGRectZero;
3123 }
3124
3125 /* Hit testing. */
3126 - (UITextPosition *)closestPositionToPoint:(CGPoint)point
3127 {
3128     return nil;
3129 }
3130
3131 - (UITextPosition *)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange *)range
3132 {
3133     return nil;
3134 }
3135
3136 - (UITextRange *)characterRangeAtPoint:(CGPoint)point
3137 {
3138     return nil;
3139 }
3140
3141 - (void)deleteBackward
3142 {
3143     _page->executeEditCommand(ASCIILiteral("deleteBackward"));
3144 }
3145
3146 // Inserts the given string, replacing any selected or marked text.
3147 - (void)insertText:(NSString *)aStringValue
3148 {
3149     _page->insertTextAsync(aStringValue, EditingRange());
3150 }
3151
3152 - (BOOL)hasText
3153 {
3154     return YES;
3155 }
3156
3157 // end of UITextInput protocol implementation
3158
3159 static UITextAutocapitalizationType toUITextAutocapitalize(AutocapitalizeType webkitType)
3160 {
3161     switch (webkitType) {
3162     case AutocapitalizeTypeDefault:
3163         return UITextAutocapitalizationTypeSentences;
3164     case AutocapitalizeTypeNone:
3165         return UITextAutocapitalizationTypeNone;
3166     case AutocapitalizeTypeWords:
3167         return UITextAutocapitalizationTypeWords;
3168     case AutocapitalizeTypeSentences:
3169         return UITextAutocapitalizationTypeSentences;
3170     case AutocapitalizeTypeAllCharacters:
3171         return UITextAutocapitalizationTypeAllCharacters;
3172     }
3173
3174     return UITextAutocapitalizationTypeSentences;
3175 }
3176
3177 static NSString *contentTypeFromFieldName(WebCore::AutofillFieldName fieldName)
3178 {
3179     switch (fieldName) {
3180     case WebCore::AutofillFieldName::Name:
3181         return UITextContentTypeName;
3182     case WebCore::AutofillFieldName::HonorificPrefix:
3183         return UITextContentTypeNamePrefix;
3184     case WebCore::AutofillFieldName::GivenName:
3185         return UITextContentTypeMiddleName;
3186     case WebCore::AutofillFieldName::AdditionalName:
3187         return UITextContentTypeMiddleName;
3188     case WebCore::AutofillFieldName::FamilyName:
3189         return UITextContentTypeFamilyName;
3190     case WebCore::AutofillFieldName::HonorificSuffix:
3191         return UITextContentTypeNameSuffix;
3192     case WebCore::AutofillFieldName::Nickname:
3193         return UITextContentTypeNickname;
3194     case WebCore::AutofillFieldName::OrganizationTitle:
3195         return UITextContentTypeJobTitle;
3196     case WebCore::AutofillFieldName::Organization:
3197         return UITextContentTypeOrganizationName;
3198     case WebCore::AutofillFieldName::StreetAddress:
3199         return UITextContentTypeFullStreetAddress;
3200     case WebCore::AutofillFieldName::AddressLine1:
3201         return UITextContentTypeStreetAddressLine1;
3202     case WebCore::AutofillFieldName::AddressLine2:
3203         return UITextContentTypeStreetAddressLine2;
3204     case WebCore::AutofillFieldName::AddressLevel3:
3205         return UITextContentTypeSublocality;
3206     case WebCore::AutofillFieldName::AddressLevel2:
3207         return UITextContentTypeAddressCity;
3208     case WebCore::AutofillFieldName::AddressLevel1:
3209         return UITextContentTypeAddressState;
3210     case WebCore::AutofillFieldName::CountryName:
3211         return UITextContentTypeCountryName;
3212     case WebCore::AutofillFieldName::PostalCode:
3213         return UITextContentTypePostalCode;
3214     case WebCore::AutofillFieldName::Tel:
3215         return UITextContentTypeTelephoneNumber;
3216     case WebCore::AutofillFieldName::Email:
3217         return UITextContentTypeEmailAddress;
3218     case WebCore::AutofillFieldName::URL:
3219         return UITextContentTypeURL;
3220     case WebCore::AutofillFieldName::None:
3221     case WebCore::AutofillFieldName::Username:
3222     case WebCore::AutofillFieldName::NewPassword:
3223     case WebCore::AutofillFieldName::CurrentPassword:
3224     case WebCore::AutofillFieldName::AddressLine3:
3225     case WebCore::AutofillFieldName::AddressLevel4:
3226     case WebCore::AutofillFieldName::Country:
3227     case WebCore::AutofillFieldName::CcName:
3228     case WebCore::AutofillFieldName::CcGivenName:
3229     case WebCore::AutofillFieldName::CcAdditionalName:
3230     case WebCore::AutofillFieldName::CcFamilyName:
3231     case WebCore::AutofillFieldName::CcNumber:
3232     case WebCore::AutofillFieldName::CcExp:
3233     case WebCore::AutofillFieldName::CcExpMonth:
3234     case WebCore::AutofillFieldName::CcExpYear:
3235     case WebCore::AutofillFieldName::CcCsc:
3236     case WebCore::AutofillFieldName::CcType:
3237     case WebCore::AutofillFieldName::TransactionCurrency:
3238     case WebCore::AutofillFieldName::TransactionAmount:
3239     case WebCore::AutofillFieldName::Language:
3240     case WebCore::AutofillFieldName::Bday:
3241     case WebCore::AutofillFieldName::BdayDay:
3242     case WebCore::AutofillFieldName::BdayMonth:
3243     case WebCore::AutofillFieldName::BdayYear:
3244     case WebCore::AutofillFieldName::Sex:
3245     case WebCore::AutofillFieldName::Photo:
3246     case WebCore::AutofillFieldName::TelCountryCode:
3247     case WebCore::AutofillFieldName::TelNational:
3248     case WebCore::AutofillFieldName::TelAreaCode:
3249     case WebCore::AutofillFieldName::TelLocal:
3250     case WebCore::AutofillFieldName::TelLocalPrefix:
3251     case WebCore::AutofillFieldName::TelLocalSuffix:
3252     case WebCore::AutofillFieldName::TelExtension:
3253     case WebCore::AutofillFieldName::Impp:
3254         break;
3255     };
3256
3257     return nil;
3258 }
3259
3260 // UITextInputPrivate protocol
3261 // Direct access to the (private) UITextInputTraits object.
3262 - (UITextInputTraits *)textInputTraits
3263 {
3264     if (!_traits)
3265         _traits = adoptNS([[UITextInputTraits alloc] init]);
3266
3267     [_traits setSecureTextEntry:_assistedNodeInformation.elementType == InputType::Password || [_formInputSession forceSecureTextEntry]];
3268     [_traits setShortcutConversionType:_assistedNodeInformation.elementType == InputType::Password ? UITextShortcutConversionTypeNo : UITextShortcutConversionTypeDefault];
3269
3270     if (!_assistedNodeInformation.formAction.isEmpty())
3271         [_traits setReturnKeyType:(_assistedNodeInformation.elementType == InputType::Search) ? UIReturnKeySearch : UIReturnKeyGo];
3272
3273     if (_assistedNodeInformation.elementType == InputType::Password || _assistedNodeInformation.elementType == InputType::Email || _assistedNodeInformation.elementType == InputType::URL || _assistedNodeInformation.formAction.contains("login")) {
3274         [_traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
3275         [_traits setAutocorrectionType:UITextAutocorrectionTypeNo];
3276     } else {
3277         [_traits setAutocapitalizationType:toUITextAutocapitalize(_assistedNodeInformation.autocapitalizeType)];
3278         [_traits setAutocorrectionType:_assistedNodeInformation.isAutocorrect ? UITextAutocorrectionTypeYes : UITextAutocorrectionTypeNo];
3279     }
3280
3281     switch (_assistedNodeInformation.elementType) {
3282     case InputType::Phone:
3283         [_traits setKeyboardType:UIKeyboardTypePhonePad];
3284         break;
3285     case InputType::URL:
3286         [_traits setKeyboardType:UIKeyboardTypeURL];
3287         break;
3288     case InputType::Email:
3289         [_traits setKeyboardType:UIKeyboardTypeEmailAddress];
3290         break;
3291     case InputType::Number:
3292         [_traits setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
3293         break;
3294     case InputType::NumberPad:
3295         [_traits setKeyboardType:UIKeyboardTypeNumberPad];
3296         break;
3297     default:
3298         [_traits setKeyboardType:UIKeyboardTypeDefault];
3299     }
3300
3301     [_traits setTextContentType:contentTypeFromFieldName(_assistedNodeInformation.autofillFieldName)];
3302
3303     return _traits.get();
3304 }
3305
3306 - (UITextInteractionAssistant *)interactionAssistant
3307 {
3308     return _textSelectionAssistant.get();
3309 }
3310
3311 - (UIWebSelectionAssistant *)webSelectionAssistant
3312 {
3313     return _webSelectionAssistant.get();
3314 }
3315
3316 - (id<UISelectionInteractionAssistant>)selectionInteractionAssistant
3317 {
3318     if ([_webSelectionAssistant conformsToProtocol:@protocol(UISelectionInteractionAssistant)])
3319         return (id<UISelectionInteractionAssistant>)_webSelectionAssistant.get();
3320     return nil;
3321 }
3322
3323 // NSRange support.  Would like to deprecate to the extent possible, although some support
3324 // (i.e. selectionRange) has shipped as API.
3325 - (NSRange)selectionRange
3326 {
3327     return NSMakeRange(NSNotFound, 0);
3328 }
3329
3330 - (CGRect)rectForNSRange:(NSRange)range
3331 {
3332     return CGRectZero;
3333 }
3334
3335 - (NSRange)_markedTextNSRange
3336 {
3337     return NSMakeRange(NSNotFound, 0);
3338 }
3339
3340 // DOM range support.
3341 - (DOMRange *)selectedDOMRange
3342 {
3343     return nil;
3344 }
3345
3346 - (void)setSelectedDOMRange:(DOMRange *)range affinityDownstream:(BOOL)affinityDownstream
3347 {
3348 }
3349
3350 // Modify text without starting a new undo grouping.
3351 - (void)replaceRangeWithTextWithoutClosingTyping:(UITextRange *)range replacementText:(NSString *)text
3352 {
3353 }
3354
3355 // Caret rect support.  Shouldn't be necessary, but firstRectForRange doesn't offer precisely
3356 // the same functionality.
3357 - (CGRect)rectContainingCaretSelection
3358 {
3359     return CGRectZero;
3360 }
3361
3362 // Web events.
3363 - (BOOL)requiresKeyEvents
3364 {
3365     return YES;
3366 }
3367
3368 - (void)_handleKeyUIEvent:(::UIEvent *)event
3369 {
3370     // We only want to handle key event from the hardware keyboard when we are
3371     // first responder and we are not interacting with editable content.
3372     if ([self isFirstResponder] && event._hidEvent && !_page->editorState().isContentEditable) {
3373         [self handleKeyEvent:event];
3374         return;
3375     }
3376
3377     [super _handleKeyUIEvent:event];
3378 }
3379
3380 - (void)handleKeyEvent:(::UIEvent *)event
3381 {
3382     // WebCore has already seen the event, no need for custom processing.
3383     if (event == _uiEventBeingResent)
3384         return;
3385
3386     WKWebEvent *webEvent = [[[WKWebEvent alloc] initWithKeyEventType:(event._isKeyDown) ? WebEventKeyDown : WebEventKeyUp
3387                                                            timeStamp:event.timestamp
3388                                                           characters:event._modifiedInput
3389                                          charactersIgnoringModifiers:event._unmodifiedInput
3390                                                            modifiers:event._modifierFlags
3391                                                          isRepeating:(event._inputFlags & kUIKeyboardInputRepeat)
3392                                                            withFlags:event._inputFlags
3393                                                              keyCode:0
3394                                                             isTabKey:[event._modifiedInput isEqualToString:@"\t"]
3395                                                         characterSet:WebEventCharacterSetUnicode] autorelease];
3396     webEvent.uiEvent = event;
3397     
3398     [self handleKeyWebEvent:webEvent];    
3399 }
3400
3401 - (void)handleKeyWebEvent:(::WebEvent *)theEvent
3402 {
3403     _page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent));
3404 }
3405
3406 - (void)handleKeyWebEvent:(::WebEvent *)theEvent withCompletionHandler:(void (^)(::WebEvent *theEvent, BOOL wasHandled))completionHandler
3407 {
3408     _keyWebEventHandler = [completionHandler copy];
3409     _page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent));
3410 }
3411
3412 - (void)_didHandleKeyEvent:(::WebEvent *)event eventWasHandled:(BOOL)eventWasHandled
3413 {
3414     if (_keyWebEventHandler) {
3415         _keyWebEventHandler(event, eventWasHandled);
3416         [_keyWebEventHandler release];
3417         _keyWebEventHandler = nil;
3418         return;
3419     }
3420         
3421     // If we aren't interacting with editable content, we still need to call [super _handleKeyUIEvent:]
3422     // so that keyboard repeat will work correctly. If we are interacting with editable content,
3423     // we already did so in _handleKeyUIEvent.
3424     if (eventWasHandled && _page->editorState().isContentEditable)
3425         return;
3426
3427     if (![event isKindOfClass:[WKWebEvent class]])
3428         return;
3429
3430     // Resending the event may destroy this WKContentView.
3431     RetainPtr<WKContentView> protector(self);
3432
3433     // We keep here the event when resending it to the application to distinguish
3434     // the case of a new event from one that has been already sent to WebCore.
3435     ASSERT(!_uiEventBeingResent);
3436     _uiEventBeingResent = [(WKWebEvent *)event uiEvent];
3437     [super _handleKeyUIEvent:_uiEventBeingResent.get()];
3438     _uiEventBeingResent = nil;
3439 }
3440
3441 - (std::optional<FloatPoint>)_scrollOffsetForEvent:(::WebEvent *)event
3442 {
3443     static const unsigned kWebSpaceKey = 0x20;
3444
3445     if (_page->editorState().isContentEditable)
3446         return std::nullopt;
3447
3448     NSString *charactersIgnoringModifiers = event.charactersIgnoringModifiers;
3449     if (!charactersIgnoringModifiers.length)
3450         return std::nullopt;
3451
3452     enum ScrollingIncrement { Document, Page, Line };
3453     enum ScrollingDirection { Up, Down, Left, Right };
3454
3455     auto computeOffset = ^(ScrollingIncrement increment, ScrollingDirection direction) {
3456         bool isHorizontal = (direction == Left || direction == Right);
3457
3458         CGFloat scrollDistance = ^ CGFloat {
3459             switch (increment) {
3460             case Document:
3461                 ASSERT(!isHorizontal);
3462                 return self.bounds.size.height;
3463             case Page:
3464                 ASSERT(!isHorizontal);
3465                 return Scrollbar::pageStep(_page->unobscuredContentRect().height(), self.bounds.size.height);
3466             case Line:
3467                 return Scrollbar::pixelsPerLineStep();
3468             }
3469             ASSERT_NOT_REACHED();
3470             return 0;
3471         }();
3472
3473         if (direction == Up || direction == Left)
3474             scrollDistance = -scrollDistance;
3475         
3476         return (isHorizontal ? FloatPoint(scrollDistance, 0) : FloatPoint(0, scrollDistance));
3477     };
3478
3479     if ([charactersIgnoringModifiers isEqualToString:UIKeyInputLeftArrow])
3480         return computeOffset(Line, Left);
3481     if ([charactersIgnoringModifiers isEqualToString:UIKeyInputRightArrow])
3482         return computeOffset(Line, Right);
3483
3484     ScrollingIncrement incrementForVerticalArrowKey = Line;
3485     if (event.modifierFlags & WebEventFlagMaskAlternate)
3486         incrementForVerticalArrowKey = Page;
3487     else if (event.modifierFlags & WebEventFlagMaskCommand)
3488         incrementForVerticalArrowKey = Document;
3489     if ([charactersIgnoringModifiers isEqualToString:UIKeyInputUpArrow])
3490         return computeOffset(incrementForVerticalArrowKey, Up);
3491     if ([charactersIgnoringModifiers isEqualToString:UIKeyInputDownArrow])
3492         return computeOffset(incrementForVerticalArrowKey, Down);
3493
3494     if ([charactersIgnoringModifiers isEqualToString:UIKeyInputPageDown])
3495         return computeOffset(Page, Down);
3496     if ([charactersIgnoringModifiers isEqualToString:UIKeyInputPageUp])
3497         return computeOffset(Page, Up);
3498
3499     if ([charactersIgnoringModifiers characterAtIndex:0] == kWebSpaceKey)
3500         return computeOffset(Page, (event.modifierFlags & WebEventFlagMaskShift) ? Up : Down);
3501
3502     return std::nullopt;
3503 }
3504
3505 - (BOOL)_interpretKeyEvent:(::WebEvent *)event isCharEvent:(BOOL)isCharEvent
3506 {
3507     static const unsigned kWebEnterKey = 0x0003;
3508     static const unsigned kWebBackspaceKey = 0x0008;
3509     static const unsigned kWebReturnKey = 0x000D;
3510     static const unsigned kWebDeleteKey = 0x007F;
3511     static const unsigned kWebDeleteForwardKey = 0xF728;
3512     static const unsigned kWebSpaceKey = 0x20;
3513
3514     BOOL contentEditable = _page->editorState().isContentEditable;
3515
3516     if (!contentEditable && event.isTabKey)
3517         return NO;
3518
3519     if (std::optional<FloatPoint> scrollOffset = [self _scrollOffsetForEvent:event]) {
3520         [_webView _scrollByContentOffset:*scrollOffset];
3521         return YES;
3522     }
3523
3524     UIKeyboardImpl *keyboard = [UIKeyboardImpl sharedInstance];
3525     NSString *characters = event.characters;
3526     
3527     if (!characters.length)
3528         return NO;
3529
3530     switch ([characters characterAtIndex:0]) {
3531     case kWebBackspaceKey:
3532     case kWebDeleteKey:
3533         if (contentEditable) {
3534             [keyboard deleteFromInputWithFlags:event.keyboardFlags];
3535             return YES;
3536         }
3537         break;
3538
3539     case kWebSpaceKey:
3540         if (contentEditable && isCharEvent) {
3541             [keyboard addInputString:event.characters withFlags:event.keyboardFlags withInputManagerHint:event.inputManagerHint];
3542             return YES;
3543         }
3544         break;
3545
3546     case kWebEnterKey:
3547     case kWebReturnKey:
3548         if (contentEditable && isCharEvent) {
3549             // Map \r from HW keyboard to \n to match the behavior of the soft keyboard.
3550             [keyboard addInputString:@"\n" withFlags:0];
3551             return YES;
3552         }
3553         break;
3554
3555     case kWebDeleteForwardKey:
3556         _page->executeEditCommand(ASCIILiteral("deleteForward"));
3557         return YES;
3558
3559     default:
3560         if (contentEditable && isCharEvent) {
3561             [keyboard addInputString:event.characters withFlags:event.keyboardFlags withInputManagerHint:event.inputManagerHint];
3562             return YES;
3563         }
3564         break;
3565     }
3566
3567     return NO;
3568 }
3569
3570 - (void)executeEditCommandWithCallback:(NSString *)commandName
3571 {
3572     [self beginSelectionChange];
3573     RetainPtr<WKContentView> view = self;
3574     _page->executeEditCommand(commandName, [view](WebKit::CallbackBase::Error) {
3575         [view endSelectionChange];
3576     });
3577 }
3578
3579 - (UITextInputArrowKeyHistory *)_moveUp:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3580 {
3581     [self executeEditCommandWithCallback:extending ? @"moveUpAndModifySelection" : @"moveUp"];
3582     return nil;
3583 }
3584
3585 - (UITextInputArrowKeyHistory *)_moveDown:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3586 {
3587     [self executeEditCommandWithCallback:extending ? @"moveDownAndModifySelection" : @"moveDown"];
3588     return nil;
3589 }
3590
3591 - (UITextInputArrowKeyHistory *)_moveLeft:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3592 {
3593     [self executeEditCommandWithCallback:extending? @"moveLeftAndModifySelection" : @"moveLeft"];
3594     return nil;
3595 }
3596
3597 - (UITextInputArrowKeyHistory *)_moveRight:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3598 {
3599     [self executeEditCommandWithCallback:extending ? @"moveRightAndModifySelection" : @"moveRight"];
3600     return nil;
3601 }
3602
3603 - (UITextInputArrowKeyHistory *)_moveToStartOfWord:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3604 {
3605     [self executeEditCommandWithCallback:extending ? @"moveWordBackwardAndModifySelection" : @"moveWordBackward"];
3606     return nil;
3607 }
3608
3609 - (UITextInputArrowKeyHistory *)_moveToStartOfParagraph:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3610 {
3611     [self executeEditCommandWithCallback:extending ? @"moveToBeginningOfParagraphAndModifySelection" : @"moveToBeginningOfParagraph"];
3612     return nil;
3613 }
3614
3615 - (UITextInputArrowKeyHistory *)_moveToStartOfLine:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3616 {
3617     [self executeEditCommandWithCallback:extending ? @"moveToBeginningOfLineAndModifySelection" : @"moveToBeginningOfLine"];
3618     return nil;
3619 }
3620
3621 - (UITextInputArrowKeyHistory *)_moveToStartOfDocument:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3622 {
3623     [self executeEditCommandWithCallback:extending ? @"moveToBeginningOfDocumentAndModifySelection" : @"moveToBeginningOfDocument"];
3624     return nil;
3625 }
3626
3627 - (UITextInputArrowKeyHistory *)_moveToEndOfWord:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3628 {
3629     [self executeEditCommandWithCallback:extending ? @"moveWordForwardAndModifySelection" : @"moveWordForward"];
3630     return nil;
3631 }
3632
3633 - (UITextInputArrowKeyHistory *)_moveToEndOfParagraph:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3634 {
3635     [self executeEditCommandWithCallback:extending ? @"moveToEndOfParagraphAndModifySelection" : @"moveToEndOfParagraph"];
3636     return nil;
3637 }
3638
3639 - (UITextInputArrowKeyHistory *)_moveToEndOfLine:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3640 {
3641     [self executeEditCommandWithCallback:extending ? @"moveToEndOfLineAndModifySelection" : @"moveToEndOfLine"];
3642     return nil;
3643 }
3644
3645 - (UITextInputArrowKeyHistory *)_moveToEndOfDocument:(BOOL)extending withHistory:(UITextInputArrowKeyHistory *)history
3646 {
3647     [self executeEditCommandWithCallback:extending ? @"moveToEndOfDocumentAndModifySelection" : @"moveToEndOfDocument"];
3648     return nil;
3649 }
3650
3651 // Sets a buffer to make room for autocorrection views
3652 - (void)setBottomBufferHeight:(CGFloat)bottomBuffer
3653 {
3654 }
3655
3656 - (UIView *)automaticallySelectedOverlay
3657 {
3658     return [self unscaledView];
3659 }
3660
3661 - (UITextGranularity)selectionGranularity
3662 {
3663     return UITextGranularityCharacter;
3664 }
3665
3666 // Should return an array of NSDictionary objects that key/value paries for the final text, correction identifier and
3667 // alternative selection counts using the keys defined at the top of this header.
3668 - (NSArray *)metadataDictionariesForDictationResults
3669 {
3670     return nil;
3671 }
3672
3673 // Returns the dictation result boundaries from position so that text that was not dictated can be excluded from logging.
3674 // If these are not implemented, no text will be logged.
3675 - (UITextPosition *)previousUnperturbedDictationResultBoundaryFromPosition:(UITextPosition *)position
3676 {
3677     return nil;
3678 }
3679
3680 - (UITextPosition *)nextUnperturbedDictationResultBoundaryFromPosition:(UITextPosition *)position
3681 {
3682     return nil;
3683 }
3684
3685 // The can all be (and have been) trivially implemented in terms of UITextInput.  Deprecate and remove.
3686 - (void)moveBackward:(unsigned)count
3687 {
3688 }
3689
3690 - (void)moveForward:(unsigned)count
3691 {
3692 }
3693
3694 - (unichar)characterBeforeCaretSelection
3695 {
3696     return 0;
3697 }
3698
3699 - (NSString *)wordContainingCaretSelection
3700 {
3701     return nil;
3702 }
3703
3704 - (DOMRange *)wordRangeContainingCaretSelection
3705 {
3706     return nil;
3707 }
3708
3709 - (void)setMarkedText:(NSString *)text
3710 {
3711 }
3712
3713 - (BOOL)hasContent
3714 {
3715     return _page->editorState().postLayoutData().hasContent;
3716 }
3717
3718 - (void)selectAll
3719 {
3720 }
3721
3722 - (UIColor *)textColorForCaretSelection
3723 {
3724     return [UIColor blackColor];
3725 }
3726
3727 - (UIFont *)fontForCaretSelection
3728 {
3729     CGFloat zoomScale = 1.0;    // FIXME: retrieve the actual document scale factor.
3730     CGFloat scaledSize = _autocorrectionData.fontSize;
3731     if (CGFAbs(zoomScale - 1.0) > FLT_EPSILON)
3732         scaledSize *= zoomScale;
3733     return [UIFont fontWithFamilyName:_autocorrectionData.fontName traits:(UIFontTrait)_autocorrectionData.fontTraits size:scaledSize];
3734 }
3735
3736 - (BOOL)hasSelection
3737 {
3738     return NO;
3739 }
3740
3741 - (BOOL)isPosition:(UITextPosition *)position atBoundary:(UITextGranularity)granularity inDirection:(UITextDirection)direction
3742 {
3743     return NO;
3744 }
3745
3746 - (UITextPosition *)positionFromPosition:(UITextPosition *)position toBoundary:(UITextGranularity)granularity inDirection:(UITextDirection)direction
3747 {
3748     return nil;
3749 }
3750
3751 - (BOOL)isPosition:(UITextPosition *)position withinTextUnit:(UITextGranularity)granularity inDirection:(UITextDirection)direction
3752 {
3753     return NO;
3754 }
3755
3756 - (UITextRange *)rangeEnclosingPosition:(UITextPosition *)position withGranularity:(UITextGranularity)granularity inDirection:(UITextDirection)direction
3757 {
3758     return nil;
3759 }
3760
3761 - (void)takeTraitsFrom:(UITextInputTraits *)traits
3762 {
3763     [[self textInputTraits] takeTraitsFrom:traits];
3764 }
3765
3766 // FIXME: I want to change the name of these functions, but I'm leaving it for now
3767 // to make it easier to look up the corresponding functions in UIKit.
3768
3769 - (void)_startAssistingKeyboard
3770 {
3771     [self useSelectionAssistantWithGranularity:WKSelectionGranularityCharacter];
3772     [self reloadInputViews];
3773 }
3774
3775 - (void)_stopAssistingKeyboard
3776 {
3777     [self useSelectionAssistantWithGranularity:_webView._selectionGranularity];
3778 }
3779
3780 - (const AssistedNodeInformation&)assistedNodeInformation
3781 {
3782     return _assistedNodeInformation;
3783 }
3784
3785 - (Vector<OptionItem>&)assistedNodeSelectOptions
3786 {
3787     return _assistedNodeInformation.selectOptions;
3788 }
3789
3790 - (UIWebFormAccessory *)formAccessoryView
3791 {
3792     [self _ensureFormAccessoryView];
3793     return _formAccessoryView.get();
3794 }
3795
3796 static bool isAssistableInputType(InputType type)
3797 {
3798     switch (type) {
3799     case InputType::ContentEditable:
3800     case InputType::Text:
3801     case InputType::Password:
3802     case InputType::TextArea:
3803     case InputType::Search:
3804     case InputType::Email:
3805     case InputType::URL:
3806     case InputType::Phone:
3807     case InputType::Number:
3808     case InputType::NumberPad:
3809     case InputType::Date:
3810     case InputType::DateTime:
3811     case InputType::DateTimeLocal:
3812     case InputType::Month:
3813     case InputType::Week:
3814     case InputType::Time:
3815     case InputType::Select:
3816         return true;
3817
3818     case InputType::None:
3819         return false;
3820     }
3821
3822     ASSERT_NOT_REACHED();
3823     return false;
3824 }
3825
3826 - (void)_startAssistingNode:(const AssistedNodeInformation&)information userIsInteracting:(BOOL)userIsInteracting blurPreviousNode:(BOOL)blurPreviousNode userObject:(NSObject <NSSecureCoding> *)userObject
3827 {
3828     _inputViewUpdateDeferrer = nullptr;
3829
3830     id <_WKInputDelegate> inputDelegate = [_webView _inputDelegate];
3831     RetainPtr<WKFocusedElementInfo> focusedElementInfo = adoptNS([[WKFocusedElementInfo alloc] initWithAssistedNodeInformation:information isUserInitiated:userIsInteracting]);
3832     BOOL shouldShowKeyboard;
3833
3834     if ([inputDelegate respondsToSelector:@selector(_webView:focusShouldStartInputSession:)])
3835         shouldShowKeyboard = [inputDelegate _webView:_webView focusShouldStartInputSession:focusedElementInfo.get()];
3836     else {
3837         // The default behavior is to allow node assistance if the user is interacting or the keyboard is already active.
3838         shouldShowKeyboard = userIsInteracting || _textSelectionAssistant;
3839 #if ENABLE(DATA_INTERACTION)
3840         shouldShowKeyboard |= _dataInteractionState.isPerformingOperation;
3841 #endif
3842     }
3843     if (!shouldShowKeyboard)
3844         return;
3845
3846     if (blurPreviousNode)
3847         [self _stopAssistingNode];
3848
3849     if (!isAssistableInputType(information.elementType))
3850         return;
3851
3852     // FIXME: We should remove this check when we manage to send StartAssistingNode from the WebProcess
3853     // only when it is truly time to show the keyboard.
3854     if (_assistedNodeInformation.elementType == information.elementType && _assistedNodeInformation.elementRect == information.elementRect)
3855         return;
3856
3857     BOOL editableChanged = [self setIsEditable:YES];
3858     _assistedNodeInformation = information;
3859     _inputPeripheral = nil;
3860     _traits = nil;
3861     if (![self isFirstResponder])
3862         [self becomeFirstResponder];
3863
3864     [self reloadInputViews];
3865     
3866     switch (information.elementType) {
3867     case InputType::Select:
3868     case InputType::DateTimeLocal:
3869     case InputType::Time:
3870     case InputType::Month:
3871     case InputType::Date:
3872         break;
3873     default:
3874         [self _startAssistingKeyboard];
3875         break;
3876     }
3877     
3878     // The custom fixed position rect behavior is affected by -isAssistingNode, so if that changes we need to recompute rects.
3879     if (editableChanged)
3880         [_webView _scheduleVisibleContentRectUpdate];
3881     
3882     [self _displayFormNodeInputView];
3883
3884     // _inputPeripheral has been initialized in inputView called by reloadInputViews.
3885     [_inputPeripheral beginEditing];
3886
3887     if ([inputDelegate respondsToSelector:@selector(_webView:didStartInputSession:)]) {
3888         _formInputSession = adoptNS([[WKFormInputSession alloc] initWithContentView:self focusedElementInfo:focusedElementInfo.get() userObject:userObject]);
3889         [inputDelegate _webView:_webView didStartInputSession:_formInputSession.get()];
3890     }
3891     
3892     [_webView didStartFormControlInteraction];
3893 }
3894
3895 - (void)_stopAssistingNode
3896 {
3897     [_formInputSession invalidate];
3898     _formInputSession = nil;
3899
3900     BOOL editableChanged = [self setIsEditable:NO];
3901
3902     _assistedNodeInformation.elementType = InputType::None;
3903     _inputPeripheral = nil;
3904
3905     [self _stopAssistingKeyboard];
3906     [_formAccessoryView hideAutoFillButton];
3907     [self reloadInputViews];
3908     [self _updateAccessory];
3909     // The name is misleading, but this actually clears the selection views and removes any selection.
3910     [_webSelectionAssistant resignedFirstResponder];
3911
3912     // The custom fixed position rect behavior is affected by -isAssistingNode, so if that changes we need to recompute rects.
3913     if (editableChanged)
3914         [_webView _scheduleVisibleContentRectUpdate];
3915
3916     [_webView didEndFormControlInteraction];
3917 }
3918
3919 - (void)_selectionChanged
3920 {
3921     _selectionNeedsUpdate = YES;
3922     // If we are changing the selection with a gesture there is no need
3923     // to wait to paint the selection.
3924     if (_usingGestureForSelection)
3925         [self _updateChangedSelection];
3926 }
3927
3928 - (void)selectWordForReplacement
3929 {