REGRESSION (r238635): Dragging a text selection within WKWebView causes the selection...
[WebKit-https.git] / Tools / TestWebKitAPI / ios / DragAndDropSimulatorIOS.mm
1 /*
2  * Copyright (C) 2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "DragAndDropSimulator.h"
28
29 #if ENABLE(DRAG_SUPPORT) && PLATFORM(IOS_FAMILY) && WK_API_ENABLED
30
31 #import "InstanceMethodSwizzler.h"
32 #import "PlatformUtilities.h"
33 #import "UIKitSPI.h"
34
35 #import <UIKit/UIDragInteraction.h>
36 #import <UIKit/UIDragItem.h>
37 #import <UIKit/UIInteraction.h>
38 #import <WebKit/WKWebViewPrivate.h>
39 #import <WebKit/_WKFocusedElementInfo.h>
40 #import <WebKit/_WKFormInputSession.h>
41 #import <wtf/RetainPtr.h>
42 #import <wtf/SoftLinking.h>
43
44 SOFT_LINK_FRAMEWORK(UIKit)
45 SOFT_LINK(UIKit, UIApplicationInstantiateSingleton, void, (Class singletonClass), (singletonClass))
46
47 using namespace TestWebKitAPI;
48
49 @implementation WKWebView (DragAndDropTesting)
50
51 - (UIView *)_dragDropInteractionView
52 {
53     return [self valueForKey:@"_currentContentView"];
54 }
55
56 - (id <UIDropInteractionDelegate>)dropInteractionDelegate
57 {
58     return (id <UIDropInteractionDelegate>)self._dragDropInteractionView;
59 }
60
61 - (id <UIDragInteractionDelegate>)dragInteractionDelegate
62 {
63     return (id <UIDragInteractionDelegate>)self._dragDropInteractionView;
64 }
65
66 - (UIDropInteraction *)dropInteraction
67 {
68     UIView *interactionView = self._dragDropInteractionView;
69     for (id <UIInteraction> interaction in interactionView.interactions) {
70         if ([interaction isKindOfClass:[UIDropInteraction class]])
71             return (UIDropInteraction *)interaction;
72     }
73     return nil;
74 }
75
76 - (UIDragInteraction *)dragInteraction
77 {
78     UIView *interactionView = self._dragDropInteractionView;
79     for (id <UIInteraction> interaction in interactionView.interactions) {
80         if ([interaction isKindOfClass:[UIDragInteraction class]])
81             return (UIDragInteraction *)interaction;
82     }
83     return nil;
84 }
85
86 @end
87
88 @implementation MockDragDropSession
89
90 - (instancetype)initWithItems:(NSArray <UIDragItem *>*)items location:(CGPoint)locationInWindow window:(UIWindow *)window allowMove:(BOOL)allowMove
91 {
92     if (self = [super init]) {
93         _mockItems = items;
94         _mockLocationInWindow = locationInWindow;
95         _window = window;
96         _allowMove = allowMove;
97     }
98     return self;
99 }
100
101 - (BOOL)allowsMoveOperation
102 {
103     return _allowMove;
104 }
105
106 - (BOOL)isRestrictedToDraggingApplication
107 {
108     return NO;
109 }
110
111 - (BOOL)hasItemsConformingToTypeIdentifiers:(NSArray<NSString *> *)typeIdentifiers
112 {
113     for (NSString *typeIdentifier in typeIdentifiers) {
114         BOOL hasItemConformingToType = NO;
115         for (UIDragItem *item in self.items)
116             hasItemConformingToType |= [[item.itemProvider registeredTypeIdentifiers] containsObject:typeIdentifier];
117         if (!hasItemConformingToType)
118             return NO;
119     }
120     return YES;
121 }
122
123 - (BOOL)canLoadObjectsOfClass:(Class<NSItemProviderReading>)aClass
124 {
125     for (UIDragItem *item in self.items) {
126         if ([item.itemProvider canLoadObjectOfClass:aClass])
127             return YES;
128     }
129     return NO;
130 }
131
132 - (BOOL)canLoadObjectsOfClasses:(NSArray<Class<NSItemProviderReading>> *)classes
133 {
134     for (Class<NSItemProviderReading> aClass in classes) {
135         BOOL canLoad = NO;
136         for (UIDragItem *item in self.items)
137             canLoad |= [item.itemProvider canLoadObjectOfClass:aClass];
138         if (!canLoad)
139             return NO;
140     }
141     return YES;
142 }
143
144 - (NSArray<UIDragItem *> *)items
145 {
146     return _mockItems.get();
147 }
148
149 - (void)setItems:(NSArray<UIDragItem *> *)items
150 {
151     _mockItems = items;
152 }
153
154 - (void)addItems:(NSArray<UIDragItem *> *)items
155 {
156     if (![items count])
157         return;
158
159     if (![_mockItems count])
160         _mockItems = items;
161     else
162         _mockItems = [_mockItems arrayByAddingObjectsFromArray:items];
163 }
164
165 - (CGPoint)locationInView:(UIView *)view
166 {
167     return [_window convertPoint:_mockLocationInWindow toView:view];
168 }
169
170 @end
171
172 @implementation MockDropSession
173
174 - (instancetype)initWithProviders:(NSArray<NSItemProvider *> *)providers location:(CGPoint)locationInWindow window:(UIWindow *)window allowMove:(BOOL)allowMove
175 {
176     auto items = adoptNS([[NSMutableArray alloc] init]);
177     for (NSItemProvider *itemProvider in providers)
178         [items addObject:[[[UIDragItem alloc] initWithItemProvider:itemProvider] autorelease]];
179
180     return [super initWithItems:items.get() location:locationInWindow window:window allowMove:allowMove];
181 }
182
183 - (BOOL)isLocal
184 {
185     return YES;
186 }
187
188 - (NSProgress *)progress
189 {
190     return [NSProgress discreteProgressWithTotalUnitCount:100];
191 }
192
193 - (void)setProgressIndicatorStyle:(UIDropSessionProgressIndicatorStyle)progressIndicatorStyle
194 {
195 }
196
197 - (UIDropSessionProgressIndicatorStyle)progressIndicatorStyle
198 {
199     return UIDropSessionProgressIndicatorStyleNone;
200 }
201
202 - (NSUInteger)operationMask
203 {
204     return 0;
205 }
206
207 - (id <UIDragSession>)localDragSession
208 {
209     return nil;
210 }
211
212 - (BOOL)hasItemsConformingToTypeIdentifier:(NSString *)typeIdentifier
213 {
214     ASSERT_NOT_REACHED();
215     return NO;
216 }
217
218 - (BOOL)canCreateItemsOfClass:(Class<NSItemProviderReading>)aClass
219 {
220     ASSERT_NOT_REACHED();
221     return NO;
222 }
223
224 - (NSProgress *)loadObjectsOfClass:(Class<NSItemProviderReading>)aClass completion:(void(^)(NSArray<__kindof id <NSItemProviderReading>> *objects))completion
225 {
226     ASSERT_NOT_REACHED();
227     return nil;
228 }
229
230 @end
231
232 @implementation MockDragSession {
233     RetainPtr<id> _localContext;
234 }
235
236 - (instancetype)initWithWindow:(UIWindow *)window allowMove:(BOOL)allowMove
237 {
238     return [super initWithItems:@[ ] location:CGPointZero window:window allowMove:allowMove];
239 }
240
241 - (NSUInteger)localOperationMask
242 {
243     ASSERT_NOT_REACHED();
244     return 0;
245 }
246
247 - (NSUInteger)externalOperationMask
248 {
249     ASSERT_NOT_REACHED();
250     return 0;
251 }
252
253 - (id)session
254 {
255     return nil;
256 }
257
258 - (id)localContext
259 {
260     return _localContext.get();
261 }
262
263 - (void)setLocalContext:(id)localContext
264 {
265     _localContext = localContext;
266 }
267
268 @end
269
270 static double progressIncrementStep = 0.033;
271 static double progressTimeStep = 0.016;
272 static NSString *TestWebKitAPISimulateCancelAllTouchesNotificationName = @"TestWebKitAPISimulateCancelAllTouchesNotificationName";
273
274 static NSArray *dragAndDropEventNames()
275 {
276     static NSArray *eventNames = nil;
277     static dispatch_once_t onceToken;
278     dispatch_once(&onceToken, ^() {
279         eventNames = @[ @"dragenter", @"dragover", @"drop", @"dragleave", @"dragstart" ];
280     });
281     return eventNames;
282 }
283
284 @interface DragAndDropSimulatorApplication : UIApplication
285 @end
286
287 @implementation DragAndDropSimulatorApplication
288 - (void)_cancelAllTouches
289 {
290     [[NSNotificationCenter defaultCenter] postNotificationName:TestWebKitAPISimulateCancelAllTouchesNotificationName object:nil];
291 }
292 @end
293
294 @implementation DragAndDropSimulator {
295     RetainPtr<TestWKWebView> _webView;
296     RetainPtr<MockDragSession> _dragSession;
297     RetainPtr<MockDropSession> _dropSession;
298     RetainPtr<NSMutableArray> _observedEventNames;
299     RetainPtr<NSArray> _externalItemProviders;
300     RetainPtr<NSArray *> _sourceItemProviders;
301     RetainPtr<NSArray *> _finalSelectionRects;
302     CGPoint _startLocation;
303     CGPoint _endLocation;
304     CGRect _lastKnownDragCaretRect;
305
306     RetainPtr<NSMutableDictionary<NSNumber *, NSValue *>>_remainingAdditionalItemRequestLocationsByProgress;
307     RetainPtr<NSMutableArray<NSValue *>>_queuedAdditionalItemRequestLocations;
308     RetainPtr<NSMutableArray<UITargetedDragPreview *>> _liftPreviews;
309
310     RetainPtr<NSMutableArray<_WKAttachment *>> _insertedAttachments;
311     RetainPtr<NSMutableArray<_WKAttachment *>> _removedAttachments;
312
313     bool _hasStartedInputSession;
314     double _currentProgress;
315     bool _isDoneWithCurrentRun;
316     DragAndDropPhase _phase;
317
318     BOOL _suppressedSelectionCommandsDuringDrop;
319     RetainPtr<UIDropProposal> _currentDropProposal;
320 }
321
322 - (instancetype)initWithWebViewFrame:(CGRect)frame
323 {
324     return [self initWithWebViewFrame:frame configuration:nil];
325 }
326
327 - (instancetype)initWithWebViewFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
328 {
329     if (configuration)
330         return [self initWithWebView:[[[TestWKWebView alloc] initWithFrame:frame configuration:configuration] autorelease]];
331
332     return [self initWithWebView:[[[TestWKWebView alloc] initWithFrame:frame] autorelease]];
333 }
334
335 - (instancetype)initWithWebView:(TestWKWebView *)webView
336 {
337     if (self = [super init]) {
338         _webView = webView;
339         _shouldEnsureUIApplication = NO;
340         _shouldAllowMoveOperation = YES;
341         [_webView setUIDelegate:self];
342         [_webView _setInputDelegate:self];
343     }
344     return self;
345 }
346
347 - (void)dealloc
348 {
349     if ([_webView UIDelegate] == self)
350         [_webView setUIDelegate:nil];
351
352     if ([_webView _inputDelegate] == self)
353         [_webView _setInputDelegate:nil];
354
355     [super dealloc];
356 }
357
358 - (void)_resetSimulatedState
359 {
360     _suppressedSelectionCommandsDuringDrop = NO;
361     _phase = DragAndDropPhaseBeginning;
362     _currentProgress = 0;
363     _isDoneWithCurrentRun = false;
364     _observedEventNames = adoptNS([[NSMutableArray alloc] init]);
365     _insertedAttachments = adoptNS([[NSMutableArray alloc] init]);
366     _removedAttachments = adoptNS([[NSMutableArray alloc] init]);
367     _finalSelectionRects = @[ ];
368     _dragSession = nil;
369     _dropSession = nil;
370     _currentDropProposal = nil;
371     _lastKnownDragCaretRect = CGRectZero;
372     _remainingAdditionalItemRequestLocationsByProgress = nil;
373     _queuedAdditionalItemRequestLocations = adoptNS([[NSMutableArray alloc] init]);
374     _liftPreviews = adoptNS([[NSMutableArray alloc] init]);
375     _hasStartedInputSession = false;
376 }
377
378 - (NSArray *)observedEventNames
379 {
380     return _observedEventNames.get();
381 }
382
383 - (void)simulateAllTouchesCanceled:(NSNotification *)notification
384 {
385     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_advanceProgress) object:nil];
386     _phase = DragAndDropPhaseCancelled;
387     _currentProgress = 1;
388     _isDoneWithCurrentRun = true;
389     if (_dragSession)
390         [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] session:_dragSession.get() didEndWithOperation:UIDropOperationCancel];
391 }
392
393 - (void)runFrom:(CGPoint)startLocation to:(CGPoint)endLocation
394 {
395     [self runFrom:startLocation to:endLocation additionalItemRequestLocations:nil];
396 }
397
398 - (void)runFrom:(CGPoint)startLocation to:(CGPoint)endLocation additionalItemRequestLocations:(ProgressToCGPointValueMap)additionalItemRequestLocations
399 {
400     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
401     [defaultCenter addObserver:self selector:@selector(simulateAllTouchesCanceled:) name:TestWebKitAPISimulateCancelAllTouchesNotificationName object:nil];
402
403     if (_shouldEnsureUIApplication)
404         UIApplicationInstantiateSingleton([DragAndDropSimulatorApplication class]);
405
406     [self _resetSimulatedState];
407
408     if (additionalItemRequestLocations)
409         _remainingAdditionalItemRequestLocationsByProgress = adoptNS([additionalItemRequestLocations mutableCopy]);
410
411     for (NSString *eventName in dragAndDropEventNames()) {
412         [_webView performAfterReceivingMessage:eventName action:[strongSelf = retainPtr(self), name = retainPtr(eventName)] {
413             [strongSelf->_observedEventNames addObject:name.get()];
414         }];
415     }
416
417     _startLocation = startLocation;
418     _endLocation = endLocation;
419
420     if (self.externalItemProviders.count) {
421         _dropSession = adoptNS([[MockDropSession alloc] initWithProviders:self.externalItemProviders location:_startLocation window:[_webView window] allowMove:self.shouldAllowMoveOperation]);
422         _phase = DragAndDropPhaseBegan;
423         [self _advanceProgress];
424     } else {
425         _dragSession = adoptNS([[MockDragSession alloc] initWithWindow:[_webView window] allowMove:self.shouldAllowMoveOperation]);
426         [_dragSession setMockLocationInWindow:_startLocation];
427         [(id <UIDragInteractionDelegate_ForWebKitOnly>)[_webView dragInteractionDelegate] _dragInteraction:[_webView dragInteraction] prepareForSession:_dragSession.get() completion:[strongSelf = retainPtr(self)] {
428             if (strongSelf->_phase == DragAndDropPhaseCancelled)
429                 return;
430
431             strongSelf->_phase = DragAndDropPhaseBeginning;
432             [strongSelf _advanceProgress];
433         }];
434     }
435
436     Util::run(&_isDoneWithCurrentRun);
437     [_webView clearMessageHandlers:dragAndDropEventNames()];
438     _finalSelectionRects = [_webView selectionRectsAfterPresentationUpdate];
439
440     [defaultCenter removeObserver:self];
441 }
442
443 - (NSArray *)finalSelectionRects
444 {
445     return _finalSelectionRects.get();
446 }
447
448 - (void)_concludeDropAndPerformOperationIfNecessary
449 {
450     _lastKnownDragCaretRect = [_webView _dragCaretRect];
451     auto operation = [_currentDropProposal operation];
452     if (operation != UIDropOperationCancel && operation != UIDropOperationForbidden) {
453         [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] performDrop:_dropSession.get()];
454         _phase = DragAndDropPhasePerformingDrop;
455     } else {
456         _isDoneWithCurrentRun = YES;
457         _phase = DragAndDropPhaseCancelled;
458     }
459
460     [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidEnd:_dropSession.get()];
461
462     if (_dragSession) {
463         auto delegate = [_webView dragInteractionDelegate];
464         [delegate dragInteraction:[_webView dragInteraction] session:_dragSession.get() didEndWithOperation:operation];
465         if ([delegate respondsToSelector:@selector(_clearToken:)])
466             [(id <UITextInputMultiDocument>)delegate _clearToken:nil];
467         [_webView becomeFirstResponder];
468     }
469 }
470
471 - (void)_enqueuePendingAdditionalItemRequestLocations
472 {
473     NSMutableArray *progressValuesToRemove = [NSMutableArray array];
474     for (NSNumber *progressValue in _remainingAdditionalItemRequestLocationsByProgress.get()) {
475         double progress = progressValue.doubleValue;
476         if (progress > _currentProgress)
477             continue;
478         [progressValuesToRemove addObject:progressValue];
479         [_queuedAdditionalItemRequestLocations addObject:[_remainingAdditionalItemRequestLocationsByProgress objectForKey:progressValue]];
480     }
481
482     for (NSNumber *progressToRemove in progressValuesToRemove)
483         [_remainingAdditionalItemRequestLocationsByProgress removeObjectForKey:progressToRemove];
484 }
485
486 - (BOOL)_sendQueuedAdditionalItemRequest
487 {
488     if (![_queuedAdditionalItemRequestLocations count])
489         return NO;
490
491     RetainPtr<NSValue> requestLocationValue = [_queuedAdditionalItemRequestLocations objectAtIndex:0];
492     [_queuedAdditionalItemRequestLocations removeObjectAtIndex:0];
493
494     auto requestLocation = [[_webView window] convertPoint:[requestLocationValue CGPointValue] toView:_webView.get()];
495     [(id <UIDragInteractionDelegate_Proposed_SPI_33146803>)[_webView dragInteractionDelegate] _dragInteraction:[_webView dragInteraction] itemsForAddingToSession:_dragSession.get() withTouchAtPoint:requestLocation completion:[dragSession = _dragSession, dropSession = _dropSession] (NSArray *items) {
496         [dragSession addItems:items];
497         [dropSession addItems:items];
498     }];
499     return YES;
500 }
501
502 - (void)_advanceProgress
503 {
504     [self _enqueuePendingAdditionalItemRequestLocations];
505     if ([self _sendQueuedAdditionalItemRequest]) {
506         [self _scheduleAdvanceProgress];
507         return;
508     }
509
510     _lastKnownDragCaretRect = [_webView _dragCaretRect];
511     _currentProgress += progressIncrementStep;
512     CGPoint locationInWindow = self._currentLocation;
513     [_dragSession setMockLocationInWindow:locationInWindow];
514     [_dropSession setMockLocationInWindow:locationInWindow];
515
516     if (_currentProgress >= 1) {
517         _currentProgress = 1;
518         [self _concludeDropAndPerformOperationIfNecessary];
519         return;
520     }
521
522     switch (_phase) {
523     case DragAndDropPhaseBeginning: {
524         NSMutableArray<NSItemProvider *> *itemProviders = [NSMutableArray array];
525         NSArray *items = [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] itemsForBeginningSession:_dragSession.get()];
526         if (!items.count) {
527             _phase = DragAndDropPhaseCancelled;
528             _currentProgress = 1;
529             _isDoneWithCurrentRun = true;
530             return;
531         }
532
533         for (UIDragItem *item in items) {
534             [itemProviders addObject:item.itemProvider];
535             UITargetedDragPreview *liftPreview = [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] previewForLiftingItem:item session:_dragSession.get()];
536             EXPECT_TRUE(!!liftPreview);
537             if (liftPreview)
538                 [_liftPreviews addObject:liftPreview];
539         }
540
541         _dropSession = adoptNS([[MockDropSession alloc] initWithProviders:itemProviders location:self._currentLocation window:[_webView window] allowMove:self.shouldAllowMoveOperation]);
542         [_dragSession setItems:items];
543         _sourceItemProviders = itemProviders;
544         if (self.showCustomActionSheetBlock) {
545             // Defer progress until the custom action sheet is dismissed.
546             auto startLocationInView = [[_webView window] convertPoint:_startLocation toView:_webView.get()];
547             [_webView _simulateLongPressActionAtLocation:startLocationInView];
548             return;
549         }
550
551         auto delegate = [_webView dragInteractionDelegate];
552         if ([delegate respondsToSelector:@selector(_preserveFocusWithToken:destructively:)])
553             [(id <UITextInputMultiDocument>)delegate _preserveFocusWithToken:nil destructively:NO];
554
555         [_webView resignFirstResponder];
556
557         [delegate dragInteraction:[_webView dragInteraction] sessionWillBegin:_dragSession.get()];
558
559         RetainPtr<WKWebView> retainedWebView = _webView;
560         dispatch_async(dispatch_get_main_queue(), ^() {
561             [retainedWebView resignFirstResponder];
562         });
563
564         _phase = DragAndDropPhaseBegan;
565         break;
566     }
567     case DragAndDropPhaseBegan:
568         [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidEnter:_dropSession.get()];
569         _phase = DragAndDropPhaseEntered;
570         break;
571     case DragAndDropPhaseEntered: {
572         _currentDropProposal = [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidUpdate:_dropSession.get()];
573         if (![self shouldAllowMoveOperation] && [_currentDropProposal operation] == UIDropOperationMove)
574             _currentDropProposal = adoptNS([[UIDropProposal alloc] initWithDropOperation:UIDropOperationCancel]);
575         break;
576     }
577     default:
578         break;
579     }
580
581     [self _scheduleAdvanceProgress];
582 }
583
584 - (void)clearExternalDragInformation
585 {
586     _externalItemProviders = nil;
587 }
588
589 - (CGPoint)_currentLocation
590 {
591     CGFloat distanceX = _endLocation.x - _startLocation.x;
592     CGFloat distanceY = _endLocation.y - _startLocation.y;
593     return CGPointMake(_startLocation.x + _currentProgress * distanceX, _startLocation.y + _currentProgress * distanceY);
594 }
595
596 - (void)_scheduleAdvanceProgress
597 {
598     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_advanceProgress) object:nil];
599     [self performSelector:@selector(_advanceProgress) withObject:nil afterDelay:progressTimeStep];
600 }
601
602 - (NSArray *)sourceItemProviders
603 {
604     return _sourceItemProviders.get();
605 }
606
607 - (NSArray *)externalItemProviders
608 {
609     return _externalItemProviders.get();
610 }
611
612 - (void)setExternalItemProviders:(NSArray *)externalItemProviders
613 {
614     _externalItemProviders = adoptNS([externalItemProviders copy]);
615 }
616
617 - (DragAndDropPhase)phase
618 {
619     return _phase;
620 }
621
622 - (NSArray<UITargetedDragPreview *> *)liftPreviews
623 {
624     return _liftPreviews.get();
625 }
626
627 - (CGRect)lastKnownDragCaretRect
628 {
629     return _lastKnownDragCaretRect;
630 }
631
632 - (void)ensureInputSession
633 {
634     Util::run(&_hasStartedInputSession);
635 }
636
637 - (NSArray<_WKAttachment *> *)insertedAttachments
638 {
639     return _insertedAttachments.get();
640 }
641
642 - (NSArray<_WKAttachment *> *)removedAttachments
643 {
644     return _removedAttachments.get();
645 }
646
647 - (void)endDataTransfer
648 {
649     [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] sessionDidTransferItems:_dragSession.get()];
650 }
651
652 - (TestWKWebView *)webView
653 {
654     return _webView.get();
655 }
656
657 #pragma mark - WKUIDelegatePrivate
658
659 - (void)_webView:(WKWebView *)webView dataInteractionOperationWasHandled:(BOOL)handled forSession:(id)session itemProviders:(NSArray<NSItemProvider *> *)itemProviders
660 {
661     _suppressedSelectionCommandsDuringDrop = [_webView textInputContentView]._shouldSuppressSelectionCommands;
662     _isDoneWithCurrentRun = true;
663
664     if (self.dropCompletionBlock)
665         self.dropCompletionBlock(handled, itemProviders);
666 }
667
668 - (NSUInteger)_webView:(WKWebView *)webView willUpdateDataInteractionOperationToOperation:(NSUInteger)operation forSession:(id)session
669 {
670     return self.overrideDragUpdateBlock ? self.overrideDragUpdateBlock(operation, session) : operation;
671 }
672
673 - (NSArray *)_webView:(WKWebView *)webView adjustedDataInteractionItemProvidersForItemProvider:(NSItemProvider *)itemProvider representingObjects:(NSArray *)representingObjects additionalData:(NSDictionary *)additionalData
674 {
675     return self.convertItemProvidersBlock ? self.convertItemProvidersBlock(itemProvider, representingObjects, additionalData) : @[ itemProvider ];
676 }
677
678 - (BOOL)_webView:(WKWebView *)webView showCustomSheetForElement:(_WKActivatedElementInfo *)element
679 {
680     if (!self.showCustomActionSheetBlock)
681         return NO;
682
683     dispatch_async(dispatch_get_main_queue(), [strongSelf = retainPtr(self)] {
684         [[strongSelf->_webView dragInteractionDelegate] dragInteraction:[strongSelf->_webView dragInteraction] sessionWillBegin:strongSelf->_dragSession.get()];
685         strongSelf->_phase = DragAndDropPhaseBegan;
686         [strongSelf _scheduleAdvanceProgress];
687     });
688
689     return self.showCustomActionSheetBlock(element);
690 }
691
692 - (NSArray<UIDragItem *> *)_webView:(WKWebView *)webView willPerformDropWithSession:(id <UIDropSession>)session
693 {
694     return self.overridePerformDropBlock ? self.overridePerformDropBlock(session) : session.items;
695 }
696
697 - (void)_webView:(WKWebView *)webView didInsertAttachment:(_WKAttachment *)attachment withSource:(NSString *)source
698 {
699     [_insertedAttachments addObject:attachment];
700 }
701
702 - (void)_webView:(WKWebView *)webView didRemoveAttachment:(_WKAttachment *)attachment
703 {
704     [_removedAttachments addObject:attachment];
705 }
706
707 #pragma mark - _WKInputDelegate
708
709 - (BOOL)_webView:(WKWebView *)webView focusShouldStartInputSession:(id <_WKFocusedElementInfo>)info
710 {
711     return _allowsFocusToStartInputSession;
712 }
713
714 - (void)_webView:(WKWebView *)webView didStartInputSession:(id <_WKFormInputSession>)inputSession
715 {
716     _hasStartedInputSession = true;
717 }
718
719 @end
720
721 #endif // ENABLE(DRAG_SUPPORT) && PLATFORM(IOS_FAMILY) && WK_API_ENABLED