[iOS] Do not allow starting selection drags when selection views are not visible
[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)
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> _lastKnownDropProposal;
320
321     BlockPtr<BOOL(_WKActivatedElementInfo *)> _showCustomActionSheetBlock;
322     BlockPtr<NSArray *(NSItemProvider *, NSArray *, NSDictionary *)> _convertItemProvidersBlock;
323     BlockPtr<NSArray *(id <UIDropSession>)> _overridePerformDropBlock;
324     BlockPtr<UIDropOperation(UIDropOperation, id)> _overrideDragUpdateBlock;
325     BlockPtr<void(BOOL, NSArray *)> _dropCompletionBlock;
326 }
327
328 - (instancetype)initWithWebViewFrame:(CGRect)frame
329 {
330     return [self initWithWebViewFrame:frame configuration:nil];
331 }
332
333 - (instancetype)initWithWebViewFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
334 {
335     if (configuration)
336         return [self initWithWebView:[[[TestWKWebView alloc] initWithFrame:frame configuration:configuration] autorelease]];
337
338     return [self initWithWebView:[[[TestWKWebView alloc] initWithFrame:frame] autorelease]];
339 }
340
341 - (instancetype)initWithWebView:(TestWKWebView *)webView
342 {
343     if (self = [super init]) {
344         _webView = webView;
345         _shouldEnsureUIApplication = NO;
346         _shouldBecomeFirstResponder = YES;
347         _shouldAllowMoveOperation = YES;
348         [_webView setUIDelegate:self];
349         [_webView _setInputDelegate:self];
350         self.dragDestinationAction = WKDragDestinationActionAny & ~WKDragDestinationActionLoad;
351     }
352     return self;
353 }
354
355 - (void)dealloc
356 {
357     if ([_webView UIDelegate] == self)
358         [_webView setUIDelegate:nil];
359
360     if ([_webView _inputDelegate] == self)
361         [_webView _setInputDelegate:nil];
362
363     [super dealloc];
364 }
365
366 - (void)_resetSimulatedState
367 {
368     _suppressedSelectionCommandsDuringDrop = NO;
369     _phase = DragAndDropPhaseBeginning;
370     _currentProgress = 0;
371     _isDoneWithCurrentRun = false;
372     _observedEventNames = adoptNS([[NSMutableArray alloc] init]);
373     _insertedAttachments = adoptNS([[NSMutableArray alloc] init]);
374     _removedAttachments = adoptNS([[NSMutableArray alloc] init]);
375     _finalSelectionRects = @[ ];
376     _dragSession = nil;
377     _dropSession = nil;
378     _lastKnownDropProposal = nil;
379     _lastKnownDragCaretRect = CGRectZero;
380     _remainingAdditionalItemRequestLocationsByProgress = nil;
381     _queuedAdditionalItemRequestLocations = adoptNS([[NSMutableArray alloc] init]);
382     _liftPreviews = adoptNS([[NSMutableArray alloc] init]);
383     _hasStartedInputSession = false;
384 }
385
386 - (NSArray *)observedEventNames
387 {
388     return _observedEventNames.get();
389 }
390
391 - (UIDropProposal *)lastKnownDropProposal
392 {
393     return _lastKnownDropProposal.get();
394 }
395
396 - (void)simulateAllTouchesCanceled:(NSNotification *)notification
397 {
398     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_advanceProgress) object:nil];
399     _phase = DragAndDropPhaseCancelled;
400     _currentProgress = 1;
401     _isDoneWithCurrentRun = true;
402     if (_dragSession)
403         [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] session:_dragSession.get() didEndWithOperation:UIDropOperationCancel];
404 }
405
406 - (void)runFrom:(CGPoint)startLocation to:(CGPoint)endLocation
407 {
408     [self runFrom:startLocation to:endLocation additionalItemRequestLocations:nil];
409 }
410
411 - (void)runFrom:(CGPoint)startLocation to:(CGPoint)endLocation additionalItemRequestLocations:(ProgressToCGPointValueMap)additionalItemRequestLocations
412 {
413     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
414     [defaultCenter addObserver:self selector:@selector(simulateAllTouchesCanceled:) name:TestWebKitAPISimulateCancelAllTouchesNotificationName object:nil];
415
416     if (_shouldEnsureUIApplication)
417         UIApplicationInstantiateSingleton([DragAndDropSimulatorApplication class]);
418
419     if (_shouldBecomeFirstResponder)
420         [_webView becomeFirstResponder];
421
422     [self _resetSimulatedState];
423
424     if (additionalItemRequestLocations)
425         _remainingAdditionalItemRequestLocationsByProgress = adoptNS([additionalItemRequestLocations mutableCopy]);
426
427     for (NSString *eventName in dragAndDropEventNames()) {
428         [_webView performAfterReceivingMessage:eventName action:[strongSelf = retainPtr(self), name = retainPtr(eventName)] {
429             [strongSelf->_observedEventNames addObject:name.get()];
430         }];
431     }
432
433     _startLocation = startLocation;
434     _endLocation = endLocation;
435
436     if (self.externalItemProviders.count) {
437         _dropSession = adoptNS([[MockDropSession alloc] initWithProviders:self.externalItemProviders location:_startLocation window:[_webView window] allowMove:self.shouldAllowMoveOperation]);
438         _phase = DragAndDropPhaseBegan;
439         [self _advanceProgress];
440     } else {
441         _dragSession = adoptNS([[MockDragSession alloc] initWithWindow:[_webView window] allowMove:self.shouldAllowMoveOperation]);
442         [_dragSession setMockLocationInWindow:_startLocation];
443         [(id <UIDragInteractionDelegate_ForWebKitOnly>)[_webView dragInteractionDelegate] _dragInteraction:[_webView dragInteraction] prepareForSession:_dragSession.get() completion:[strongSelf = retainPtr(self)] {
444             if (strongSelf->_phase == DragAndDropPhaseCancelled)
445                 return;
446
447             strongSelf->_phase = DragAndDropPhaseBeginning;
448             [strongSelf _advanceProgress];
449         }];
450     }
451
452     Util::run(&_isDoneWithCurrentRun);
453     [_webView clearMessageHandlers:dragAndDropEventNames()];
454     _finalSelectionRects = [_webView selectionRectsAfterPresentationUpdate];
455
456     [defaultCenter removeObserver:self];
457 }
458
459 - (NSArray *)finalSelectionRects
460 {
461     return _finalSelectionRects.get();
462 }
463
464 - (void)_concludeDropAndPerformOperationIfNecessary
465 {
466     _lastKnownDragCaretRect = [_webView _dragCaretRect];
467     auto operation = [_lastKnownDropProposal operation];
468     if (operation != UIDropOperationCancel && operation != UIDropOperationForbidden) {
469         [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] performDrop:_dropSession.get()];
470         _phase = DragAndDropPhasePerformingDrop;
471     } else {
472         _isDoneWithCurrentRun = YES;
473         _phase = DragAndDropPhaseCancelled;
474     }
475
476     [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidEnd:_dropSession.get()];
477
478     if (_dragSession) {
479         auto delegate = [_webView dragInteractionDelegate];
480         [delegate dragInteraction:[_webView dragInteraction] session:_dragSession.get() didEndWithOperation:operation];
481         if ([delegate respondsToSelector:@selector(_clearToken:)])
482             [(id <UITextInputMultiDocument>)delegate _clearToken:nil];
483         [_webView becomeFirstResponder];
484     }
485 }
486
487 - (void)_enqueuePendingAdditionalItemRequestLocations
488 {
489     NSMutableArray *progressValuesToRemove = [NSMutableArray array];
490     for (NSNumber *progressValue in _remainingAdditionalItemRequestLocationsByProgress.get()) {
491         double progress = progressValue.doubleValue;
492         if (progress > _currentProgress)
493             continue;
494         [progressValuesToRemove addObject:progressValue];
495         [_queuedAdditionalItemRequestLocations addObject:[_remainingAdditionalItemRequestLocationsByProgress objectForKey:progressValue]];
496     }
497
498     for (NSNumber *progressToRemove in progressValuesToRemove)
499         [_remainingAdditionalItemRequestLocationsByProgress removeObjectForKey:progressToRemove];
500 }
501
502 - (BOOL)_sendQueuedAdditionalItemRequest
503 {
504     if (![_queuedAdditionalItemRequestLocations count])
505         return NO;
506
507     RetainPtr<NSValue> requestLocationValue = [_queuedAdditionalItemRequestLocations objectAtIndex:0];
508     [_queuedAdditionalItemRequestLocations removeObjectAtIndex:0];
509
510     auto requestLocation = [[_webView window] convertPoint:[requestLocationValue CGPointValue] toView:_webView.get()];
511     [(id <UIDragInteractionDelegate_ForWebKitOnly>)[_webView dragInteractionDelegate] _dragInteraction:[_webView dragInteraction] itemsForAddingToSession:_dragSession.get() withTouchAtPoint:requestLocation completion:[dragSession = _dragSession, dropSession = _dropSession] (NSArray *items) {
512         [dragSession addItems:items];
513         [dropSession addItems:items];
514     }];
515     return YES;
516 }
517
518 - (void)_advanceProgress
519 {
520     [self _enqueuePendingAdditionalItemRequestLocations];
521     if ([self _sendQueuedAdditionalItemRequest]) {
522         [self _scheduleAdvanceProgress];
523         return;
524     }
525
526     _lastKnownDragCaretRect = [_webView _dragCaretRect];
527     _currentProgress += progressIncrementStep;
528     CGPoint locationInWindow = self._currentLocation;
529     [_dragSession setMockLocationInWindow:locationInWindow];
530     [_dropSession setMockLocationInWindow:locationInWindow];
531
532     if (_currentProgress >= 1) {
533         _currentProgress = 1;
534         [self _concludeDropAndPerformOperationIfNecessary];
535         return;
536     }
537
538     switch (_phase) {
539     case DragAndDropPhaseBeginning: {
540         NSMutableArray<NSItemProvider *> *itemProviders = [NSMutableArray array];
541         NSArray *items = [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] itemsForBeginningSession:_dragSession.get()];
542         if (!items.count) {
543             _phase = DragAndDropPhaseCancelled;
544             _currentProgress = 1;
545             _isDoneWithCurrentRun = true;
546             return;
547         }
548
549         for (UIDragItem *item in items) {
550             [itemProviders addObject:item.itemProvider];
551             UITargetedDragPreview *liftPreview = [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] previewForLiftingItem:item session:_dragSession.get()];
552             EXPECT_TRUE(!!liftPreview);
553             if (liftPreview)
554                 [_liftPreviews addObject:liftPreview];
555         }
556
557         _dropSession = adoptNS([[MockDropSession alloc] initWithProviders:itemProviders location:self._currentLocation window:[_webView window] allowMove:self.shouldAllowMoveOperation]);
558         [_dragSession setItems:items];
559         _sourceItemProviders = itemProviders;
560         if (self.showCustomActionSheetBlock) {
561             // Defer progress until the custom action sheet is dismissed.
562             auto startLocationInView = [[_webView window] convertPoint:_startLocation toView:_webView.get()];
563             [_webView _simulateLongPressActionAtLocation:startLocationInView];
564             return;
565         }
566
567         auto delegate = [_webView dragInteractionDelegate];
568         if ([delegate respondsToSelector:@selector(_preserveFocusWithToken:destructively:)])
569             [(id <UITextInputMultiDocument>)delegate _preserveFocusWithToken:nil destructively:NO];
570
571         [_webView resignFirstResponder];
572
573         [delegate dragInteraction:[_webView dragInteraction] sessionWillBegin:_dragSession.get()];
574
575         RetainPtr<WKWebView> retainedWebView = _webView;
576         dispatch_async(dispatch_get_main_queue(), ^() {
577             [retainedWebView resignFirstResponder];
578         });
579
580         _phase = DragAndDropPhaseBegan;
581         break;
582     }
583     case DragAndDropPhaseBegan:
584         [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidEnter:_dropSession.get()];
585         _phase = DragAndDropPhaseEntered;
586         break;
587     case DragAndDropPhaseEntered: {
588         _lastKnownDropProposal = [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidUpdate:_dropSession.get()];
589         if (![self shouldAllowMoveOperation] && [_lastKnownDropProposal operation] == UIDropOperationMove)
590             _lastKnownDropProposal = adoptNS([[UIDropProposal alloc] initWithDropOperation:UIDropOperationCancel]);
591         break;
592     }
593     default:
594         break;
595     }
596
597     [self _scheduleAdvanceProgress];
598 }
599
600 - (void)clearExternalDragInformation
601 {
602     _externalItemProviders = nil;
603 }
604
605 - (CGPoint)_currentLocation
606 {
607     CGFloat distanceX = _endLocation.x - _startLocation.x;
608     CGFloat distanceY = _endLocation.y - _startLocation.y;
609     return CGPointMake(_startLocation.x + _currentProgress * distanceX, _startLocation.y + _currentProgress * distanceY);
610 }
611
612 - (void)_scheduleAdvanceProgress
613 {
614     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_advanceProgress) object:nil];
615     [self performSelector:@selector(_advanceProgress) withObject:nil afterDelay:progressTimeStep];
616 }
617
618 - (NSArray *)sourceItemProviders
619 {
620     return _sourceItemProviders.get();
621 }
622
623 - (NSArray *)externalItemProviders
624 {
625     return _externalItemProviders.get();
626 }
627
628 - (void)setExternalItemProviders:(NSArray *)externalItemProviders
629 {
630     _externalItemProviders = adoptNS([externalItemProviders copy]);
631 }
632
633 - (DragAndDropPhase)phase
634 {
635     return _phase;
636 }
637
638 - (NSArray<UITargetedDragPreview *> *)liftPreviews
639 {
640     return _liftPreviews.get();
641 }
642
643 - (CGRect)lastKnownDragCaretRect
644 {
645     return _lastKnownDragCaretRect;
646 }
647
648 - (void)ensureInputSession
649 {
650     Util::run(&_hasStartedInputSession);
651 }
652
653 - (NSArray<_WKAttachment *> *)insertedAttachments
654 {
655     return _insertedAttachments.get();
656 }
657
658 - (NSArray<_WKAttachment *> *)removedAttachments
659 {
660     return _removedAttachments.get();
661 }
662
663 - (void)endDataTransfer
664 {
665     [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] sessionDidTransferItems:_dragSession.get()];
666 }
667
668 - (TestWKWebView *)webView
669 {
670     return _webView.get();
671 }
672
673 - (void)setShowCustomActionSheetBlock:(BOOL(^)(_WKActivatedElementInfo *))showCustomActionSheetBlock
674 {
675     _showCustomActionSheetBlock = showCustomActionSheetBlock;
676 }
677
678 - (BOOL(^)(_WKActivatedElementInfo *))showCustomActionSheetBlock
679 {
680     return _showCustomActionSheetBlock.get();
681 }
682
683 - (void)setConvertItemProvidersBlock:(NSArray *(^)(NSItemProvider *, NSArray *, NSDictionary *))convertItemProvidersBlock
684 {
685     _convertItemProvidersBlock = convertItemProvidersBlock;
686 }
687
688 - (NSArray *(^)(NSItemProvider *, NSArray *, NSDictionary *))convertItemProvidersBlock
689 {
690     return _convertItemProvidersBlock.get();
691 }
692
693 - (void)setOverridePerformDropBlock:(NSArray *(^)(id <UIDropSession>))overridePerformDropBlock
694 {
695     _overridePerformDropBlock = overridePerformDropBlock;
696 }
697
698 - (NSArray *(^)(id <UIDropSession>))overridePerformDropBlock
699 {
700     return _overridePerformDropBlock.get();
701 }
702
703 - (void)setOverrideDragUpdateBlock:(UIDropOperation(^)(UIDropOperation, id <UIDropSession>))overrideDragUpdateBlock
704 {
705     _overrideDragUpdateBlock = overrideDragUpdateBlock;
706 }
707
708 - (UIDropOperation(^)(UIDropOperation, id <UIDropSession>))overrideDragUpdateBlock
709 {
710     return _overrideDragUpdateBlock.get();
711 }
712
713 - (void)setDropCompletionBlock:(void(^)(BOOL, NSArray *))dropCompletionBlock
714 {
715     _dropCompletionBlock = dropCompletionBlock;
716 }
717
718 - (void(^)(BOOL, NSArray *))dropCompletionBlock
719 {
720     return _dropCompletionBlock.get();
721 }
722
723 #pragma mark - WKUIDelegatePrivate
724
725 - (void)_webView:(WKWebView *)webView dataInteractionOperationWasHandled:(BOOL)handled forSession:(id)session itemProviders:(NSArray<NSItemProvider *> *)itemProviders
726 {
727     _suppressedSelectionCommandsDuringDrop = [_webView textInputContentView]._shouldSuppressSelectionCommands;
728     _isDoneWithCurrentRun = true;
729
730     if (self.dropCompletionBlock)
731         self.dropCompletionBlock(handled, itemProviders);
732 }
733
734 - (UIDropProposal *)_webView:(WKWebView *)webView willUpdateDropProposalToProposal:(UIDropProposal *)proposal forSession:(id <UIDropSession>)session
735 {
736     if (!self.overrideDragUpdateBlock)
737         return proposal;
738
739     return [[[UIDropProposal alloc] initWithDropOperation:self.overrideDragUpdateBlock(proposal.operation, session)] autorelease];
740 }
741
742 - (NSArray *)_webView:(WKWebView *)webView adjustedDataInteractionItemProvidersForItemProvider:(NSItemProvider *)itemProvider representingObjects:(NSArray *)representingObjects additionalData:(NSDictionary *)additionalData
743 {
744     return self.convertItemProvidersBlock ? self.convertItemProvidersBlock(itemProvider, representingObjects, additionalData) : @[ itemProvider ];
745 }
746
747 - (BOOL)_webView:(WKWebView *)webView showCustomSheetForElement:(_WKActivatedElementInfo *)element
748 {
749     if (!self.showCustomActionSheetBlock)
750         return NO;
751
752     dispatch_async(dispatch_get_main_queue(), [strongSelf = retainPtr(self)] {
753         [[strongSelf->_webView dragInteractionDelegate] dragInteraction:[strongSelf->_webView dragInteraction] sessionWillBegin:strongSelf->_dragSession.get()];
754         strongSelf->_phase = DragAndDropPhaseBegan;
755         [strongSelf _scheduleAdvanceProgress];
756     });
757
758     return self.showCustomActionSheetBlock(element);
759 }
760
761 - (NSArray<UIDragItem *> *)_webView:(WKWebView *)webView willPerformDropWithSession:(id <UIDropSession>)session
762 {
763     return self.overridePerformDropBlock ? self.overridePerformDropBlock(session) : session.items;
764 }
765
766 - (void)_webView:(WKWebView *)webView didInsertAttachment:(_WKAttachment *)attachment withSource:(NSString *)source
767 {
768     [_insertedAttachments addObject:attachment];
769 }
770
771 - (void)_webView:(WKWebView *)webView didRemoveAttachment:(_WKAttachment *)attachment
772 {
773     [_removedAttachments addObject:attachment];
774 }
775
776 - (WKDragDestinationAction)_webView:(WKWebView *)webView dragDestinationActionMaskForDraggingInfo:(id)draggingInfo
777 {
778     return self.dragDestinationAction;
779 }
780
781 #pragma mark - _WKInputDelegate
782
783 - (BOOL)_webView:(WKWebView *)webView focusShouldStartInputSession:(id <_WKFocusedElementInfo>)info
784 {
785     return _allowsFocusToStartInputSession;
786 }
787
788 - (void)_webView:(WKWebView *)webView didStartInputSession:(id <_WKFormInputSession>)inputSession
789 {
790     _hasStartedInputSession = true;
791 }
792
793 @end
794
795 #endif // ENABLE(DRAG_SUPPORT) && PLATFORM(IOS_FAMILY)