Switch from PLATFORM(IOS) to PLATFORM(IOS_FAMILY)
[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<UIItemProviderReading>)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<UIItemProviderReading>> *)classes
133 {
134     for (Class<UIItemProviderReading> 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<UIItemProvider *> *)providers location:(CGPoint)locationInWindow window:(UIWindow *)window allowMove:(BOOL)allowMove
175 {
176     auto items = adoptNS([[NSMutableArray alloc] init]);
177     for (UIItemProvider *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<UIItemProviderReading>)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 _isDoneWaitingForInputSession;
314     double _currentProgress;
315     bool _isDoneWithCurrentRun;
316     DragAndDropPhase _phase;
317
318     RetainPtr<UIDropProposal> _currentDropProposal;
319 }
320
321 - (instancetype)initWithWebViewFrame:(CGRect)frame
322 {
323     return [self initWithWebViewFrame:frame configuration:nil];
324 }
325
326 - (instancetype)initWithWebViewFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
327 {
328     if (configuration)
329         return [self initWithWebView:[[[TestWKWebView alloc] initWithFrame:frame configuration:configuration] autorelease]];
330
331     return [self initWithWebView:[[[TestWKWebView alloc] initWithFrame:frame] autorelease]];
332 }
333
334 - (instancetype)initWithWebView:(TestWKWebView *)webView
335 {
336     if (self = [super init]) {
337         _webView = webView;
338         _shouldEnsureUIApplication = NO;
339         _shouldAllowMoveOperation = YES;
340         _isDoneWaitingForInputSession = true;
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     _phase = DragAndDropPhaseBeginning;
361     _currentProgress = 0;
362     _isDoneWithCurrentRun = false;
363     _observedEventNames = adoptNS([[NSMutableArray alloc] init]);
364     _insertedAttachments = adoptNS([[NSMutableArray alloc] init]);
365     _removedAttachments = adoptNS([[NSMutableArray alloc] init]);
366     _finalSelectionRects = @[ ];
367     _dragSession = nil;
368     _dropSession = nil;
369     _currentDropProposal = nil;
370     _lastKnownDragCaretRect = CGRectZero;
371     _remainingAdditionalItemRequestLocationsByProgress = nil;
372     _queuedAdditionalItemRequestLocations = adoptNS([[NSMutableArray alloc] init]);
373     _liftPreviews = adoptNS([[NSMutableArray alloc] init]);
374 }
375
376 - (NSArray *)observedEventNames
377 {
378     return _observedEventNames.get();
379 }
380
381 - (void)simulateAllTouchesCanceled:(NSNotification *)notification
382 {
383     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_advanceProgress) object:nil];
384     _phase = DragAndDropPhaseCancelled;
385     _currentProgress = 1;
386     _isDoneWithCurrentRun = true;
387     if (_dragSession)
388         [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] session:_dragSession.get() didEndWithOperation:UIDropOperationCancel];
389 }
390
391 - (void)runFrom:(CGPoint)startLocation to:(CGPoint)endLocation
392 {
393     [self runFrom:startLocation to:endLocation additionalItemRequestLocations:nil];
394 }
395
396 - (void)runFrom:(CGPoint)startLocation to:(CGPoint)endLocation additionalItemRequestLocations:(ProgressToCGPointValueMap)additionalItemRequestLocations
397 {
398     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
399     [defaultCenter addObserver:self selector:@selector(simulateAllTouchesCanceled:) name:TestWebKitAPISimulateCancelAllTouchesNotificationName object:nil];
400
401     if (_shouldEnsureUIApplication)
402         UIApplicationInstantiateSingleton([DragAndDropSimulatorApplication class]);
403
404     [self _resetSimulatedState];
405
406     if (additionalItemRequestLocations)
407         _remainingAdditionalItemRequestLocationsByProgress = adoptNS([additionalItemRequestLocations mutableCopy]);
408
409     for (NSString *eventName in dragAndDropEventNames()) {
410         [_webView performAfterReceivingMessage:eventName action:[strongSelf = retainPtr(self), name = retainPtr(eventName)] {
411             [strongSelf->_observedEventNames addObject:name.get()];
412         }];
413     }
414
415     _startLocation = startLocation;
416     _endLocation = endLocation;
417
418     if (self.externalItemProviders.count) {
419         _dropSession = adoptNS([[MockDropSession alloc] initWithProviders:self.externalItemProviders location:_startLocation window:[_webView window] allowMove:self.shouldAllowMoveOperation]);
420         _phase = DragAndDropPhaseBegan;
421         [self _advanceProgress];
422     } else {
423         _dragSession = adoptNS([[MockDragSession alloc] initWithWindow:[_webView window] allowMove:self.shouldAllowMoveOperation]);
424         [_dragSession setMockLocationInWindow:_startLocation];
425         [(id <UIDragInteractionDelegate_ForWebKitOnly>)[_webView dragInteractionDelegate] _dragInteraction:[_webView dragInteraction] prepareForSession:_dragSession.get() completion:[strongSelf = retainPtr(self)] {
426             if (strongSelf->_phase == DragAndDropPhaseCancelled)
427                 return;
428
429             strongSelf->_phase = DragAndDropPhaseBeginning;
430             [strongSelf _advanceProgress];
431         }];
432     }
433
434     Util::run(&_isDoneWithCurrentRun);
435     [_webView clearMessageHandlers:dragAndDropEventNames()];
436     _finalSelectionRects = [_webView selectionRectsAfterPresentationUpdate];
437
438     [defaultCenter removeObserver:self];
439 }
440
441 - (NSArray *)finalSelectionRects
442 {
443     return _finalSelectionRects.get();
444 }
445
446 - (void)_concludeDropAndPerformOperationIfNecessary
447 {
448     _lastKnownDragCaretRect = [_webView _dragCaretRect];
449     auto operation = [_currentDropProposal operation];
450     if (operation != UIDropOperationCancel && operation != UIDropOperationForbidden) {
451         [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] performDrop:_dropSession.get()];
452         _phase = DragAndDropPhasePerformingDrop;
453     } else {
454         _isDoneWithCurrentRun = YES;
455         _phase = DragAndDropPhaseCancelled;
456     }
457
458     [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidEnd:_dropSession.get()];
459
460     if (_dragSession)
461         [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] session:_dragSession.get() didEndWithOperation:operation];
462 }
463
464 - (void)_enqueuePendingAdditionalItemRequestLocations
465 {
466     NSMutableArray *progressValuesToRemove = [NSMutableArray array];
467     for (NSNumber *progressValue in _remainingAdditionalItemRequestLocationsByProgress.get()) {
468         double progress = progressValue.doubleValue;
469         if (progress > _currentProgress)
470             continue;
471         [progressValuesToRemove addObject:progressValue];
472         [_queuedAdditionalItemRequestLocations addObject:[_remainingAdditionalItemRequestLocationsByProgress objectForKey:progressValue]];
473     }
474
475     for (NSNumber *progressToRemove in progressValuesToRemove)
476         [_remainingAdditionalItemRequestLocationsByProgress removeObjectForKey:progressToRemove];
477 }
478
479 - (BOOL)_sendQueuedAdditionalItemRequest
480 {
481     if (![_queuedAdditionalItemRequestLocations count])
482         return NO;
483
484     RetainPtr<NSValue> requestLocationValue = [_queuedAdditionalItemRequestLocations objectAtIndex:0];
485     [_queuedAdditionalItemRequestLocations removeObjectAtIndex:0];
486
487     auto requestLocation = [[_webView window] convertPoint:[requestLocationValue CGPointValue] toView:_webView.get()];
488     [(id <UIDragInteractionDelegate_Proposed_SPI_33146803>)[_webView dragInteractionDelegate] _dragInteraction:[_webView dragInteraction] itemsForAddingToSession:_dragSession.get() withTouchAtPoint:requestLocation completion:[dragSession = _dragSession, dropSession = _dropSession] (NSArray *items) {
489         [dragSession addItems:items];
490         [dropSession addItems:items];
491     }];
492     return YES;
493 }
494
495 - (void)_advanceProgress
496 {
497     [self _enqueuePendingAdditionalItemRequestLocations];
498     if ([self _sendQueuedAdditionalItemRequest]) {
499         [self _scheduleAdvanceProgress];
500         return;
501     }
502
503     _lastKnownDragCaretRect = [_webView _dragCaretRect];
504     _currentProgress += progressIncrementStep;
505     CGPoint locationInWindow = self._currentLocation;
506     [_dragSession setMockLocationInWindow:locationInWindow];
507     [_dropSession setMockLocationInWindow:locationInWindow];
508
509     if (_currentProgress >= 1) {
510         _currentProgress = 1;
511         [self _concludeDropAndPerformOperationIfNecessary];
512         return;
513     }
514
515     switch (_phase) {
516     case DragAndDropPhaseBeginning: {
517         NSMutableArray<UIItemProvider *> *itemProviders = [NSMutableArray array];
518         NSArray *items = [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] itemsForBeginningSession:_dragSession.get()];
519         if (!items.count) {
520             _phase = DragAndDropPhaseCancelled;
521             _currentProgress = 1;
522             _isDoneWithCurrentRun = true;
523             return;
524         }
525
526         for (UIDragItem *item in items) {
527             [itemProviders addObject:item.itemProvider];
528             UITargetedDragPreview *liftPreview = [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] previewForLiftingItem:item session:_dragSession.get()];
529             EXPECT_TRUE(!!liftPreview);
530             if (liftPreview)
531                 [_liftPreviews addObject:liftPreview];
532         }
533
534         _dropSession = adoptNS([[MockDropSession alloc] initWithProviders:itemProviders location:self._currentLocation window:[_webView window] allowMove:self.shouldAllowMoveOperation]);
535         [_dragSession setItems:items];
536         _sourceItemProviders = itemProviders;
537         if (self.showCustomActionSheetBlock) {
538             // Defer progress until the custom action sheet is dismissed.
539             auto startLocationInView = [[_webView window] convertPoint:_startLocation toView:_webView.get()];
540             [_webView _simulateLongPressActionAtLocation:startLocationInView];
541             return;
542         }
543
544         [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] sessionWillBegin:_dragSession.get()];
545
546         RetainPtr<WKWebView> retainedWebView = _webView;
547         dispatch_async(dispatch_get_main_queue(), ^() {
548             [retainedWebView resignFirstResponder];
549         });
550
551         _phase = DragAndDropPhaseBegan;
552         break;
553     }
554     case DragAndDropPhaseBegan:
555         [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidEnter:_dropSession.get()];
556         _phase = DragAndDropPhaseEntered;
557         break;
558     case DragAndDropPhaseEntered: {
559         _currentDropProposal = [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] sessionDidUpdate:_dropSession.get()];
560         if (![self shouldAllowMoveOperation] && [_currentDropProposal operation] == UIDropOperationMove)
561             _currentDropProposal = adoptNS([[UIDropProposal alloc] initWithDropOperation:UIDropOperationCancel]);
562         break;
563     }
564     default:
565         break;
566     }
567
568     [self _scheduleAdvanceProgress];
569 }
570
571 - (void)clearExternalDragInformation
572 {
573     _externalItemProviders = nil;
574 }
575
576 - (CGPoint)_currentLocation
577 {
578     CGFloat distanceX = _endLocation.x - _startLocation.x;
579     CGFloat distanceY = _endLocation.y - _startLocation.y;
580     return CGPointMake(_startLocation.x + _currentProgress * distanceX, _startLocation.y + _currentProgress * distanceY);
581 }
582
583 - (void)_scheduleAdvanceProgress
584 {
585     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_advanceProgress) object:nil];
586     [self performSelector:@selector(_advanceProgress) withObject:nil afterDelay:progressTimeStep];
587 }
588
589 - (NSArray *)sourceItemProviders
590 {
591     return _sourceItemProviders.get();
592 }
593
594 - (NSArray *)externalItemProviders
595 {
596     return _externalItemProviders.get();
597 }
598
599 - (void)setExternalItemProviders:(NSArray *)externalItemProviders
600 {
601     _externalItemProviders = adoptNS([externalItemProviders copy]);
602 }
603
604 - (DragAndDropPhase)phase
605 {
606     return _phase;
607 }
608
609 - (NSArray<UITargetedDragPreview *> *)liftPreviews
610 {
611     return _liftPreviews.get();
612 }
613
614 - (CGRect)lastKnownDragCaretRect
615 {
616     return _lastKnownDragCaretRect;
617 }
618
619 - (void)waitForInputSession
620 {
621     _isDoneWaitingForInputSession = false;
622
623     // Waiting for an input session implies that we should allow input sessions to begin.
624     self.allowsFocusToStartInputSession = YES;
625
626     Util::run(&_isDoneWaitingForInputSession);
627 }
628
629 - (NSArray<_WKAttachment *> *)insertedAttachments
630 {
631     return _insertedAttachments.get();
632 }
633
634 - (NSArray<_WKAttachment *> *)removedAttachments
635 {
636     return _removedAttachments.get();
637 }
638
639 - (void)endDataTransfer
640 {
641     [[_webView dragInteractionDelegate] dragInteraction:[_webView dragInteraction] sessionDidTransferItems:_dragSession.get()];
642 }
643
644 - (TestWKWebView *)webView
645 {
646     return _webView.get();
647 }
648
649 #pragma mark - WKUIDelegatePrivate
650
651 - (void)_webView:(WKWebView *)webView dataInteractionOperationWasHandled:(BOOL)handled forSession:(id)session itemProviders:(NSArray<UIItemProvider *> *)itemProviders
652 {
653     _isDoneWithCurrentRun = true;
654
655     if (self.dropCompletionBlock)
656         self.dropCompletionBlock(handled, itemProviders);
657 }
658
659 - (NSUInteger)_webView:(WKWebView *)webView willUpdateDataInteractionOperationToOperation:(NSUInteger)operation forSession:(id)session
660 {
661     return self.overrideDragUpdateBlock ? self.overrideDragUpdateBlock(operation, session) : operation;
662 }
663
664 - (NSArray *)_webView:(WKWebView *)webView adjustedDataInteractionItemProvidersForItemProvider:(UIItemProvider *)itemProvider representingObjects:(NSArray *)representingObjects additionalData:(NSDictionary *)additionalData
665 {
666     return self.convertItemProvidersBlock ? self.convertItemProvidersBlock(itemProvider, representingObjects, additionalData) : @[ itemProvider ];
667 }
668
669 - (BOOL)_webView:(WKWebView *)webView showCustomSheetForElement:(_WKActivatedElementInfo *)element
670 {
671     if (!self.showCustomActionSheetBlock)
672         return NO;
673
674     dispatch_async(dispatch_get_main_queue(), [strongSelf = retainPtr(self)] {
675         [[strongSelf->_webView dragInteractionDelegate] dragInteraction:[strongSelf->_webView dragInteraction] sessionWillBegin:strongSelf->_dragSession.get()];
676         strongSelf->_phase = DragAndDropPhaseBegan;
677         [strongSelf _scheduleAdvanceProgress];
678     });
679
680     return self.showCustomActionSheetBlock(element);
681 }
682
683 - (NSArray<UIDragItem *> *)_webView:(WKWebView *)webView willPerformDropWithSession:(id <UIDropSession>)session
684 {
685     return self.overridePerformDropBlock ? self.overridePerformDropBlock(session) : session.items;
686 }
687
688 - (void)_webView:(WKWebView *)webView didInsertAttachment:(_WKAttachment *)attachment withSource:(NSString *)source
689 {
690     [_insertedAttachments addObject:attachment];
691 }
692
693 - (void)_webView:(WKWebView *)webView didRemoveAttachment:(_WKAttachment *)attachment
694 {
695     [_removedAttachments addObject:attachment];
696 }
697
698 #pragma mark - _WKInputDelegate
699
700 - (BOOL)_webView:(WKWebView *)webView focusShouldStartInputSession:(id <_WKFocusedElementInfo>)info
701 {
702     return _allowsFocusToStartInputSession;
703 }
704
705 - (void)_webView:(WKWebView *)webView didStartInputSession:(id <_WKFormInputSession>)inputSession
706 {
707     _isDoneWaitingForInputSession = true;
708 }
709
710 @end
711
712 #endif // ENABLE(DRAG_SUPPORT) && PLATFORM(IOS_FAMILY) && WK_API_ENABLED