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