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