Title: [250256] trunk
Revision
250256
Author
[email protected]
Date
2019-09-23 15:16:47 -0700 (Mon, 23 Sep 2019)

Log Message

[iOS] Drop animation when dragging images from Photos to WebKit2 Mail compose is incorrect
https://bugs.webkit.org/show_bug.cgi?id=201674
<rdar://problem/51250952>

Reviewed by Tim Horton.

Source/WebCore:

Adds new helper methods on DragController to support the new image placeholder drop codepath. See WebKit
ChangeLog for more details.

Tests:  WKAttachmentTestsIOS.TargetedPreviewsWhenDroppingImages
        WKAttachmentTestsIOS.TargetedPreviewIsClippedWhenDroppingTallImage

* editing/WebContentReader.h:

Fix the Windows build after including WebContentReader.h in DragController.cpp.

* html/HTMLImageElement.h:
(WebCore::HTMLImageElement::isDroppedImagePlaceholder const):
(WebCore::HTMLImageElement::setIsDroppedImagePlaceholder):

Add a flag to HTMLImageElement, indicating whether it is a dropped image placeholder. If so, we have special
logic to remove some temporary inline style properties from the image after it has finished loading (see
finalizeDroppedImagePlaceholder).

Note that this doesn't increase the size of HTMLImageElement.

* page/DragController.cpp:
(WebCore::DragController::dragEnded):

Clean up any stale placeholders after the drag ends.

(WebCore::DragController::performDragOperation):
(WebCore::DragController::removeAllDroppedImagePlaceholders):

Add a private helper to clean up any dropped image placeholders after failing to update dropped image
placeholders for any reason.

(WebCore::DragController::tryToUpdateDroppedImagePlaceholders):

Invoked when performing the drag operation, after image data has been loaded; this function attempts to update
the list of image placeholder elements tracked by DragController that were previously inserted using
insertDroppedImagePlaceholdersAtCaret, and updates the source attribute of each element (as well as any backed
attachment element, if attachment elements are enabled). It achieves this by reading the dropped data as web
content, and matching up the images in the resulting fragment against the placeholder images. If each image in
the fragment can correspond to exactly one placeholder, we update the source of each placeholder image,
migrate attachment elements over to the placeholder images if needed, and finally discard the fragment.

A return value of false indicates that this process failed, in which case we clean up the placeholders and fall
back to handling the drop normally.

(WebCore::DragController::insertDroppedImagePlaceholdersAtCaret):

Invoked when handling the drop, before any image data has been loaded; this function takes a list of sizes
representing the preferred presentation sizes of each item provider that will be loaded as an image, and uses
ReplaceSelectionCommand to insert a list of (initially blank) placeholder images at the drop caret, sized
accordingly to each item provider's preferredPresentationSize.

To make this compatible with Mail compose (and all other known internal clients that use the _editable SPI), we
additionally enforce a max-width of 100% on each image and preserve the aspect ratio of the image by adjusting
the height if needed.

(WebCore::DragController::finalizeDroppedImagePlaceholder):
* page/DragController.h:

Have DragController keep track of the list of dropped image placeholders (in DOM order), as well as the dropped
image placeholder range. This information is used once item provider data arrives and the drag operation is
being performed, to update the source of each dropped image placeholder.

(WebCore::DragController::droppedImagePlaceholders const):
(WebCore::DragController::droppedImagePlaceholderRange const):
* platform/network/mac/UTIUtilities.h:

Mark an existing helper function as WEBCORE_EXPORT.

Source/WebKit:

Our current logic for handling dropped content in editable elements on iOS works like this in the ideal case:

(1)     UIKit asks us for a targeted preview for each UIDragItem. We don't know (and can't determine this
        synchronously without blocking on the web process) so we simply retarget the preview to animate to the
        last known caret location.

(2)     Soonafter, UIKit hands us a drop preview update block, which may be used to retarget the drop preview
        once, as long as the drop animation is less than 90% complete. We stash these update blocks for now.

(3)     -dropInteraction:performDrop: is then called, and we start loading item provider data right away.

(4)     When the data has finished loading, we perform the drop in the web process. After any inserted images
        have finished loading, we take snapshots (of the dropped content as well as surrounding web content
        minus the dropped content), and deliver these images to the UI process via TextIndicatorData.

(5)     Upon receiving the TextIndicatorData sent in (4), we use the image data to create updated targeted drag
        previews, and use these to invoke the preview update blocks we stored earlier in (2). We also obscure
        the entire web view with a snapshot of the view minus any dropped content, such that the updated drop
        previews may animate into place without also showing the final content.

(6)     When the drop animation ends, we remove the unselected content snapshot view added in (5) simultaneously
        as the targeted previews disappear, revealing the actual dropped content on the page. The drop is now
        complete.

However, note that the drag update block we invoke in (5) doesn't work if the drop animation is already more
than 90% complete. Since the lifecycle of the drop animation is distinct from that of item provider loading, if
the delay between (3) and (4) exceeds 90% of the total drop animation time, we'll fail to update the targeted
previews, such that the user only sees the initial drag preview fly on top of the caret and disappear. While we
typically win this race for data dragged from other WebKit apps, we almost always lose when dragging from Photos
and end up with a janky drop animation. This is especially true for any images that aren't locally available,
and need to be fetched from iCloud. An additional problem is that in step (5), we use the same final snapshot to
update the drop preview of every item, since we don't have a snapshot for the fragment corresponding to each
individual dropped item.

To address these issues for Mail in the case where the user drops images with known sizes (i.e. -[NSItemProvider
preferredPresentationSize] is specified), we introduce an alternate codepath for handling dropped images that
performs the drop immediately upon receiving -dropInteraction:performDrop: in the UI process. Since the data has
yet to arrive, we instead handle the drop by inserting placeholder image elements at the drag caret position,
which initially have no source but are sized to fit their expected final image sizes. After doing so, we
snapshot the page (minus the dropped content range, as usual) and deliver this snapshot to the UI process, along
with the rects (in root view coordinates) of each placeholder image that was inserted. In the UI process, we
then take this snapshot and obscure the content view with it, and also use each of the placeholder rects to
provide an updated target for each drag preview, such that the drop previews now animate to their final
locations on the page.

When the data eventually arrives, we handle the drop by detecting the placeholder elements we inserted earlier,
and using the dropped data to update the source attribute and attachment backing for each of these placeholder
elements instead of attempting to insert new content.

Note that this codepath is currently only enabled for SPI clients that set -[WKWebView _editable] to YES, since
it involves us performing the editing action for the drop (thus changing the DOM) prior to the preventable drop
event, and prior to us having any data at all. However, the drop event can't come before the editing action,
since we need to have already loaded data from the item providers to expose it via the dataTransfer of the drop
event. This contradiction means that this image placeholder hack is only for _editable SPI clients that, at the
very least, will not require preventing default behavior when dropping only images with predetermined sizes.

Covered by 2 new API tests. See comments below for more detail.

* UIProcess/WebPageProxy.h:
* UIProcess/ios/DragDropInteractionState.h:
* UIProcess/ios/DragDropInteractionState.mm:
(WebKit::DragDropInteractionState::setDefaultDropPreview):

Add a way to keep track of default drop previews that we observed during each call to
-dropInteraction:previewForDroppingItem:withDefault:. In the image placeholder drop scenario, we use these
default drop previews later on to create retargeted drop previews after the placeholders have been inserted.

(WebKit::DragDropInteractionState::defaultDropPreview const):
(WebKit::DragDropInteractionState::deliverDelayedDropPreview):

Add an alternate version of deliverDelayedDropPreview that is used when inserting image placeholders. Rather
than use text indicator data of the final dropped content on the page, use the root-view-coordinate rects of
each of the placeholder elements to reposition the default drop previews.

There's additional logic here to handle the case where the final image is taller than the height of the
unobscured content rect, in which case we clip the drop preview using UIDragPreviewParameter's visiblePath to
prevent the drop preview from being shown outside of the bounds of the web view.

* UIProcess/ios/WKContentViewInteraction.h:
* UIProcess/ios/WKContentViewInteraction.mm:
(-[WKContentView _deliverDelayedDropPreviewIfPossible:]):
(sizesOfPlaceholderElementsToInsertWhenDroppingItems):

Collects the list of expected image sizes for the dropped item providers, or an empty list in the case where
any of the item providers may not be represented as inline images or do not have predetermined sizes.

(-[WKContentView _handleDropByInsertingImagePlaceholders:session:]):

If possible, handles the drop by inserting image placeholders instead of waiting for the data to finish loading
before dropping. Returns whether or not we decided to proceed with the image placeholder drop.

(-[WKContentView dropInteraction:performDrop:]):
(-[WKContentView dropInteraction:item:willAnimateDropWithAnimator:]):

Fixes a bug where the unselected content snapshot view could linger around on the web view forever after a drop
where the data doesn't load in time for the drop to finish by keeping track of whether there is an actively
animating drag item, and only applying the unselected content snapshot if so.

(-[WKContentView dropInteraction:previewForDroppingItem:withDefault:]):

Stash the default drop preview away here.

* UIProcess/ios/WebPageProxyIOS.mm:
(WebKit::WebPageProxy::insertDroppedImagePlaceholders):
* WebProcess/WebPage/WebPage.h:
* WebProcess/WebPage/WebPage.messages.in:
* WebProcess/WebPage/ios/WebPageIOS.mm:
(WebKit::WebPage::insertDroppedImagePlaceholders):

See WebCore ChangeLog for more information.

(WebKit::WebPage::didFinishLoadingImageForElement):

If the image that finished loading is a dropped image placeholder, allow DragController to "finalize" it by
stripping away some styles that were temporarily added.

Tools:

Add a couple of new API tests to exercise the new image placeholder drop codepath, in addition to testing
infrastructure to simulate the timing of drop animation delegate calls.

* TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
* TestWebKitAPI/Tests/WebKitCocoa/WKAttachmentTests.mm:
(-[NSArray _attachmentWithName:]):
(-[TestWKWebView allBoundingClientRects:]):

Add some new API testing helper methods.

(TestWebKitAPI::targetedImageDragPreview):
(TestWebKitAPI::TEST):

Add two new tests, to:
(1) verify that images are dropped as attachment-backed placeholder image elements when the web view is editable
    and enables attachment elements, and
(2) verify that when dropping an image taller than the web view, the bottom portion of the drop preview is
    clipped using the targeted preview parameter's visiblePath.

* TestWebKitAPI/Tests/ios/DragAndDropTestsIOS.mm:
(-[NSItemProvider registerDataRepresentationForTypeIdentifier:withData:]): Deleted.
* TestWebKitAPI/cocoa/DragAndDropSimulator.h:
* TestWebKitAPI/cocoa/NSItemProviderAdditions.h: Added.
* TestWebKitAPI/cocoa/NSItemProviderAdditions.mm: Added.

Move some common helpers for registering data on a NSItemProvider to a separate file, so that it can be used in
both WKAttachmentTests and DragAndDropTests.

(-[NSItemProvider registerDataRepresentationForTypeIdentifier:withData:]):
(-[NSItemProvider registerDataRepresentationForTypeIdentifier:withData:loadingDelay:]):
* TestWebKitAPI/ios/DragAndDropSimulatorIOS.mm:
(-[DragAndDropSimulator initWithWebView:]):
(-[DragAndDropSimulator _concludeDropAndPerformOperationIfNecessary]):
(-[DragAndDropSimulator clearExternalDragInformation]):
(-[DragAndDropSimulator setExternalItemProviders:defaultDropPreviews:]):

Add a new method to allow tests to specify both a list of externally dragged item providers, as well as default
targeted previews for each of the corresponding items. These default previews are used when invoking the drop
interaction delegate's preview generation methods.

(-[DragAndDropSimulator addAnimations:]):

Not implemented yet; for now, this simply asserts.

(-[DragAndDropSimulator addCompletion:]):

Queues a completion handler, which is invoked when the drop animation for each item completes. Depending on the
value of DragAndDropSimulator's -dropAnimationTiming, this may occur either before or after handling the drop.
By default, these will be invoked after the drop completes, which represents the common case where data can be
loaded quickly relative to the drop animation.

(-[DragAndDropSimulator _invokeDropAnimationCompletionBlocksAndConcludeDrop]):
(-[DragAndDropSimulator _webView:dataInteractionOperationWasHandled:forSession:itemProviders:]):

Modified Paths

Added Paths

Diff

Modified: trunk/Source/WebCore/ChangeLog (250255 => 250256)


--- trunk/Source/WebCore/ChangeLog	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebCore/ChangeLog	2019-09-23 22:16:47 UTC (rev 250256)
@@ -1,3 +1,79 @@
+2019-09-23  Wenson Hsieh  <[email protected]>
+
+        [iOS] Drop animation when dragging images from Photos to WebKit2 Mail compose is incorrect
+        https://bugs.webkit.org/show_bug.cgi?id=201674
+        <rdar://problem/51250952>
+
+        Reviewed by Tim Horton.
+
+        Adds new helper methods on DragController to support the new image placeholder drop codepath. See WebKit
+        ChangeLog for more details.
+
+        Tests:  WKAttachmentTestsIOS.TargetedPreviewsWhenDroppingImages
+                WKAttachmentTestsIOS.TargetedPreviewIsClippedWhenDroppingTallImage
+
+        * editing/WebContentReader.h:
+
+        Fix the Windows build after including WebContentReader.h in DragController.cpp.
+
+        * html/HTMLImageElement.h:
+        (WebCore::HTMLImageElement::isDroppedImagePlaceholder const):
+        (WebCore::HTMLImageElement::setIsDroppedImagePlaceholder):
+
+        Add a flag to HTMLImageElement, indicating whether it is a dropped image placeholder. If so, we have special
+        logic to remove some temporary inline style properties from the image after it has finished loading (see
+        finalizeDroppedImagePlaceholder).
+
+        Note that this doesn't increase the size of HTMLImageElement.
+
+        * page/DragController.cpp:
+        (WebCore::DragController::dragEnded):
+
+        Clean up any stale placeholders after the drag ends.
+
+        (WebCore::DragController::performDragOperation):
+        (WebCore::DragController::removeAllDroppedImagePlaceholders):
+
+        Add a private helper to clean up any dropped image placeholders after failing to update dropped image
+        placeholders for any reason.
+
+        (WebCore::DragController::tryToUpdateDroppedImagePlaceholders):
+
+        Invoked when performing the drag operation, after image data has been loaded; this function attempts to update
+        the list of image placeholder elements tracked by DragController that were previously inserted using
+        insertDroppedImagePlaceholdersAtCaret, and updates the source attribute of each element (as well as any backed
+        attachment element, if attachment elements are enabled). It achieves this by reading the dropped data as web
+        content, and matching up the images in the resulting fragment against the placeholder images. If each image in
+        the fragment can correspond to exactly one placeholder, we update the source of each placeholder image,
+        migrate attachment elements over to the placeholder images if needed, and finally discard the fragment.
+
+        A return value of false indicates that this process failed, in which case we clean up the placeholders and fall
+        back to handling the drop normally.
+
+        (WebCore::DragController::insertDroppedImagePlaceholdersAtCaret):
+
+        Invoked when handling the drop, before any image data has been loaded; this function takes a list of sizes
+        representing the preferred presentation sizes of each item provider that will be loaded as an image, and uses
+        ReplaceSelectionCommand to insert a list of (initially blank) placeholder images at the drop caret, sized
+        accordingly to each item provider's preferredPresentationSize.
+
+        To make this compatible with Mail compose (and all other known internal clients that use the _editable SPI), we
+        additionally enforce a max-width of 100% on each image and preserve the aspect ratio of the image by adjusting
+        the height if needed.
+
+        (WebCore::DragController::finalizeDroppedImagePlaceholder):
+        * page/DragController.h:
+
+        Have DragController keep track of the list of dropped image placeholders (in DOM order), as well as the dropped
+        image placeholder range. This information is used once item provider data arrives and the drag operation is
+        being performed, to update the source of each dropped image placeholder.
+
+        (WebCore::DragController::droppedImagePlaceholders const):
+        (WebCore::DragController::droppedImagePlaceholderRange const):
+        * platform/network/mac/UTIUtilities.h:
+
+        Mark an existing helper function as WEBCORE_EXPORT.
+
 2019-09-23  Daniel Bates  <[email protected]>
 
         Improve CSP inheritance semantics

Modified: trunk/Source/WebCore/editing/WebContentReader.h (250255 => 250256)


--- trunk/Source/WebCore/editing/WebContentReader.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebCore/editing/WebContentReader.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -79,8 +79,8 @@
     bool readImage(Ref<SharedBuffer>&&, const String& type, PresentationSize preferredPresentationSize = { }) override;
     bool readURL(const URL&, const String& title) override;
     bool readDataBuffer(SharedBuffer&, const String& type, const String& name, PresentationSize preferredPresentationSize = { }) override;
+    bool readPlainText(const String&) override;
 #endif
-    bool readPlainText(const String&) override;
 };
 
 class WebContentMarkupReader final : public FrameWebContentReader {
@@ -103,8 +103,8 @@
     bool readImage(Ref<SharedBuffer>&&, const String&, PresentationSize = { }) override { return false; }
     bool readURL(const URL&, const String&) override { return false; }
     bool readDataBuffer(SharedBuffer&, const String&, const String&, PresentationSize = { }) override { return false; }
+    bool readPlainText(const String&) override { return false; }
 #endif
-    bool readPlainText(const String&) override { return false; }
 };
 
 #if PLATFORM(COCOA) && defined(__OBJC__)

Modified: trunk/Source/WebCore/html/HTMLImageElement.h (250255 => 250256)


--- trunk/Source/WebCore/html/HTMLImageElement.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebCore/html/HTMLImageElement.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -126,6 +126,9 @@
 
     bool createdByParser() const { return m_createdByParser; }
 
+    bool isDroppedImagePlaceholder() const { return m_isDroppedImagePlaceholder; }
+    void setIsDroppedImagePlaceholder() { m_isDroppedImagePlaceholder = true; }
+
 protected:
     HTMLImageElement(const QualifiedName&, Document&, HTMLFormElement* = nullptr, bool createdByParser = false);
 
@@ -189,6 +192,7 @@
     bool m_experimentalImageMenuEnabled;
     bool m_hadNameBeforeAttributeChanged { false }; // FIXME: We only need this because parseAttribute() can't see the old value.
     bool m_createdByParser { false };
+    bool m_isDroppedImagePlaceholder { false };
 
     RefPtr<EditableImageReference> m_editableImage;
     WeakPtr<HTMLPictureElement> m_pictureElement;

Modified: trunk/Source/WebCore/page/DragController.cpp (250255 => 250256)


--- trunk/Source/WebCore/page/DragController.cpp	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebCore/page/DragController.cpp	2019-09-23 22:16:47 UTC (rev 250256)
@@ -83,6 +83,7 @@
 #include "Text.h"
 #include "TextEvent.h"
 #include "VisiblePosition.h"
+#include "WebContentReader.h"
 #include "markup.h"
 
 #if ENABLE(DATA_INTERACTION)
@@ -206,6 +207,7 @@
     m_didInitiateDrag = false;
     m_documentUnderMouse = nullptr;
     clearDragCaret();
+    removeAllDroppedImagePlaceholders();
     
     m_client.dragEnded();
 }
@@ -238,6 +240,16 @@
 
 bool DragController::performDragOperation(const DragData& dragData)
 {
+    if (!m_droppedImagePlaceholders.isEmpty() && m_droppedImagePlaceholderRange && tryToUpdateDroppedImagePlaceholders(dragData)) {
+        m_droppedImagePlaceholders.clear();
+        m_droppedImagePlaceholderRange = nullptr;
+        m_documentUnderMouse = nullptr;
+        clearDragCaret();
+        return true;
+    }
+
+    removeAllDroppedImagePlaceholders();
+
     SetForScope<bool> isPerformingDrop(m_isPerformingDrop, true);
     TemporarySelectionChange ignoreSelectionChanges(m_page.focusController().focusedOrMainFrame(), WTF::nullopt, TemporarySelectionOption::IgnoreSelectionChanges);
 
@@ -1312,6 +1324,138 @@
     cleanupAfterSystemDrag();
 }
 
+void DragController::removeAllDroppedImagePlaceholders()
+{
+    m_droppedImagePlaceholderRange = nullptr;
+    for (auto& placeholder : std::exchange(m_droppedImagePlaceholders, { })) {
+        if (placeholder->isConnected())
+            placeholder->remove();
+    }
+}
+
+bool DragController::tryToUpdateDroppedImagePlaceholders(const DragData& dragData)
+{
+    ASSERT(!m_droppedImagePlaceholders.isEmpty());
+    ASSERT(m_droppedImagePlaceholderRange);
+
+    auto document = makeRef(m_droppedImagePlaceholders[0]->document());
+    auto frame = makeRefPtr(document->frame());
+    if (!frame)
+        return false;
+
+    WebContentReader reader(*frame, *m_droppedImagePlaceholderRange, true);
+    auto pasteboard = Pasteboard::createForDragAndDrop(dragData);
+    pasteboard->read(reader);
+
+    if (!reader.fragment)
+        return false;
+
+    Vector<Ref<HTMLImageElement>> imageElements;
+    for (auto& imageElement : descendantsOfType<HTMLImageElement>(*reader.fragment))
+        imageElements.append(imageElement);
+
+    if (imageElements.size() != m_droppedImagePlaceholders.size()) {
+        ASSERT_NOT_REACHED();
+        return false;
+    }
+
+    for (size_t i = 0; i < imageElements.size(); ++i) {
+        auto& imageElement = imageElements[i];
+        auto& placeholder = m_droppedImagePlaceholders[i];
+        placeholder->setAttributeWithoutSynchronization(HTMLNames::srcAttr, imageElement->attributeWithoutSynchronization(HTMLNames::srcAttr));
+#if ENABLE(ATTACHMENT_ELEMENT)
+        if (auto attachment = imageElement->attachmentElement())
+            placeholder->setAttachmentElement(attachment.releaseNonNull());
+#endif
+    }
+    return true;
+}
+
+void DragController::insertDroppedImagePlaceholdersAtCaret(const Vector<IntSize>& imageSizes)
+{
+    auto& caretController = m_page.dragCaretController();
+    if (!caretController.isContentRichlyEditable())
+        return;
+
+    auto dropCaret = caretController.caretPosition();
+    if (dropCaret.isNull())
+        return;
+
+    auto document = makeRefPtr(dropCaret.deepEquivalent().document());
+    if (!document)
+        return;
+
+    auto frame = makeRefPtr(document->frame());
+    if (!frame)
+        return;
+
+    TemporarySelectionChange selectionChange(*frame, WTF::nullopt, { TemporarySelectionOption::IgnoreSelectionChanges });
+
+    auto fragment = DocumentFragment::create(*document);
+    for (auto& size : imageSizes) {
+        ASSERT(!size.isEmpty());
+        auto image = HTMLImageElement::create(*document);
+        image->setAttributeWithoutSynchronization(HTMLNames::widthAttr, AtomString::number(size.width()));
+        image->setAttributeWithoutSynchronization(HTMLNames::heightAttr, AtomString::number(size.height()));
+        image->setInlineStyleProperty(CSSPropertyMaxWidth, 100, CSSPrimitiveValue::CSS_PERCENTAGE);
+        image->setInlineStyleProperty(CSSPropertyBackgroundColor, Color(Color::black).colorWithAlpha(0.05).cssText());
+        image->setIsDroppedImagePlaceholder();
+        fragment->appendChild(WTFMove(image));
+    }
+
+    frame->selection().setSelection(dropCaret);
+
+    auto command = ReplaceSelectionCommand::create(*document, WTFMove(fragment), { ReplaceSelectionCommand::PreventNesting, ReplaceSelectionCommand::SmartReplace }, EditAction::InsertFromDrop);
+    command->apply();
+
+    auto insertedContentRange = command->insertedContentRange();
+    if (!insertedContentRange) {
+        ASSERT_NOT_REACHED();
+        return;
+    }
+
+    auto container = makeRefPtr(insertedContentRange->commonAncestorContainer());
+    if (!is<ContainerNode>(container)) {
+        ASSERT_NOT_REACHED();
+        return;
+    }
+
+    Vector<Ref<HTMLImageElement>> placeholders;
+    for (auto& placeholder : descendantsOfType<HTMLImageElement>(downcast<ContainerNode>(*container))) {
+        auto intersectsNode = insertedContentRange->intersectsNode(placeholder);
+        if (!intersectsNode.hasException() && intersectsNode.returnValue())
+            placeholders.append(placeholder);
+    }
+
+    if (placeholders.size() != imageSizes.size()) {
+        ASSERT_NOT_REACHED();
+        return;
+    }
+
+    for (size_t i = 0; i < placeholders.size(); ++i) {
+        auto& placeholder = placeholders[i];
+        auto imageSize = imageSizes[i];
+        double clientWidth = placeholder->clientWidth();
+        double heightRespectingAspectRatio = (imageSize.height() * clientWidth) / imageSize.width();
+        placeholder->setAttributeWithoutSynchronization(HTMLNames::heightAttr, AtomString::number(heightRespectingAspectRatio));
+    }
+
+    document->updateLayout();
+
+    m_droppedImagePlaceholders = WTFMove(placeholders);
+    m_droppedImagePlaceholderRange = WTFMove(insertedContentRange);
+
+    frame->selection().clear();
+    caretController.setCaretPosition(m_droppedImagePlaceholderRange->startPosition());
+}
+
+void DragController::finalizeDroppedImagePlaceholder(HTMLImageElement& placeholder)
+{
+    ASSERT(placeholder.isDroppedImagePlaceholder());
+    placeholder.removeAttribute(HTMLNames::heightAttr);
+    placeholder.removeInlineStyleProperty(CSSPropertyBackgroundColor);
+}
+
 // Manual drag caret manipulation
 void DragController::placeDragCaret(const IntPoint& windowPoint)
 {

Modified: trunk/Source/WebCore/page/DragController.h (250255 => 250256)


--- trunk/Source/WebCore/page/DragController.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebCore/page/DragController.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -40,6 +40,7 @@
 class Element;
 class Frame;
 class FrameSelection;
+class HTMLImageElement;
 class HTMLInputElement;
 class IntRect;
 class Page;
@@ -88,6 +89,12 @@
         WEBCORE_EXPORT void dragEnded();
         
         WEBCORE_EXPORT void placeDragCaret(const IntPoint&);
+
+        const Vector<Ref<HTMLImageElement>>& droppedImagePlaceholders() const { return m_droppedImagePlaceholders; }
+        const RefPtr<Range>& droppedImagePlaceholderRange() const { return m_droppedImagePlaceholderRange; }
+
+        WEBCORE_EXPORT void finalizeDroppedImagePlaceholder(HTMLImageElement&);
+        WEBCORE_EXPORT void insertDroppedImagePlaceholdersAtCaret(const Vector<IntSize>& imageSizes);
         
         bool startDrag(Frame& src, const DragState&, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin, HasNonDefaultPasteboardData);
         static const IntSize& maxDragImageSize();
@@ -128,6 +135,9 @@
 #endif
         }
 
+        bool tryToUpdateDroppedImagePlaceholders(const DragData&);
+        void removeAllDroppedImagePlaceholders();
+
         String platformContentTypeForBlobType(const String& type) const;
 
         void cleanupAfterSystemDrag();
@@ -152,6 +162,8 @@
         IntPoint m_dragOffset;
         URL m_draggingImageURL;
         bool m_isPerformingDrop { false };
+        Vector<Ref<HTMLImageElement>> m_droppedImagePlaceholders;
+        RefPtr<Range> m_droppedImagePlaceholderRange;
     };
 
     WEBCORE_EXPORT bool isDraggableLink(const Element&);

Modified: trunk/Source/WebCore/platform/Pasteboard.h (250255 => 250256)


--- trunk/Source/WebCore/platform/Pasteboard.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebCore/platform/Pasteboard.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -144,8 +144,8 @@
     virtual bool readImage(Ref<SharedBuffer>&&, const String& type, PresentationSize preferredPresentationSize = { }) = 0;
     virtual bool readURL(const URL&, const String& title) = 0;
     virtual bool readDataBuffer(SharedBuffer&, const String& type, const String& name, PresentationSize preferredPresentationSize = { }) = 0;
+    virtual bool readPlainText(const String&) = 0;
 #endif
-    virtual bool readPlainText(const String&) = 0;
 };
 
 struct PasteboardPlainText {

Modified: trunk/Source/WebCore/platform/network/mac/UTIUtilities.h (250255 => 250256)


--- trunk/Source/WebCore/platform/network/mac/UTIUtilities.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebCore/platform/network/mac/UTIUtilities.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -30,7 +30,7 @@
 #import <wtf/RetainPtr.h>
 
 namespace WebCore {
-String MIMETypeFromUTI(const String&);
+WEBCORE_EXPORT String MIMETypeFromUTI(const String&);
 String MIMETypeFromUTITree(const String&);
 WEBCORE_EXPORT String UTIFromMIMEType(const String&);
 bool isDeclaredUTI(const String&);

Modified: trunk/Source/WebKit/ChangeLog (250255 => 250256)


--- trunk/Source/WebKit/ChangeLog	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/ChangeLog	2019-09-23 22:16:47 UTC (rev 250256)
@@ -1,3 +1,127 @@
+2019-09-23  Wenson Hsieh  <[email protected]>
+
+        [iOS] Drop animation when dragging images from Photos to WebKit2 Mail compose is incorrect
+        https://bugs.webkit.org/show_bug.cgi?id=201674
+        <rdar://problem/51250952>
+
+        Reviewed by Tim Horton.
+
+        Our current logic for handling dropped content in editable elements on iOS works like this in the ideal case:
+
+        (1)     UIKit asks us for a targeted preview for each UIDragItem. We don't know (and can't determine this
+                synchronously without blocking on the web process) so we simply retarget the preview to animate to the
+                last known caret location.
+
+        (2)     Soonafter, UIKit hands us a drop preview update block, which may be used to retarget the drop preview
+                once, as long as the drop animation is less than 90% complete. We stash these update blocks for now.
+
+        (3)     -dropInteraction:performDrop: is then called, and we start loading item provider data right away.
+
+        (4)     When the data has finished loading, we perform the drop in the web process. After any inserted images
+                have finished loading, we take snapshots (of the dropped content as well as surrounding web content
+                minus the dropped content), and deliver these images to the UI process via TextIndicatorData.
+
+        (5)     Upon receiving the TextIndicatorData sent in (4), we use the image data to create updated targeted drag
+                previews, and use these to invoke the preview update blocks we stored earlier in (2). We also obscure
+                the entire web view with a snapshot of the view minus any dropped content, such that the updated drop
+                previews may animate into place without also showing the final content.
+
+        (6)     When the drop animation ends, we remove the unselected content snapshot view added in (5) simultaneously
+                as the targeted previews disappear, revealing the actual dropped content on the page. The drop is now
+                complete.
+
+        However, note that the drag update block we invoke in (5) doesn't work if the drop animation is already more
+        than 90% complete. Since the lifecycle of the drop animation is distinct from that of item provider loading, if
+        the delay between (3) and (4) exceeds 90% of the total drop animation time, we'll fail to update the targeted
+        previews, such that the user only sees the initial drag preview fly on top of the caret and disappear. While we
+        typically win this race for data dragged from other WebKit apps, we almost always lose when dragging from Photos
+        and end up with a janky drop animation. This is especially true for any images that aren't locally available,
+        and need to be fetched from iCloud. An additional problem is that in step (5), we use the same final snapshot to
+        update the drop preview of every item, since we don't have a snapshot for the fragment corresponding to each
+        individual dropped item.
+
+        To address these issues for Mail in the case where the user drops images with known sizes (i.e. -[NSItemProvider
+        preferredPresentationSize] is specified), we introduce an alternate codepath for handling dropped images that
+        performs the drop immediately upon receiving -dropInteraction:performDrop: in the UI process. Since the data has
+        yet to arrive, we instead handle the drop by inserting placeholder image elements at the drag caret position,
+        which initially have no source but are sized to fit their expected final image sizes. After doing so, we
+        snapshot the page (minus the dropped content range, as usual) and deliver this snapshot to the UI process, along
+        with the rects (in root view coordinates) of each placeholder image that was inserted. In the UI process, we
+        then take this snapshot and obscure the content view with it, and also use each of the placeholder rects to
+        provide an updated target for each drag preview, such that the drop previews now animate to their final
+        locations on the page.
+
+        When the data eventually arrives, we handle the drop by detecting the placeholder elements we inserted earlier,
+        and using the dropped data to update the source attribute and attachment backing for each of these placeholder
+        elements instead of attempting to insert new content.
+
+        Note that this codepath is currently only enabled for SPI clients that set -[WKWebView _editable] to YES, since
+        it involves us performing the editing action for the drop (thus changing the DOM) prior to the preventable drop
+        event, and prior to us having any data at all. However, the drop event can't come before the editing action,
+        since we need to have already loaded data from the item providers to expose it via the dataTransfer of the drop
+        event. This contradiction means that this image placeholder hack is only for _editable SPI clients that, at the
+        very least, will not require preventing default behavior when dropping only images with predetermined sizes.
+
+        Covered by 2 new API tests. See comments below for more detail.
+
+        * UIProcess/WebPageProxy.h:
+        * UIProcess/ios/DragDropInteractionState.h:
+        * UIProcess/ios/DragDropInteractionState.mm:
+        (WebKit::DragDropInteractionState::setDefaultDropPreview):
+
+        Add a way to keep track of default drop previews that we observed during each call to
+        -dropInteraction:previewForDroppingItem:withDefault:. In the image placeholder drop scenario, we use these
+        default drop previews later on to create retargeted drop previews after the placeholders have been inserted.
+
+        (WebKit::DragDropInteractionState::defaultDropPreview const):
+        (WebKit::DragDropInteractionState::deliverDelayedDropPreview):
+
+        Add an alternate version of deliverDelayedDropPreview that is used when inserting image placeholders. Rather
+        than use text indicator data of the final dropped content on the page, use the root-view-coordinate rects of
+        each of the placeholder elements to reposition the default drop previews.
+
+        There's additional logic here to handle the case where the final image is taller than the height of the
+        unobscured content rect, in which case we clip the drop preview using UIDragPreviewParameter's visiblePath to
+        prevent the drop preview from being shown outside of the bounds of the web view.
+
+        * UIProcess/ios/WKContentViewInteraction.h:
+        * UIProcess/ios/WKContentViewInteraction.mm:
+        (-[WKContentView _deliverDelayedDropPreviewIfPossible:]):
+        (sizesOfPlaceholderElementsToInsertWhenDroppingItems):
+
+        Collects the list of expected image sizes for the dropped item providers, or an empty list in the case where
+        any of the item providers may not be represented as inline images or do not have predetermined sizes.
+
+        (-[WKContentView _handleDropByInsertingImagePlaceholders:session:]):
+
+        If possible, handles the drop by inserting image placeholders instead of waiting for the data to finish loading
+        before dropping. Returns whether or not we decided to proceed with the image placeholder drop.
+
+        (-[WKContentView dropInteraction:performDrop:]):
+        (-[WKContentView dropInteraction:item:willAnimateDropWithAnimator:]):
+
+        Fixes a bug where the unselected content snapshot view could linger around on the web view forever after a drop
+        where the data doesn't load in time for the drop to finish by keeping track of whether there is an actively
+        animating drag item, and only applying the unselected content snapshot if so.
+
+        (-[WKContentView dropInteraction:previewForDroppingItem:withDefault:]):
+
+        Stash the default drop preview away here.
+
+        * UIProcess/ios/WebPageProxyIOS.mm:
+        (WebKit::WebPageProxy::insertDroppedImagePlaceholders):
+        * WebProcess/WebPage/WebPage.h:
+        * WebProcess/WebPage/WebPage.messages.in:
+        * WebProcess/WebPage/ios/WebPageIOS.mm:
+        (WebKit::WebPage::insertDroppedImagePlaceholders):
+
+        See WebCore ChangeLog for more information.
+
+        (WebKit::WebPage::didFinishLoadingImageForElement):
+
+        If the image that finished loading is a dropped image placeholder, allow DragController to "finalize" it by
+        stripping away some styles that were temporarily added.
+
 2019-09-23  Alex Christensen  <[email protected]>
 
         REGRESSION(250143) Disk cache should be enabled for Safari

Modified: trunk/Source/WebKit/UIProcess/WebPageProxy.h (250255 => 250256)


--- trunk/Source/WebKit/UIProcess/WebPageProxy.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/UIProcess/WebPageProxy.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -747,6 +747,7 @@
     void didHandleAdditionalDragItemsRequest(bool added);
     void requestDragStart(const WebCore::IntPoint& clientPosition, const WebCore::IntPoint& globalPosition, WebCore::DragSourceAction allowedActions);
     void requestAdditionalItemsForDragSession(const WebCore::IntPoint& clientPosition, const WebCore::IntPoint& globalPosition, WebCore::DragSourceAction allowedActions);
+    void insertDroppedImagePlaceholders(const Vector<WebCore::IntSize>&, CompletionHandler<void(const Vector<WebCore::IntRect>&, Optional<WebCore::TextIndicatorData>)>&& reply);
     void willReceiveEditDragSnapshot();
     void didReceiveEditDragSnapshot(Optional<WebCore::TextIndicatorData>);
     void didConcludeDrop();

Modified: trunk/Source/WebKit/UIProcess/ios/DragDropInteractionState.h (250255 => 250256)


--- trunk/Source/WebKit/UIProcess/ios/DragDropInteractionState.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/UIProcess/ios/DragDropInteractionState.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -59,6 +59,11 @@
     NSInteger itemIdentifier { 0 };
 };
 
+struct ItemAndPreview {
+    RetainPtr<UIDragItem> item;
+    RetainPtr<UITargetedDragPreview> preview;
+};
+
 struct ItemAndPreviewProvider {
     RetainPtr<UIDragItem> item;
     BlockPtr<void(UITargetedDragPreview *)> provider;
@@ -98,13 +103,17 @@
     BlockPtr<void()> takeDragCancelSetDownBlock() { return WTFMove(m_dragCancelSetDownBlock); }
     BlockPtr<void(NSArray<UIDragItem *> *)> takeAddDragItemCompletionBlock() { return WTFMove(m_addDragItemCompletionBlock); }
 
+    void setDefaultDropPreview(UIDragItem *, UITargetedDragPreview *);
     void prepareForDelayedDropPreview(UIDragItem *, void(^provider)(UITargetedDragPreview *preview));
     void deliverDelayedDropPreview(UIView *contentView, UIView *previewContainer, const WebCore::TextIndicatorData&);
+    void deliverDelayedDropPreview(UIView *contentView, CGRect unobscuredContentRect, NSArray<UIDragItem *> *, const Vector<WebCore::IntRect>& placeholderRects);
     void clearAllDelayedItemPreviewProviders();
 
 private:
     void updatePreviewsForActiveDragSources();
     Optional<DragSourceState> activeDragSourceForItem(UIDragItem *) const;
+    UITargetedDragPreview *defaultDropPreview(UIDragItem *) const;
+    BlockPtr<void(UITargetedDragPreview *)> dropPreviewProvider(UIDragItem *);
 
     CGPoint m_lastGlobalPosition { CGPointZero };
     CGPoint m_adjustedPositionForDragEnd { CGPointZero };
@@ -119,6 +128,7 @@
     Optional<DragSourceState> m_stagedDragSource;
     Vector<DragSourceState> m_activeDragSources;
     Vector<ItemAndPreviewProvider> m_delayedItemPreviewProviders;
+    Vector<ItemAndPreview> m_defaultDropPreviews;
 };
 
 } // namespace WebKit

Modified: trunk/Source/WebKit/UIProcess/ios/DragDropInteractionState.mm (250255 => 250256)


--- trunk/Source/WebKit/UIProcess/ios/DragDropInteractionState.mm	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/UIProcess/ios/DragDropInteractionState.mm	2019-09-23 22:16:47 UTC (rev 250256)
@@ -23,11 +23,12 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "DragDropInteractionState.h"
+#import "config.h"
+#import "DragDropInteractionState.h"
 
 #if ENABLE(DRAG_SUPPORT) && PLATFORM(IOS_FAMILY)
 
+#import "Logging.h"
 #import <WebCore/DragItem.h>
 #import <WebCore/Image.h>
 
@@ -185,6 +186,31 @@
     updatePreviewsForActiveDragSources();
 }
 
+void DragDropInteractionState::setDefaultDropPreview(UIDragItem *item, UITargetedDragPreview *preview)
+{
+    m_defaultDropPreviews.append({ item, preview });
+}
+
+UITargetedDragPreview *DragDropInteractionState::defaultDropPreview(UIDragItem *item) const
+{
+    auto matchIndex = m_defaultDropPreviews.findMatching([&] (auto& itemAndPreview) {
+        return itemAndPreview.item == item;
+    });
+    return matchIndex == notFound ? nil : m_defaultDropPreviews[matchIndex].preview.get();
+}
+
+BlockPtr<void(UITargetedDragPreview *)> DragDropInteractionState::dropPreviewProvider(UIDragItem *item)
+{
+    auto matchIndex = m_delayedItemPreviewProviders.findMatching([&] (auto& itemAndProvider) {
+        return itemAndProvider.item == item;
+    });
+
+    if (matchIndex == notFound)
+        return nil;
+
+    return m_delayedItemPreviewProviders[matchIndex].provider;
+}
+
 void DragDropInteractionState::prepareForDelayedDropPreview(UIDragItem *item, void(^provider)(UITargetedDragPreview *preview))
 {
     m_delayedItemPreviewProviders.append({ item, provider });
@@ -202,6 +228,61 @@
     m_delayedItemPreviewProviders.clear();
 }
 
+void DragDropInteractionState::deliverDelayedDropPreview(UIView *contentView, CGRect unobscuredContentRect, NSArray<UIDragItem *> *items, const Vector<IntRect>& placeholderRects)
+{
+    if (items.count != placeholderRects.size()) {
+        RELEASE_LOG(DragAndDrop, "Failed to animate image placeholders: number of drag items (%tu) does not match number of placeholders (%tu)", items.count, placeholderRects.size());
+        clearAllDelayedItemPreviewProviders();
+        return;
+    }
+
+    for (size_t i = 0; i < placeholderRects.size(); ++i) {
+        UIDragItem *item = [items objectAtIndex:i];
+        auto& placeholderRect = placeholderRects[i];
+        auto provider = dropPreviewProvider(item);
+        if (!provider)
+            continue;
+
+        auto defaultPreview = defaultDropPreview(item);
+        auto defaultPreviewSize = [defaultPreview size];
+        if (!defaultPreview || defaultPreviewSize.width <= 0 || defaultPreviewSize.height <= 0 || placeholderRect.isEmpty()) {
+            provider(nil);
+            continue;
+        }
+
+        FloatRect previewIntersectionRect = enclosingIntRect(CGRectIntersection(unobscuredContentRect, placeholderRect));
+        if (previewIntersectionRect.isEmpty()) {
+            // If the preview rect is completely offscreen, don't bother trying to clip out or scale the default preview;
+            // simply retarget the default preview.
+            auto target = adoptNS([[UIDragPreviewTarget alloc] initWithContainer:contentView center:placeholderRect.center()]);
+            provider([defaultPreview retargetedPreviewWithTarget:target.get()]);
+            continue;
+        }
+
+        // Targeted previews don't clip to the bounds of any enclosing view; this means that when targeting previews outside
+        // the visible bounds of the content view, the preview will spill out the web view. This is most noticeable when
+        // dropping a tall image into Mail compose on iOS 13, where the bottom of the compose window is not flush against
+        // the bottom of the window. To mitigate this, we use the preview target's `visiblePath` property to clip the default
+        // drop preview's view, by the same proportion that the final placeholder image is clipped (with respect to the
+        // unobscured content rect).
+        auto previewBounds = [defaultPreview view].bounds;
+        auto insetPreviewBounds = UIEdgeInsetsInsetRect(previewBounds, {
+            (previewIntersectionRect.y() - placeholderRect.y()) / placeholderRect.height() * previewBounds.size.height,
+            (previewIntersectionRect.x() - placeholderRect.x()) / placeholderRect.width() * previewBounds.size.width,
+            (placeholderRect.maxY() - previewIntersectionRect.maxY()) / placeholderRect.height() * previewBounds.size.height,
+            (placeholderRect.maxX() - previewIntersectionRect.maxX()) / placeholderRect.width() * previewBounds.size.width
+        });
+
+        auto transform = CGAffineTransformMakeScale(placeholderRect.width() / defaultPreviewSize.width, placeholderRect.height() / defaultPreviewSize.height);
+        auto target = adoptNS([[UIDragPreviewTarget alloc] initWithContainer:contentView center:previewIntersectionRect.center() transform:transform]);
+        [defaultPreview parameters].visiblePath = [UIBezierPath bezierPathWithRect:insetPreviewBounds];
+        auto newPreview = adoptNS([[UITargetedDragPreview alloc] initWithView:[defaultPreview view] parameters:[defaultPreview parameters] target:target.get()]);
+        provider(newPreview.get());
+    }
+
+    m_delayedItemPreviewProviders.clear();
+}
+
 void DragDropInteractionState::clearAllDelayedItemPreviewProviders()
 {
     for (auto& itemAndPreviewProvider : m_delayedItemPreviewProviders)

Modified: trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.h (250255 => 250256)


--- trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -360,6 +360,7 @@
 
     BOOL _focusRequiresStrongPasswordAssistance;
     BOOL _waitingForEditDragSnapshot;
+    NSInteger _dropAnimationCount;
 
     BOOL _hasSetUpInteractions;
     NSUInteger _ignoreSelectionCommandFadeCount;

Modified: trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm (250255 => 250256)


--- trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm	2019-09-23 22:16:47 UTC (rev 250256)
@@ -93,6 +93,7 @@
 #import <WebCore/InputMode.h>
 #import <WebCore/KeyEventCodesIOS.h>
 #import <WebCore/LocalizedStrings.h>
+#import <WebCore/MIMETypeRegistry.h>
 #import <WebCore/NotImplemented.h>
 #import <WebCore/Pasteboard.h>
 #import <WebCore/Path.h>
@@ -102,6 +103,7 @@
 #import <WebCore/Scrollbar.h>
 #import <WebCore/ShareData.h>
 #import <WebCore/TextIndicator.h>
+#import <WebCore/UTIUtilities.h>
 #import <WebCore/VisibleSelection.h>
 #import <WebCore/WebEvent.h>
 #import <WebCore/WritingDirection.h>
@@ -6774,6 +6776,9 @@
     if (!unselectedSnapshotImage)
         return;
 
+    if (!_dropAnimationCount)
+        return;
+
     auto unselectedContentImageForEditDrag = adoptNS([[UIImage alloc] initWithCGImage:unselectedSnapshotImage.get() scale:_page->deviceScaleFactor() orientation:UIImageOrientationUp]);
     _unselectedContentSnapshot = adoptNS([[UIImageView alloc] initWithImage:unselectedContentImageForEditDrag.get()]);
     [_unselectedContentSnapshot setFrame:data->contentImageWithoutSelectionRectInRootViewCoordinates];
@@ -7040,6 +7045,72 @@
 
 #endif
 
+static Vector<WebCore::IntSize> sizesOfPlaceholderElementsToInsertWhenDroppingItems(NSArray<NSItemProvider *> *itemProviders)
+{
+    Vector<WebCore::IntSize> sizes;
+    for (NSItemProvider *item in itemProviders) {
+        if (!WebCore::MIMETypeRegistry::isSupportedImageMIMEType(WebCore::MIMETypeFromUTI(item.web_fileUploadContentTypes.firstObject)))
+            return { };
+
+        WebCore::IntSize presentationSize(item.preferredPresentationSize);
+        if (presentationSize.isEmpty())
+            return { };
+
+        sizes.append(WTFMove(presentationSize));
+    }
+    return sizes;
+}
+
+- (BOOL)_handleDropByInsertingImagePlaceholders:(NSArray<NSItemProvider *> *)itemProviders session:(id <UIDropSession>)session
+{
+    if (!_webView._editable)
+        return NO;
+
+    if (_dragDropInteractionState.dragSession())
+        return NO;
+
+    if (session.items.count != itemProviders.count)
+        return NO;
+
+    auto imagePlaceholderSizes = sizesOfPlaceholderElementsToInsertWhenDroppingItems(itemProviders);
+    if (imagePlaceholderSizes.isEmpty())
+        return NO;
+
+    RELEASE_LOG(DragAndDrop, "Inserting dropped image placeholders for session: %p", session);
+
+    _page->insertDroppedImagePlaceholders(imagePlaceholderSizes, [protectedSelf = retainPtr(self), dragItems = retainPtr(session.items)] (auto& placeholderRects, auto data) {
+        auto& state = protectedSelf->_dragDropInteractionState;
+        if (!data || !protectedSelf->_dropAnimationCount) {
+            RELEASE_LOG(DragAndDrop, "Failed to animate image placeholders: missing text indicator data.");
+            state.clearAllDelayedItemPreviewProviders();
+            return;
+        }
+
+        auto snapshotWithoutSelection = data->contentImageWithoutSelection;
+        if (!snapshotWithoutSelection) {
+            RELEASE_LOG(DragAndDrop, "Failed to animate image placeholders: missing unselected content image.");
+            state.clearAllDelayedItemPreviewProviders();
+            return;
+        }
+
+        auto unselectedSnapshotImage = snapshotWithoutSelection->nativeImage();
+        if (!unselectedSnapshotImage) {
+            RELEASE_LOG(DragAndDrop, "Failed to animate image placeholders: could not decode unselected content image.");
+            state.clearAllDelayedItemPreviewProviders();
+            return;
+        }
+
+        auto unselectedContentImageForEditDrag = adoptNS([[UIImage alloc] initWithCGImage:unselectedSnapshotImage.get() scale:protectedSelf->_page->deviceScaleFactor() orientation:UIImageOrientationUp]);
+        auto snapshotView = adoptNS([[UIImageView alloc] initWithImage:unselectedContentImageForEditDrag.get()]);
+        [snapshotView setFrame:data->contentImageWithoutSelectionRectInRootViewCoordinates];
+        [protectedSelf addSubview:snapshotView.get()];
+        protectedSelf->_unselectedContentSnapshot = WTFMove(snapshotView);
+        state.deliverDelayedDropPreview(protectedSelf.get(), [protectedSelf unobscuredContentRect], dragItems.get(), placeholderRects);
+    });
+
+    return YES;
+}
+
 #pragma mark - UIDragInteractionDelegate
 
 - (BOOL)_dragInteraction:(UIDragInteraction *)interaction shouldDelayCompetingGestureRecognizer:(UIGestureRecognizer *)competingGestureRecognizer
@@ -7320,6 +7391,7 @@
     [[WebItemProviderPasteboard sharedInstance] setItemProviders:itemProviders];
     [[WebItemProviderPasteboard sharedInstance] incrementPendingOperationCount];
     auto dragData = [self dragDataForDropSession:session dragDestinationAction:WKDragDestinationActionAny];
+    BOOL shouldSnapshotView = ![self _handleDropByInsertingImagePlaceholders:itemProviders session:session];
 
     RELEASE_LOG(DragAndDrop, "Loading data from %tu item providers for session: %p", itemProviders.count, session);
     // Always loading content from the item provider ensures that the web process will be allowed to call back in to the UI
@@ -7327,7 +7399,7 @@
     // or the page prevented default on `dragover`, but without this, dropping into a normal editable areas will fail due to
     // item providers not loading any data.
     RetainPtr<WKContentView> retainedSelf(self);
-    [[WebItemProviderPasteboard sharedInstance] doAfterLoadingProvidedContentIntoFileURLs:[retainedSelf, capturedDragData = WTFMove(dragData)] (NSArray *fileURLs) mutable {
+    [[WebItemProviderPasteboard sharedInstance] doAfterLoadingProvidedContentIntoFileURLs:[retainedSelf, capturedDragData = WTFMove(dragData), shouldSnapshotView] (NSArray *fileURLs) mutable {
         RELEASE_LOG(DragAndDrop, "Loaded data into %tu files", fileURLs.count);
         Vector<String> filenames;
         for (NSURL *fileURL in fileURLs)
@@ -7338,18 +7410,20 @@
         WebKit::SandboxExtension::HandleArray sandboxExtensionForUpload;
         retainedSelf->_page->createSandboxExtensionsIfNeeded(filenames, sandboxExtensionHandle, sandboxExtensionForUpload);
         retainedSelf->_page->performDragOperation(capturedDragData, "data interaction pasteboard", WTFMove(sandboxExtensionHandle), WTFMove(sandboxExtensionForUpload));
-        retainedSelf->_visibleContentViewSnapshot = [retainedSelf snapshotViewAfterScreenUpdates:NO];
-        [UIView performWithoutAnimation:[retainedSelf] {
+        if (shouldSnapshotView) {
+            retainedSelf->_visibleContentViewSnapshot = [retainedSelf snapshotViewAfterScreenUpdates:NO];
             [retainedSelf->_visibleContentViewSnapshot setFrame:[retainedSelf bounds]];
             [retainedSelf addSubview:retainedSelf->_visibleContentViewSnapshot.get()];
-        }];
+        }
     }];
 }
 
 - (void)dropInteraction:(UIDropInteraction *)interaction item:(UIDragItem *)item willAnimateDropWithAnimator:(id <UIDragAnimating>)animator
 {
+    _dropAnimationCount++;
     [animator addCompletion:[strongSelf = retainPtr(self)] (UIViewAnimatingPosition) {
-        [std::exchange(strongSelf->_unselectedContentSnapshot, nil) removeFromSuperview];
+        if (!--strongSelf->_dropAnimationCount)
+            [std::exchange(strongSelf->_unselectedContentSnapshot, nil) removeFromSuperview];
     }];
 }
 
@@ -7363,6 +7437,8 @@
 
 - (UITargetedDragPreview *)dropInteraction:(UIDropInteraction *)interaction previewForDroppingItem:(UIDragItem *)item withDefault:(UITargetedDragPreview *)defaultPreview
 {
+    _dragDropInteractionState.setDefaultDropPreview(item, defaultPreview);
+
     CGRect caretRect = _page->currentDragCaretRect();
     if (CGRectIsEmpty(caretRect))
         return nil;

Modified: trunk/Source/WebKit/UIProcess/ios/WebPageProxyIOS.mm (250255 => 250256)


--- trunk/Source/WebKit/UIProcess/ios/WebPageProxyIOS.mm	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/UIProcess/ios/WebPageProxyIOS.mm	2019-09-23 22:16:47 UTC (rev 250256)
@@ -1223,6 +1223,14 @@
         m_process->send(Messages::WebPage::RequestAdditionalItemsForDragSession(clientPosition, globalPosition, allowedActions), m_webPageID);
 }
 
+void WebPageProxy::insertDroppedImagePlaceholders(const Vector<IntSize>& imageSizes, CompletionHandler<void(const Vector<IntRect>&, Optional<WebCore::TextIndicatorData>)>&& completionHandler)
+{
+    if (hasRunningProcess())
+        m_process->connection()->sendWithAsyncReply(Messages::WebPage::InsertDroppedImagePlaceholders(imageSizes), WTFMove(completionHandler), m_webPageID);
+    else
+        completionHandler({ }, WTF::nullopt);
+}
+
 void WebPageProxy::willReceiveEditDragSnapshot()
 {
     pageClient().willReceiveEditDragSnapshot();

Modified: trunk/Source/WebKit/WebProcess/WebPage/WebPage.h (250255 => 250256)


--- trunk/Source/WebKit/WebProcess/WebPage/WebPage.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/WebProcess/WebPage/WebPage.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -1289,6 +1289,7 @@
 #if PLATFORM(IOS_FAMILY) && ENABLE(DATA_INTERACTION)
     void requestDragStart(const WebCore::IntPoint& clientPosition, const WebCore::IntPoint& globalPosition, uint64_t allowedActions);
     void requestAdditionalItemsForDragSession(const WebCore::IntPoint& clientPosition, const WebCore::IntPoint& globalPosition, uint64_t allowedActions);
+    void insertDroppedImagePlaceholders(const Vector<WebCore::IntSize>&, CompletionHandler<void(const Vector<WebCore::IntRect>&, Optional<WebCore::TextIndicatorData>)>&& reply);
     void computeAndSendEditDragSnapshot();
 #endif
 

Modified: trunk/Source/WebKit/WebProcess/WebPage/WebPage.messages.in (250255 => 250256)


--- trunk/Source/WebKit/WebProcess/WebPage/WebPage.messages.in	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/WebProcess/WebPage/WebPage.messages.in	2019-09-23 22:16:47 UTC (rev 250256)
@@ -311,6 +311,7 @@
 #if PLATFORM(IOS_FAMILY) && ENABLE(DRAG_SUPPORT)
     RequestDragStart(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t allowedActions)
     RequestAdditionalItemsForDragSession(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t allowedActions)
+    InsertDroppedImagePlaceholders(Vector<WebCore::IntSize> imageSize) -> (Vector<WebCore::IntRect> dropPreviewRects, Optional<WebCore::TextIndicatorData> textIndicator) Async
     DidConcludeDrop()
 #endif
 

Modified: trunk/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm (250255 => 250256)


--- trunk/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm	2019-09-23 22:16:47 UTC (rev 250256)
@@ -894,6 +894,40 @@
     send(Messages::WebPageProxy::DidHandleAdditionalDragItemsRequest(didHandleDrag));
 }
 
+void WebPage::insertDroppedImagePlaceholders(const Vector<IntSize>& imageSizes, CompletionHandler<void(const Vector<IntRect>&, Optional<WebCore::TextIndicatorData>)>&& reply)
+{
+    m_page->dragController().insertDroppedImagePlaceholdersAtCaret(imageSizes);
+    auto placeholderRects = m_page->dragController().droppedImagePlaceholders().map([&] (auto& element) {
+        return rootViewBoundsForElement(element);
+    });
+
+    auto imagePlaceholderRange = m_page->dragController().droppedImagePlaceholderRange();
+    if (placeholderRects.size() != imageSizes.size()) {
+        RELEASE_LOG(DragAndDrop, "Failed to insert dropped image placeholders: placeholder rect count (%tu) does not match image size count (%tu).", placeholderRects.size(), imageSizes.size());
+        reply({ }, WTF::nullopt);
+        return;
+    }
+
+    if (!imagePlaceholderRange) {
+        RELEASE_LOG(DragAndDrop, "Failed to insert dropped image placeholders: no image placeholder range.");
+        reply({ }, WTF::nullopt);
+        return;
+    }
+
+    Optional<TextIndicatorData> textIndicatorData;
+    OptionSet<TextIndicatorOption> textIndicatorOptions = {
+        TextIndicatorOptionIncludeSnapshotOfAllVisibleContentWithoutSelection,
+        TextIndicatorOptionExpandClipBeyondVisibleRect,
+        TextIndicatorOptionPaintAllContent,
+        TextIndicatorOptionUseSelectionRectForSizing
+    };
+
+    if (auto textIndicator = TextIndicator::createWithRange(*imagePlaceholderRange, textIndicatorOptions.toRaw(), TextIndicatorPresentationTransition::None, { }))
+        textIndicatorData = textIndicator->data();
+
+    reply(WTFMove(placeholderRects), WTFMove(textIndicatorData));
+}
+
 void WebPage::didConcludeDrop()
 {
     m_rangeForDropSnapshot = nullptr;
@@ -923,6 +957,9 @@
 
 void WebPage::didFinishLoadingImageForElement(WebCore::HTMLImageElement& element)
 {
+    if (element.isDroppedImagePlaceholder())
+        m_page->dragController().finalizeDroppedImagePlaceholder(element);
+
     if (m_pendingImageElementsForDropSnapshot.isEmpty())
         return;
 

Modified: trunk/Tools/ChangeLog (250255 => 250256)


--- trunk/Tools/ChangeLog	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Tools/ChangeLog	2019-09-23 22:16:47 UTC (rev 250256)
@@ -1,3 +1,65 @@
+2019-09-23  Wenson Hsieh  <[email protected]>
+
+        [iOS] Drop animation when dragging images from Photos to WebKit2 Mail compose is incorrect
+        https://bugs.webkit.org/show_bug.cgi?id=201674
+        <rdar://problem/51250952>
+
+        Reviewed by Tim Horton.
+
+        Add a couple of new API tests to exercise the new image placeholder drop codepath, in addition to testing
+        infrastructure to simulate the timing of drop animation delegate calls.
+
+        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+        * TestWebKitAPI/Tests/WebKitCocoa/WKAttachmentTests.mm:
+        (-[NSArray _attachmentWithName:]):
+        (-[TestWKWebView allBoundingClientRects:]):
+
+        Add some new API testing helper methods.
+
+        (TestWebKitAPI::targetedImageDragPreview):
+        (TestWebKitAPI::TEST):
+
+        Add two new tests, to:
+        (1) verify that images are dropped as attachment-backed placeholder image elements when the web view is editable
+            and enables attachment elements, and
+        (2) verify that when dropping an image taller than the web view, the bottom portion of the drop preview is
+            clipped using the targeted preview parameter's visiblePath.
+
+        * TestWebKitAPI/Tests/ios/DragAndDropTestsIOS.mm:
+        (-[NSItemProvider registerDataRepresentationForTypeIdentifier:withData:]): Deleted.
+        * TestWebKitAPI/cocoa/DragAndDropSimulator.h:
+        * TestWebKitAPI/cocoa/NSItemProviderAdditions.h: Added.
+        * TestWebKitAPI/cocoa/NSItemProviderAdditions.mm: Added.
+
+        Move some common helpers for registering data on a NSItemProvider to a separate file, so that it can be used in
+        both WKAttachmentTests and DragAndDropTests.
+
+        (-[NSItemProvider registerDataRepresentationForTypeIdentifier:withData:]):
+        (-[NSItemProvider registerDataRepresentationForTypeIdentifier:withData:loadingDelay:]):
+        * TestWebKitAPI/ios/DragAndDropSimulatorIOS.mm:
+        (-[DragAndDropSimulator initWithWebView:]):
+        (-[DragAndDropSimulator _concludeDropAndPerformOperationIfNecessary]):
+        (-[DragAndDropSimulator clearExternalDragInformation]):
+        (-[DragAndDropSimulator setExternalItemProviders:defaultDropPreviews:]):
+
+        Add a new method to allow tests to specify both a list of externally dragged item providers, as well as default
+        targeted previews for each of the corresponding items. These default previews are used when invoking the drop
+        interaction delegate's preview generation methods.
+
+        (-[DragAndDropSimulator addAnimations:]):
+
+        Not implemented yet; for now, this simply asserts.
+
+        (-[DragAndDropSimulator addCompletion:]):
+
+        Queues a completion handler, which is invoked when the drop animation for each item completes. Depending on the
+        value of DragAndDropSimulator's -dropAnimationTiming, this may occur either before or after handling the drop.
+        By default, these will be invoked after the drop completes, which represents the common case where data can be
+        loaded quickly relative to the drop animation.
+
+        (-[DragAndDropSimulator _invokeDropAnimationCompletionBlocksAndConcludeDrop]):
+        (-[DragAndDropSimulator _webView:dataInteractionOperationWasHandled:forSession:itemProviders:]):
+
 2019-09-23  Jonathan Bedard  <[email protected]>
 
         results.webkit.org: Collapse results with the same version name (Follow-up fix)

Modified: trunk/Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj (250255 => 250256)


--- trunk/Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj	2019-09-23 22:16:47 UTC (rev 250256)
@@ -1029,6 +1029,7 @@
 		F4E0A2B42122402B00AF7C7F /* image-and-file-upload.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = F4E0A2B321223F2D00AF7C7F /* image-and-file-upload.html */; };
 		F4E0A2B82122847400AF7C7F /* TestFilePromiseReceiver.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4E0A2B72122847400AF7C7F /* TestFilePromiseReceiver.mm */; };
 		F4E3D80820F70BB9007B58C5 /* significant-text-milestone-article.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = F4E3D80720F708E4007B58C5 /* significant-text-milestone-article.html */; };
+		F4EB4E912328AC3000574DAB /* NSItemProviderAdditions.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4EB4E902328AC3000574DAB /* NSItemProviderAdditions.mm */; };
 		F4F137921D9B683E002BEC57 /* large-video-test-now-playing.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = F4F137911D9B6832002BEC57 /* large-video-test-now-playing.html */; };
 		F4F405BC1D4C0D1C007A9707 /* full-size-autoplaying-video-with-audio.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = F4F405BA1D4C0CF8007A9707 /* full-size-autoplaying-video-with-audio.html */; };
 		F4F405BD1D4C0D1C007A9707 /* skinny-autoplaying-video-with-audio.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = F4F405BB1D4C0CF8007A9707 /* skinny-autoplaying-video-with-audio.html */; };
@@ -2527,6 +2528,8 @@
 		F4E0A2B62122847400AF7C7F /* TestFilePromiseReceiver.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TestFilePromiseReceiver.h; sourceTree = "<group>"; };
 		F4E0A2B72122847400AF7C7F /* TestFilePromiseReceiver.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = TestFilePromiseReceiver.mm; sourceTree = "<group>"; };
 		F4E3D80720F708E4007B58C5 /* significant-text-milestone-article.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = "significant-text-milestone-article.html"; sourceTree = "<group>"; };
+		F4EB4E8F2328AC3000574DAB /* NSItemProviderAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = NSItemProviderAdditions.h; path = cocoa/NSItemProviderAdditions.h; sourceTree = SOURCE_ROOT; };
+		F4EB4E902328AC3000574DAB /* NSItemProviderAdditions.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = NSItemProviderAdditions.mm; path = cocoa/NSItemProviderAdditions.mm; sourceTree = SOURCE_ROOT; };
 		F4F137911D9B6832002BEC57 /* large-video-test-now-playing.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = "large-video-test-now-playing.html"; sourceTree = "<group>"; };
 		F4F405BA1D4C0CF8007A9707 /* full-size-autoplaying-video-with-audio.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = "full-size-autoplaying-video-with-audio.html"; sourceTree = "<group>"; };
 		F4F405BB1D4C0CF8007A9707 /* skinny-autoplaying-video-with-audio.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = "skinny-autoplaying-video-with-audio.html"; sourceTree = "<group>"; };
@@ -2834,6 +2837,8 @@
 				CD2D0D19213465560018C784 /* NowPlaying.mm */,
 				2ECFF5541D9B12F800B55394 /* NowPlayingControlsTests.mm */,
 				A10F047C1E3AD29C00C95E19 /* NSFileManagerExtras.mm */,
+				F4EB4E8F2328AC3000574DAB /* NSItemProviderAdditions.h */,
+				F4EB4E902328AC3000574DAB /* NSItemProviderAdditions.mm */,
 				37A22AA51DCAA27200AFBFC4 /* ObservedRenderingProgressEventsAfterCrash.mm */,
 				CEA6CF2219CCF5BD0064F5A7 /* OpenAndCloseWindow.mm */,
 				CEBCA12E1E3A660100C73293 /* OverrideContentSecurityPolicy.mm */,
@@ -4633,6 +4638,7 @@
 				2ECFF5551D9B12F800B55394 /* NowPlayingControlsTests.mm in Sources */,
 				A10F047E1E3AD29C00C95E19 /* NSFileManagerExtras.mm in Sources */,
 				F442851D2140DF2900CCDA22 /* NSFontPanelTesting.mm in Sources */,
+				F4EB4E912328AC3000574DAB /* NSItemProviderAdditions.mm in Sources */,
 				37A22AA71DCAA27200AFBFC4 /* ObservedRenderingProgressEventsAfterCrash.mm in Sources */,
 				2D70059921EDA4D0003463CB /* OffscreenWindow.mm in Sources */,
 				7CCE7F251A411AF600447C4C /* OpenAndCloseWindow.mm in Sources */,

Modified: trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/WKAttachmentTests.mm (250255 => 250256)


--- trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/WKAttachmentTests.mm	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/WKAttachmentTests.mm	2019-09-23 22:16:47 UTC (rev 250256)
@@ -28,6 +28,7 @@
 #if PLATFORM(MAC) || PLATFORM(IOS)
 
 #import "DragAndDropSimulator.h"
+#import "NSItemProviderAdditions.h"
 #import "PencilKitTestSPI.h"
 #import "PlatformUtilities.h"
 #import "TestNavigationDelegate.h"
@@ -53,6 +54,21 @@
 SOFT_LINK_CLASS(MapKit, MKMapItem)
 SOFT_LINK_CLASS(MapKit, MKPlacemark)
 
+@interface NSArray (AttachmentTestingHelpers)
+- (_WKAttachment *)_attachmentWithName:(NSString *)name;
+@end
+
+@implementation NSArray (AttachmentTestingHelpers)
+- (_WKAttachment *)_attachmentWithName:(NSString *)name
+{
+    for (_WKAttachment *attachment in self) {
+        if ([attachment.info.name isEqualToString:name])
+            return attachment;
+    }
+    return nil;
+}
+@end
+
 #define USES_MODERN_ATTRIBUTED_STRING_CONVERSION ((PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000) || PLATFORM(MAC))
 
 @interface AttachmentUpdateObserver : NSObject <WKUIDelegatePrivate>
@@ -271,6 +287,25 @@
     return attachment.autorelease();
 }
 
+- (NSArray<NSValue *> *)allBoundingClientRects:(NSString *)querySelector
+{
+    auto rects = adoptNS([[NSMutableArray alloc] init]);
+    bool doneEvaluatingScript = false;
+    NSString *script = [NSString stringWithFormat:@"Array.from(document.querySelectorAll('%@')).map(e => { const r = e.getBoundingClientRect(); return [r.left, r.top, r.width, r.height]; })", querySelector];
+    [self evaluateJavaScript:script completionHandler:[rects, &doneEvaluatingScript] (NSArray<NSArray<NSNumber *> *> *result, NSError *) {
+        for (NSArray<NSNumber *> *rectInfo in result) {
+#if PLATFORM(IOS_FAMILY)
+            [rects addObject:[NSValue valueWithCGRect:CGRectMake(rectInfo[0].floatValue, rectInfo[1].floatValue, rectInfo[2].floatValue, rectInfo[3].floatValue)]];
+#else
+            [rects addObject:[NSValue valueWithRect:NSMakeRect(rectInfo[0].floatValue, rectInfo[1].floatValue, rectInfo[2].floatValue, rectInfo[3].floatValue)]];
+#endif
+        }
+        doneEvaluatingScript = true;
+    }];
+    TestWebKitAPI::Util::run(&doneEvaluatingScript);
+    return rects.autorelease();
+}
+
 - (CGPoint)attachmentElementMidPoint
 {
     __block CGPoint midPoint;
@@ -1650,6 +1685,90 @@
 
 #if PLATFORM(IOS_FAMILY)
 
+static RetainPtr<UITargetedDragPreview> targetedImageDragPreview(WKWebView *webView, NSData *imageData, CGSize size)
+{
+    auto imageView = adoptNS([[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]]);
+    [imageView setBounds:CGRectMake(0, 0, size.width, size.height)];
+    auto defaultDropTarget = adoptNS([[UIDragPreviewTarget alloc] initWithContainer:webView center:CGPointMake(450, 450)]);
+    auto parameters = adoptNS([[UIDragPreviewParameters alloc] init]);
+    return adoptNS([[UITargetedDragPreview alloc] initWithView:imageView.get() parameters:parameters.get() target:defaultDropTarget.get()]);
+}
+
+TEST(WKAttachmentTestsIOS, TargetedPreviewsWhenDroppingImages)
+{
+    auto webView = webViewForTestingAttachments();
+    [webView _setEditable:YES];
+
+    auto simulator = adoptNS([[DragAndDropSimulator alloc] initWithWebView:webView.get()]);
+
+    // The first item preview should be scaled down by a factor of 2.
+    auto firstPreview = targetedImageDragPreview(webView.get(), testImageData(), CGSizeMake(430, 348));
+    auto firstItem = adoptNS([[NSItemProvider alloc] init]);
+    [firstItem registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypePNG withData:testImageData() loadingDelay:0.5];
+    [firstItem setPreferredPresentationSize:CGSizeMake(215, 174)];
+    [firstItem setSuggestedName:@"icon"];
+
+    // The second item preview should be scaled up by a factor of 2.
+    auto secondPreview = targetedImageDragPreview(webView.get(), testGIFData(), CGSizeMake(26, 32));
+    auto secondItem = adoptNS([[NSItemProvider alloc] init]);
+    [secondItem registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeGIF withData:testGIFData() loadingDelay:0.5];
+    [secondItem setPreferredPresentationSize:CGSizeMake(52, 64)];
+    [secondItem setSuggestedName:@"apple"];
+
+    [simulator setDropAnimationTiming:DropAnimationShouldFinishBeforeHandlingDrop];
+    [simulator setExternalItemProviders:[NSArray arrayWithObjects:firstItem.get(), secondItem.get(), nil] defaultDropPreviews:[NSArray arrayWithObjects:firstPreview.get(), secondPreview.get(), nil]];
+    [simulator runFrom:CGPointMake(0, 0) to:CGPointMake(450, 450)];
+
+    EXPECT_EQ([simulator delayedDropPreviews].count, 2U);
+    UITargetedDragPreview *firstDelayedPreview = [simulator delayedDropPreviews].firstObject;
+    UITargetedDragPreview *secondDelayedPreview = [simulator delayedDropPreviews].lastObject;
+    auto imageElementBounds = retainPtr([webView allBoundingClientRects:@"IMG"]);
+
+    EXPECT_TRUE(CGAffineTransformEqualToTransform(CGAffineTransformMakeScale(0.5, 0.5), firstDelayedPreview.target.transform));
+    EXPECT_TRUE(CGRectEqualToRect(CGRectMake(0, 0, 430, 348), firstDelayedPreview.parameters.visiblePath.bounds));
+    EXPECT_TRUE(CGRectContainsPoint([imageElementBounds firstObject].CGRectValue, firstDelayedPreview.target.center));
+
+    EXPECT_TRUE(CGAffineTransformEqualToTransform(CGAffineTransformMakeScale(2, 2), secondDelayedPreview.target.transform));
+    EXPECT_TRUE(CGRectEqualToRect(CGRectMake(0, 0, 26, 32), secondDelayedPreview.parameters.visiblePath.bounds));
+    EXPECT_TRUE(CGRectContainsPoint([imageElementBounds lastObject].CGRectValue, secondDelayedPreview.target.center));
+
+    [webView expectElementCount:2 querySelector:@"IMG"];
+    _WKAttachment *pngAttachment = [[simulator insertedAttachments] _attachmentWithName:@"icon.png"];
+    _WKAttachment *gifAttachment = [[simulator insertedAttachments] _attachmentWithName:@"apple.gif"];
+    EXPECT_WK_STREQ(pngAttachment.info.contentType, @"image/png");
+    EXPECT_WK_STREQ(gifAttachment.info.contentType, @"image/gif");
+}
+
+TEST(WKAttachmentTestsIOS, TargetedPreviewIsClippedWhenDroppingTallImage)
+{
+    auto webView = webViewForTestingAttachments(CGSizeMake(800, 200));
+    [webView stringByEvaluatingJavaScript:@"document.body.style.margin = '0'"];
+    [webView _setEditable:YES];
+
+    auto imageData = retainPtr([NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"400x400-green" withExtension:@"png" subdirectory:@"TestWebKitAPI.resources"]]);
+    auto simulator = adoptNS([[DragAndDropSimulator alloc] initWithWebView:webView.get()]);
+
+    auto preview = targetedImageDragPreview(webView.get(), imageData.get(), CGSizeMake(100, 100));
+    auto item = adoptNS([[NSItemProvider alloc] init]);
+    [item registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypePNG withData:imageData.get() loadingDelay:0.5];
+    [item setPreferredPresentationSize:CGSizeMake(400, 400)];
+    [item setSuggestedName:@"green"];
+
+    [simulator setDropAnimationTiming:DropAnimationShouldFinishBeforeHandlingDrop];
+    [simulator setExternalItemProviders:[NSArray arrayWithObject:item.get()] defaultDropPreviews:[NSArray arrayWithObject:preview.get()]];
+    [simulator runFrom:CGPointMake(0, 0) to:CGPointMake(350, 350)];
+
+    EXPECT_EQ([simulator delayedDropPreviews].count, 1U);
+    UITargetedDragPreview *delayedPreview = [simulator delayedDropPreviews].firstObject;
+    EXPECT_TRUE(CGAffineTransformEqualToTransform(CGAffineTransformMakeScale(4, 4), delayedPreview.target.transform));
+    EXPECT_TRUE(CGRectEqualToRect(CGRectMake(0, 0, 100, 50), delayedPreview.parameters.visiblePath.bounds));
+    EXPECT_TRUE(CGPointEqualToPoint(CGPointMake(200, 100), delayedPreview.target.center));
+
+    [webView expectElementCount:1 querySelector:@"IMG"];
+    _WKAttachment *attachment = [[simulator insertedAttachments] _attachmentWithName:@"green.png"];
+    EXPECT_WK_STREQ(attachment.info.contentType, @"image/png");
+}
+
 TEST(WKAttachmentTestsIOS, InsertDroppedImageAsAttachment)
 {
     auto webView = webViewForTestingAttachments();

Modified: trunk/Tools/TestWebKitAPI/Tests/ios/DragAndDropTestsIOS.mm (250255 => 250256)


--- trunk/Tools/TestWebKitAPI/Tests/ios/DragAndDropTestsIOS.mm	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Tools/TestWebKitAPI/Tests/ios/DragAndDropTestsIOS.mm	2019-09-23 22:16:47 UTC (rev 250256)
@@ -29,6 +29,7 @@
 
 #import "ClassMethodSwizzler.h"
 #import "DragAndDropSimulator.h"
+#import "NSItemProviderAdditions.h"
 #import "PlatformUtilities.h"
 #import "TestWKWebView.h"
 #import "UIKitSPI.h"
@@ -53,10 +54,6 @@
 SOFT_LINK_CLASS(MapKit, MKMapItem)
 SOFT_LINK_CLASS(MapKit, MKPlacemark)
 
-typedef void (^FileLoadCompletionBlock)(NSURL *, BOOL, NSError *);
-typedef void (^DataLoadCompletionBlock)(NSData *, NSError *);
-typedef void (^NSItemProviderDataLoadCompletionBlock)(NSData *, NSError *);
-
 #if !USE(APPLE_INTERNAL_SDK)
 
 @interface NSItemProviderRepresentationOptions : NSObject
@@ -81,19 +78,6 @@
     return [NSData dataWithContentsOfURL:zipFileURL];
 }
 
-@implementation NSItemProvider (DragAndDropTests)
-
-- (void)registerDataRepresentationForTypeIdentifier:(NSString *)typeIdentifier withData:(NSData *)data
-{
-    RetainPtr<NSData> retainedData = data;
-    [self registerDataRepresentationForTypeIdentifier:typeIdentifier visibility:NSItemProviderRepresentationVisibilityAll loadHandler: [retainedData] (DataLoadCompletionBlock block) -> NSProgress * {
-        block(retainedData.get(), nil);
-        return [NSProgress discreteProgressWithTotalUnitCount:100];
-    }];
-}
-
-@end
-
 @implementation TestWKWebView (DragAndDropTests)
 
 - (BOOL)editorContainsImageElement
@@ -997,7 +981,7 @@
     NSString *textPayload = @"Ceci n'est pas une string";
     auto simulator = adoptNS([[DragAndDropSimulator alloc] initWithWebView:webView.get()]);
     auto simulatedItemProvider = adoptNS([[NSItemProvider alloc] init]);
-    [simulatedItemProvider registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(NSItemProviderDataLoadCompletionBlock completionBlock)
+    [simulatedItemProvider registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(DataLoadCompletionBlock completionBlock)
     {
         completionBlock([textPayload dataUsingEncoding:NSUTF8StringEncoding], nil);
         return [NSProgress discreteProgressWithTotalUnitCount:100];
@@ -1017,7 +1001,7 @@
 
     auto simulator = adoptNS([[DragAndDropSimulator alloc] initWithWebView:webView.get()]);
     auto simulatedItemProvider = adoptNS([[NSItemProvider alloc] init]);
-    [simulatedItemProvider registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeJPEG visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(NSItemProviderDataLoadCompletionBlock completionBlock)
+    [simulatedItemProvider registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeJPEG visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(DataLoadCompletionBlock completionBlock)
     {
         completionBlock(UIImageJPEGRepresentation(testIconImage(), 0.5), nil);
         return [NSProgress discreteProgressWithTotalUnitCount:100];
@@ -1313,7 +1297,7 @@
     [webView stringByEvaluatingJavaScript:@"getSelection().removeAllRanges()"];
 
     auto simulatedItemProvider = adoptNS([[NSItemProvider alloc] init]);
-    [simulatedItemProvider registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(NSItemProviderDataLoadCompletionBlock completionBlock)
+    [simulatedItemProvider registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(DataLoadCompletionBlock completionBlock)
     {
         completionBlock([@"Hello world" dataUsingEncoding:NSUTF8StringEncoding], nil);
         return [NSProgress discreteProgressWithTotalUnitCount:100];
@@ -1336,7 +1320,7 @@
     [webView stringByEvaluatingJavaScript:@"getSelection().removeAllRanges()"];
 
     auto simulatedItemProvider = adoptNS([[NSItemProvider alloc] init]);
-    [simulatedItemProvider registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(NSItemProviderDataLoadCompletionBlock completionBlock)
+    [simulatedItemProvider registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(DataLoadCompletionBlock completionBlock)
     {
         completionBlock([@"Hello world" dataUsingEncoding:NSUTF8StringEncoding], nil);
         return [NSProgress discreteProgressWithTotalUnitCount:100];
@@ -1581,7 +1565,7 @@
 
     WebItemProviderPasteboard *pasteboard = [WebItemProviderPasteboard sharedInstance];
     auto fastItem = adoptNS([[NSItemProvider alloc] init]);
-    [fastItem registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(NSItemProviderDataLoadCompletionBlock completionBlock)
+    [fastItem registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(DataLoadCompletionBlock completionBlock)
     {
         completionBlock([fastString dataUsingEncoding:NSUTF8StringEncoding], nil);
         return nil;
@@ -1588,7 +1572,7 @@
     }];
 
     auto slowItem = adoptNS([[NSItemProvider alloc] init]);
-    [slowItem registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(NSItemProviderDataLoadCompletionBlock completionBlock)
+    [slowItem registerDataRepresentationForTypeIdentifier:(__bridge NSString *)kUTTypeUTF8PlainText visibility:NSItemProviderRepresentationVisibilityAll loadHandler:^NSProgress *(DataLoadCompletionBlock completionBlock)
     {
         sleep(2_s);
         completionBlock([slowString dataUsingEncoding:NSUTF8StringEncoding], nil);

Modified: trunk/Tools/TestWebKitAPI/cocoa/DragAndDropSimulator.h (250255 => 250256)


--- trunk/Tools/TestWebKitAPI/cocoa/DragAndDropSimulator.h	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Tools/TestWebKitAPI/cocoa/DragAndDropSimulator.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -47,6 +47,11 @@
     DragAndDropPhasePerformingDrop = 4
 };
 
+typedef NS_ENUM(NSInteger, DropAnimationTiming) {
+    DropAnimationShouldFinishAfterHandlingDrop,
+    DropAnimationShouldFinishBeforeHandlingDrop
+};
+
 typedef NSDictionary<NSNumber *, NSValue *> *ProgressToCGPointValueMap;
 
 @interface MockDragDropSession : NSObject <UIDragDropSession> {
@@ -91,6 +96,7 @@
 - (instancetype)initWithWebView:(TestWKWebView *)webView;
 - (void)runFrom:(CGPoint)startLocation to:(CGPoint)endLocation additionalItemRequestLocations:(ProgressToCGPointValueMap)additionalItemRequestLocations;
 - (void)ensureInputSession;
+- (void)setExternalItemProviders:(NSArray<NSItemProvider *> *)itemProviders defaultDropPreviews:(NSArray<UITargetedDragPreview *> *)previews;
 
 @property (nonatomic, readonly) DragAndDropPhase phase;
 @property (nonatomic) BOOL allowsFocusToStartInputSession;
@@ -115,6 +121,7 @@
 @property (nonatomic, readonly) NSArray<UITargetedDragPreview *> *cancellationPreviews;
 @property (nonatomic, readonly) NSArray *dropPreviews;
 @property (nonatomic, readonly) NSArray *delayedDropPreviews;
+@property (nonatomic) DropAnimationTiming dropAnimationTiming;
 
 #endif // PLATFORM(IOS_FAMILY)
 

Added: trunk/Tools/TestWebKitAPI/cocoa/NSItemProviderAdditions.h (0 => 250256)


--- trunk/Tools/TestWebKitAPI/cocoa/NSItemProviderAdditions.h	                        (rev 0)
+++ trunk/Tools/TestWebKitAPI/cocoa/NSItemProviderAdditions.h	2019-09-23 22:16:47 UTC (rev 250256)
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2019 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#import <Foundation/Foundation.h>
+
+typedef void (^FileLoadCompletionBlock)(NSURL *, BOOL, NSError *);
+typedef void (^DataLoadCompletionBlock)(NSData *, NSError *);
+
+@interface NSItemProvider (NSItemProviderAdditions)
+- (void)registerDataRepresentationForTypeIdentifier:(NSString *)typeIdentifier withData:(NSData *)data;
+- (void)registerDataRepresentationForTypeIdentifier:(NSString *)typeIdentifier withData:(NSData *)data loadingDelay:(NSTimeInterval)delay;
+@end

Added: trunk/Tools/TestWebKitAPI/cocoa/NSItemProviderAdditions.mm (0 => 250256)


--- trunk/Tools/TestWebKitAPI/cocoa/NSItemProviderAdditions.mm	                        (rev 0)
+++ trunk/Tools/TestWebKitAPI/cocoa/NSItemProviderAdditions.mm	2019-09-23 22:16:47 UTC (rev 250256)
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2019 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "config.h"
+#import "NSItemProviderAdditions.h"
+
+#import <wtf/BlockPtr.h>
+#import <wtf/RetainPtr.h>
+
+@implementation NSItemProvider (NSItemProviderAdditions)
+
+- (void)registerDataRepresentationForTypeIdentifier:(NSString *)typeIdentifier withData:(NSData *)data
+{
+    [self registerDataRepresentationForTypeIdentifier:typeIdentifier withData:data loadingDelay:0];
+}
+
+- (void)registerDataRepresentationForTypeIdentifier:(NSString *)typeIdentifier withData:(NSData *)data loadingDelay:(NSTimeInterval)delay
+{
+    auto retainedData = retainPtr(data);
+    [self registerDataRepresentationForTypeIdentifier:typeIdentifier visibility:NSItemProviderRepresentationVisibilityAll loadHandler: [retainedData, delay] (DataLoadCompletionBlock block) -> NSProgress * {
+        if (delay > 0) {
+            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), [block = makeBlockPtr(block), retainedData] {
+                block(retainedData.get(), nil);
+            });
+        } else
+            block(retainedData.get(), nil);
+        return [NSProgress discreteProgressWithTotalUnitCount:100];
+    }];
+}
+
+@end

Modified: trunk/Tools/TestWebKitAPI/ios/DragAndDropSimulatorIOS.mm (250255 => 250256)


--- trunk/Tools/TestWebKitAPI/ios/DragAndDropSimulatorIOS.mm	2019-09-23 21:56:43 UTC (rev 250255)
+++ trunk/Tools/TestWebKitAPI/ios/DragAndDropSimulatorIOS.mm	2019-09-23 22:16:47 UTC (rev 250256)
@@ -296,6 +296,9 @@
 
 @end
 
+@interface DragAndDropSimulator () <UIDragAnimating>
+@end
+
 @implementation DragAndDropSimulator {
     RetainPtr<TestWKWebView> _webView;
     RetainPtr<MockDragSession> _dragSession;
@@ -314,6 +317,7 @@
     RetainPtr<NSMutableArray<UITargetedDragPreview *>> _cancellationPreviews;
     RetainPtr<NSMutableArray> _dropPreviews;
     RetainPtr<NSMutableArray> _delayedDropPreviews;
+    RetainPtr<NSMutableArray> _defaultDropPreviewsForExternalItems;
 
     RetainPtr<NSMutableArray<_WKAttachment *>> _insertedAttachments;
     RetainPtr<NSMutableArray<_WKAttachment *>> _removedAttachments;
@@ -332,6 +336,7 @@
     BlockPtr<UIDropOperation(UIDropOperation, id)> _overrideDragUpdateBlock;
     BlockPtr<void(BOOL, NSArray *)> _dropCompletionBlock;
     BlockPtr<void()> _sessionWillBeginBlock;
+    Vector<BlockPtr<void(UIViewAnimatingPosition)>> _dropAnimationCompletionBlocks;
 }
 
 - (instancetype)initWithWebViewFrame:(CGRect)frame
@@ -354,6 +359,7 @@
         _shouldEnsureUIApplication = NO;
         _shouldBecomeFirstResponder = YES;
         _shouldAllowMoveOperation = YES;
+        _dropAnimationTiming = DropAnimationShouldFinishAfterHandlingDrop;
         [_webView setUIDelegate:self];
         [_webView _setInputDelegate:self];
         self.dragDestinationAction = WKDragDestinationActionAny & ~WKDragDestinationActionLoad;
@@ -480,8 +486,16 @@
         NSInteger dropPreviewIndex = 0;
         __block NSUInteger numberOfPendingPreviews = [_dropSession items].count;
         _isDoneWaitingForDelayedDropPreviews = !numberOfPendingPreviews;
+        BOOL canUseDefaultDropPreviewsForExternalItems = [_defaultDropPreviewsForExternalItems count] == [_dropSession items].count;
         for (UIDragItem *item in [_dropSession items]) {
-            auto defaultPreview = adoptNS([[UITargetedDragPreview alloc] initWithView:_webView.get()]);
+            RetainPtr<UITargetedDragPreview> defaultPreview;
+            if (canUseDefaultDropPreviewsForExternalItems)
+                defaultPreview = [_defaultDropPreviewsForExternalItems objectAtIndex:dropPreviewIndex];
+            else {
+                // Just fall back to an arbitrary non-null drag preview if the test didn't specify one.
+                defaultPreview = adoptNS([[UITargetedDragPreview alloc] initWithView:_webView.get()]);
+            }
+
             id <UIDropInteractionDelegate_Staging_31075005> delegate = (id <UIDropInteractionDelegate_Staging_31075005>)[_webView dropInteractionDelegate];
             UIDropInteraction *interaction = [_webView dropInteraction];
             [_dropPreviews addObject:[delegate dropInteraction:interaction previewForDroppingItem:item withDefault:defaultPreview.get()] ?: NSNull.null];
@@ -497,6 +511,18 @@
         }
         [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] performDrop:_dropSession.get()];
         _phase = DragAndDropPhasePerformingDrop;
+
+        for (UIDragItem *item in [_dropSession items])
+            [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] item:item willAnimateDropWithAnimator:self];
+
+        if (_dropAnimationTiming == DropAnimationShouldFinishBeforeHandlingDrop) {
+            [_webView evaluateJavaScript:@"" completionHandler:^(id, NSError *) {
+                // We need to at least ensure one round trip to the web process and back, to ensure that the UI process will have received any image placeholders
+                // that were just inserted as a result of performing the drop. However, this is guaranteed to run before the UI process receives the drop completion
+                // message, since item provider loading is asynchronous.
+                [self _invokeDropAnimationCompletionBlocksAndConcludeDrop];
+            }];
+        }
     } else {
         _isDoneWithCurrentRun = true;
         _phase = DragAndDropPhaseCancelled;
@@ -639,6 +665,7 @@
 - (void)clearExternalDragInformation
 {
     _externalItemProviders = nil;
+    _defaultDropPreviewsForExternalItems = nil;
 }
 
 - (CGPoint)_currentLocation
@@ -669,6 +696,13 @@
     _externalItemProviders = adoptNS([externalItemProviders copy]);
 }
 
+- (void)setExternalItemProviders:(NSArray<NSItemProvider *> *)itemProviders defaultDropPreviews:(NSArray<UITargetedDragPreview *> *)previews
+{
+    ASSERT(itemProviders.count == previews.count);
+    self.externalItemProviders = itemProviders;
+    _defaultDropPreviewsForExternalItems = adoptNS(previews.copy);
+}
+
 - (DragAndDropPhase)phase
 {
     return _phase;
@@ -784,6 +818,25 @@
     return _sessionWillBeginBlock.get();
 }
 
+- (void)addAnimations:(void (^)())animations
+{
+    // This is not implemented by the drag-and-drop simulator yet, since WebKit doesn't make use of
+    // "alongside" animations during drop.
+    ASSERT_NOT_REACHED();
+}
+
+- (void)addCompletion:(void (^)(UIViewAnimatingPosition))completion
+{
+    _dropAnimationCompletionBlocks.append(makeBlockPtr(completion));
+}
+
+- (void)_invokeDropAnimationCompletionBlocksAndConcludeDrop
+{
+    for (auto block : std::exchange(_dropAnimationCompletionBlocks, { }))
+        block(UIViewAnimatingPositionEnd);
+    [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] concludeDrop:_dropSession.get()];
+}
+
 #pragma mark - WKUIDelegatePrivate
 
 - (void)_webView:(WKWebView *)webView dataInteraction:(UIDragInteraction *)interaction sessionWillBegin:(id <UIDragSession>)session
@@ -797,8 +850,13 @@
     if (self.dropCompletionBlock)
         self.dropCompletionBlock(handled, itemProviders);
 
+    if (_dropAnimationTiming == DropAnimationShouldFinishBeforeHandlingDrop) {
+        _isDoneWithCurrentRun = true;
+        return;
+    }
+
     [_webView _doAfterReceivingEditDragSnapshotForTesting:^{
-        [[_webView dropInteractionDelegate] dropInteraction:[_webView dropInteraction] concludeDrop:_dropSession.get()];
+        [self _invokeDropAnimationCompletionBlocksAndConcludeDrop];
         _isDoneWithCurrentRun = true;
     }];
 }
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to