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