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