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