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