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