2 * Copyright (C) 2007-2016 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "DragController.h"
29 #include "HTMLAnchorElement.h"
30 #include "SVGAElement.h"
32 #if ENABLE(DRAG_SUPPORT)
33 #include "CachedImage.h"
34 #include "CachedResourceLoader.h"
35 #include "DataTransfer.h"
37 #include "DocumentFragment.h"
38 #include "DragActions.h"
39 #include "DragClient.h"
41 #include "DragImage.h"
42 #include "DragState.h"
45 #include "EditorClient.h"
46 #include "ElementAncestorIterator.h"
47 #include "EventHandler.h"
49 #include "FloatRect.h"
50 #include "FocusController.h"
51 #include "FrameLoadRequest.h"
52 #include "FrameLoader.h"
53 #include "FrameSelection.h"
54 #include "FrameView.h"
55 #include "HTMLAttachmentElement.h"
56 #include "HTMLImageElement.h"
57 #include "HTMLInputElement.h"
58 #include "HTMLParserIdioms.h"
59 #include "HTMLPlugInElement.h"
60 #include "HitTestRequest.h"
61 #include "HitTestResult.h"
63 #include "ImageOrientation.h"
64 #include "MainFrame.h"
65 #include "MoveSelectionCommand.h"
67 #include "Pasteboard.h"
68 #include "PlatformKeyboardEvent.h"
69 #include "PluginDocument.h"
70 #include "PluginViewBase.h"
72 #include "PromisedBlobInfo.h"
73 #include "RenderAttachment.h"
74 #include "RenderFileUploadControl.h"
75 #include "RenderImage.h"
76 #include "RenderView.h"
77 #include "ReplaceSelectionCommand.h"
78 #include "ResourceRequest.h"
79 #include "SecurityOrigin.h"
81 #include "ShadowRoot.h"
82 #include "StyleProperties.h"
84 #include "TextEvent.h"
85 #include "VisiblePosition.h"
88 #if ENABLE(DATA_INTERACTION)
89 #include "SelectionRect.h"
92 #include <wtf/CurrentTime.h>
93 #include <wtf/RefPtr.h>
94 #include <wtf/SetForScope.h>
97 #if ENABLE(DATA_DETECTION)
98 #include "DataDetection.h"
103 bool isDraggableLink(const Element& element)
105 if (is<HTMLAnchorElement>(element)) {
106 auto& anchorElement = downcast<HTMLAnchorElement>(element);
107 if (!anchorElement.isLiveLink())
109 #if ENABLE(DATA_DETECTION)
110 return !DataDetection::isDataDetectorURL(anchorElement.href());
115 if (is<SVGAElement>(element))
116 return element.isLink();
120 #if ENABLE(DRAG_SUPPORT)
122 static PlatformMouseEvent createMouseEvent(const DragData& dragData)
124 bool shiftKey = false;
125 bool ctrlKey = false;
127 bool metaKey = false;
129 PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
131 return PlatformMouseEvent(dragData.clientPosition(), dragData.globalPosition(),
132 LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
133 metaKey, WallTime::now(), ForceAtClick, NoTap);
136 DragController::DragController(Page& page, DragClient& client)
139 , m_numberOfItemsToBeAccepted(0)
140 , m_dragHandlingMethod(DragHandlingMethod::None)
141 , m_dragDestinationAction(DragDestinationActionNone)
142 , m_dragSourceAction(DragSourceActionNone)
143 , m_didInitiateDrag(false)
144 , m_sourceDragOperation(DragOperationNone)
148 DragController::~DragController()
150 m_client.dragControllerDestroyed();
153 static RefPtr<DocumentFragment> documentFragmentFromDragData(const DragData& dragData, Frame& frame, Range& context, bool allowPlainText, bool& chosePlainText)
155 chosePlainText = false;
157 Document& document = context.ownerDocument();
158 if (dragData.containsCompatibleContent()) {
159 if (auto fragment = frame.editor().webContentFromPasteboard(*Pasteboard::createForDragAndDrop(dragData), context, allowPlainText, chosePlainText))
162 if (dragData.containsURL(DragData::DoNotConvertFilenames)) {
164 String url = dragData.asURL(DragData::DoNotConvertFilenames, &title);
165 if (!url.isEmpty()) {
166 auto anchor = HTMLAnchorElement::create(document);
167 anchor->setHref(url);
168 if (title.isEmpty()) {
169 // Try the plain text first because the url might be normalized or escaped.
170 if (dragData.containsPlainText())
171 title = dragData.asPlainText();
175 anchor->appendChild(document.createTextNode(title));
176 auto fragment = document.createDocumentFragment();
177 fragment->appendChild(anchor);
178 return WTFMove(fragment);
182 if (allowPlainText && dragData.containsPlainText()) {
183 chosePlainText = true;
184 return createFragmentFromText(context, dragData.asPlainText()).ptr();
192 DragOperation DragController::platformGenericDragOperation()
194 return DragOperationMove;
199 bool DragController::dragIsMove(FrameSelection& selection, const DragData& dragData)
201 const VisibleSelection& visibleSelection = selection.selection();
202 return m_documentUnderMouse == m_dragInitiator && visibleSelection.isContentEditable() && visibleSelection.isRange() && !isCopyKeyDown(dragData);
205 void DragController::clearDragCaret()
207 m_page.dragCaretController().clear();
210 void DragController::dragEnded()
212 m_dragInitiator = nullptr;
213 m_didInitiateDrag = false;
214 m_documentUnderMouse = nullptr;
217 m_client.dragEnded();
220 DragOperation DragController::dragEntered(const DragData& dragData)
222 return dragEnteredOrUpdated(dragData);
225 void DragController::dragExited(const DragData& dragData)
227 auto& mainFrame = m_page.mainFrame();
228 if (mainFrame.view())
229 mainFrame.eventHandler().cancelDragAndDrop(createMouseEvent(dragData), Pasteboard::createForDragAndDrop(dragData), dragData.draggingSourceOperationMask(), dragData.containsFiles());
230 mouseMovedIntoDocument(nullptr);
231 if (m_fileInputElementUnderMouse)
232 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
233 m_fileInputElementUnderMouse = nullptr;
236 DragOperation DragController::dragUpdated(const DragData& dragData)
238 return dragEnteredOrUpdated(dragData);
241 inline static bool dragIsHandledByDocument(DragController::DragHandlingMethod dragHandlingMethod)
243 if (dragHandlingMethod == DragController::DragHandlingMethod::None)
246 if (dragHandlingMethod == DragController::DragHandlingMethod::PageLoad)
252 bool DragController::performDragOperation(const DragData& dragData)
254 SetForScope<bool> isPerformingDrop(m_isPerformingDrop, true);
255 TemporarySelectionChange ignoreSelectionChanges(m_page.focusController().focusedOrMainFrame(), std::nullopt, TemporarySelectionOptionIgnoreSelectionChanges);
257 m_documentUnderMouse = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
259 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = ShouldOpenExternalURLsPolicy::ShouldNotAllow;
260 if (m_documentUnderMouse)
261 shouldOpenExternalURLsPolicy = m_documentUnderMouse->shouldOpenExternalURLsPolicyToPropagate();
263 if ((m_dragDestinationAction & DragDestinationActionDHTML) && dragIsHandledByDocument(m_dragHandlingMethod)) {
264 m_client.willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
265 Ref<MainFrame> mainFrame(m_page.mainFrame());
266 bool preventedDefault = false;
267 if (mainFrame->view())
268 preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), Pasteboard::createForDragAndDrop(dragData), dragData.draggingSourceOperationMask(), dragData.containsFiles());
269 if (preventedDefault) {
271 m_documentUnderMouse = nullptr;
276 if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
277 m_client.didConcludeEditDrag();
278 m_documentUnderMouse = nullptr;
283 m_documentUnderMouse = nullptr;
286 if (operationForLoad(dragData) == DragOperationNone)
289 auto urlString = dragData.asURL();
290 if (urlString.isEmpty())
293 m_client.willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
294 m_page.mainFrame().loader().load(FrameLoadRequest(m_page.mainFrame(), { urlString }, shouldOpenExternalURLsPolicy));
298 void DragController::mouseMovedIntoDocument(Document* newDocument)
300 if (m_documentUnderMouse == newDocument)
303 // If we were over another document clear the selection
304 if (m_documentUnderMouse)
306 m_documentUnderMouse = newDocument;
309 DragOperation DragController::dragEnteredOrUpdated(const DragData& dragData)
311 mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(dragData.clientPosition()));
313 m_dragDestinationAction = dragData.dragDestinationAction();
314 if (m_dragDestinationAction == DragDestinationActionNone) {
315 clearDragCaret(); // FIXME: Why not call mouseMovedIntoDocument(nullptr)?
316 return DragOperationNone;
319 DragOperation dragOperation = DragOperationNone;
320 m_dragHandlingMethod = tryDocumentDrag(dragData, m_dragDestinationAction, dragOperation);
321 if (m_dragHandlingMethod == DragHandlingMethod::None && (m_dragDestinationAction & DragDestinationActionLoad)) {
322 dragOperation = operationForLoad(dragData);
323 if (dragOperation != DragOperationNone)
324 m_dragHandlingMethod = DragHandlingMethod::PageLoad;
327 updateSupportedTypeIdentifiersForDragHandlingMethod(m_dragHandlingMethod, dragData);
328 return dragOperation;
331 static HTMLInputElement* asFileInput(Node& node)
333 if (!is<HTMLInputElement>(node))
336 auto* inputElement = &downcast<HTMLInputElement>(node);
338 // If this is a button inside of the a file input, move up to the file input.
339 if (inputElement->isTextButton() && is<ShadowRoot>(inputElement->treeScope().rootNode())) {
340 auto& host = *downcast<ShadowRoot>(inputElement->treeScope().rootNode()).host();
341 inputElement = is<HTMLInputElement>(host) ? &downcast<HTMLInputElement>(host) : nullptr;
344 return inputElement && inputElement->isFileUpload() ? inputElement : nullptr;
347 // This can return null if an empty document is loaded.
348 static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
350 Frame* frame = documentUnderMouse->frame();
351 float zoomFactor = frame ? frame->pageZoomFactor() : 1;
352 LayoutPoint point(p.x() * zoomFactor, p.y() * zoomFactor);
354 HitTestResult result(point);
355 documentUnderMouse->renderView()->hitTest(HitTestRequest(), result);
357 Node* node = result.innerNode();
358 while (node && !is<Element>(*node))
359 node = node->parentNode();
361 node = node->deprecatedShadowAncestorNode();
363 return downcast<Element>(node);
366 #if !ENABLE(DATA_INTERACTION)
368 void DragController::updateSupportedTypeIdentifiersForDragHandlingMethod(DragHandlingMethod, const DragData&) const
374 DragController::DragHandlingMethod DragController::tryDocumentDrag(const DragData& dragData, DragDestinationAction actionMask, DragOperation& dragOperation)
376 if (!m_documentUnderMouse)
377 return DragHandlingMethod::None;
379 if (m_dragInitiator && !m_documentUnderMouse->securityOrigin().canReceiveDragData(m_dragInitiator->securityOrigin()))
380 return DragHandlingMethod::None;
382 bool isHandlingDrag = false;
383 if (actionMask & DragDestinationActionDHTML) {
384 isHandlingDrag = tryDHTMLDrag(dragData, dragOperation);
385 // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
386 // tryDHTMLDrag fires dragenter event. The event listener that listens
387 // to this event may create a nested message loop (open a modal dialog),
388 // which could process dragleave event and reset m_documentUnderMouse in
390 if (!m_documentUnderMouse)
391 return DragHandlingMethod::None;
394 // It's unclear why this check is after tryDHTMLDrag.
395 // We send drag events in tryDHTMLDrag and that may be the reason.
396 RefPtr<FrameView> frameView = m_documentUnderMouse->view();
398 return DragHandlingMethod::None;
400 if (isHandlingDrag) {
402 return DragHandlingMethod::NonDefault;
405 if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
406 if (dragData.containsColor()) {
407 dragOperation = DragOperationGeneric;
408 return DragHandlingMethod::SetColor;
411 IntPoint point = frameView->windowToContents(dragData.clientPosition());
412 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
414 return DragHandlingMethod::None;
416 HTMLInputElement* elementAsFileInput = asFileInput(*element);
417 if (m_fileInputElementUnderMouse != elementAsFileInput) {
418 if (m_fileInputElementUnderMouse)
419 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
420 m_fileInputElementUnderMouse = elementAsFileInput;
423 if (!m_fileInputElementUnderMouse)
424 m_page.dragCaretController().setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
428 Frame* innerFrame = element->document().frame();
429 dragOperation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
430 m_numberOfItemsToBeAccepted = 0;
432 unsigned numberOfFiles = dragData.numberOfFiles();
433 if (m_fileInputElementUnderMouse) {
434 if (m_fileInputElementUnderMouse->isDisabledFormControl())
435 m_numberOfItemsToBeAccepted = 0;
436 else if (m_fileInputElementUnderMouse->multiple())
437 m_numberOfItemsToBeAccepted = numberOfFiles;
438 else if (numberOfFiles > 1)
439 m_numberOfItemsToBeAccepted = 0;
441 m_numberOfItemsToBeAccepted = 1;
443 if (!m_numberOfItemsToBeAccepted)
444 dragOperation = DragOperationNone;
445 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(m_numberOfItemsToBeAccepted);
447 // We are not over a file input element. The dragged item(s) will only
448 // be loaded into the view the number of dragged items is 1.
449 m_numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
452 if (m_fileInputElementUnderMouse)
453 return DragHandlingMethod::UploadFile;
455 if (m_page.dragCaretController().isContentRichlyEditable())
456 return DragHandlingMethod::EditRichText;
458 return DragHandlingMethod::EditPlainText;
461 // We are not over an editable region. Make sure we're clearing any prior drag cursor.
463 if (m_fileInputElementUnderMouse)
464 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
465 m_fileInputElementUnderMouse = nullptr;
466 return DragHandlingMethod::None;
469 DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
471 m_dragSourceAction = m_client.dragSourceActionMaskForPoint(rootViewPoint);
472 return m_dragSourceAction;
475 DragOperation DragController::operationForLoad(const DragData& dragData)
477 Document* document = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
479 bool pluginDocumentAcceptsDrags = false;
481 if (is<PluginDocument>(document)) {
482 const Widget* widget = downcast<PluginDocument>(*document).pluginWidget();
483 const PluginViewBase* pluginView = is<PluginViewBase>(widget) ? downcast<PluginViewBase>(widget) : nullptr;
486 pluginDocumentAcceptsDrags = pluginView->shouldAllowNavigationFromDrags();
489 if (document && (m_didInitiateDrag || (is<PluginDocument>(*document) && !pluginDocumentAcceptsDrags) || document->hasEditableStyle()))
490 return DragOperationNone;
491 return dragOperation(dragData);
494 static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
496 Ref<Frame> protector(*frame);
497 frame->selection().setSelection(dragCaret);
498 if (frame->selection().selection().isNone()) {
499 dragCaret = frame->visiblePositionForPoint(point);
500 frame->selection().setSelection(dragCaret);
501 range = dragCaret.toNormalizedRange();
503 return !frame->selection().isNone() && frame->selection().selection().isContentEditable();
506 bool DragController::dispatchTextInputEventFor(Frame* innerFrame, const DragData& dragData)
508 ASSERT(m_page.dragCaretController().hasCaret());
509 String text = m_page.dragCaretController().isContentRichlyEditable() ? emptyString() : dragData.asPlainText();
510 Element* target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
511 // FIXME: What guarantees target is not null?
512 auto event = TextEvent::createForDrop(innerFrame->document()->domWindow(), text);
513 target->dispatchEvent(event);
514 return !event->defaultPrevented();
517 bool DragController::concludeEditDrag(const DragData& dragData)
519 RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
520 if (m_fileInputElementUnderMouse) {
521 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
522 m_fileInputElementUnderMouse = nullptr;
525 if (!m_documentUnderMouse)
528 IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData.clientPosition());
529 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
532 RefPtr<Frame> innerFrame = element->document().frame();
535 if (m_page.dragCaretController().hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
538 if (dragData.containsColor()) {
539 Color color = dragData.asColor();
540 if (!color.isValid())
542 RefPtr<Range> innerRange = innerFrame->selection().toNormalizedRange();
545 RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
546 style->setProperty(CSSPropertyColor, color.serialized(), false);
547 if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
549 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
550 innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
554 if (dragData.containsFiles() && fileInput) {
555 // fileInput should be the element we hit tested for, unless it was made
556 // display:none in a drop event handler.
557 ASSERT(fileInput == element || !fileInput->renderer());
558 if (fileInput->isDisabledFormControl())
561 return fileInput->receiveDroppedFiles(dragData);
564 if (!m_page.dragController().canProcessDrag(dragData))
567 VisibleSelection dragCaret = m_page.dragCaretController().caretPosition();
568 RefPtr<Range> range = dragCaret.toNormalizedRange();
569 RefPtr<Element> rootEditableElement = innerFrame->selection().selection().rootEditableElement();
571 // For range to be null a WebKit client must have done something bad while
572 // manually controlling drag behaviour
576 ResourceCacheValidationSuppressor validationSuppressor(range->ownerDocument().cachedResourceLoader());
577 auto& editor = innerFrame->editor();
578 bool isMove = dragIsMove(innerFrame->selection(), dragData);
579 if (isMove || dragCaret.isContentRichlyEditable()) {
580 bool chosePlainText = false;
581 RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, *innerFrame, *range, true, chosePlainText);
582 if (!fragment || !editor.shouldInsertFragment(*fragment, range.get(), EditorInsertAction::Dropped))
585 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
587 if (editor.client() && editor.client()->performTwoStepDrop(*fragment, *range, isMove))
591 // NSTextView behavior is to always smart delete on moving a selection,
592 // but only to smart insert if the selection granularity is word granularity.
593 bool smartDelete = editor.smartInsertDeleteEnabled();
594 bool smartInsert = smartDelete && innerFrame->selection().granularity() == WordGranularity && dragData.canSmartReplace();
595 MoveSelectionCommand::create(fragment.releaseNonNull(), dragCaret.base(), smartInsert, smartDelete)->apply();
597 if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
598 ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
599 if (dragData.canSmartReplace())
600 options |= ReplaceSelectionCommand::SmartReplace;
602 options |= ReplaceSelectionCommand::MatchStyle;
603 ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment.releaseNonNull(), options, EditActionInsertFromDrop)->apply();
607 String text = dragData.asPlainText();
608 if (text.isEmpty() || !editor.shouldInsertText(text, range.get(), EditorInsertAction::Dropped))
611 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
612 RefPtr<DocumentFragment> fragment = createFragmentFromText(*range, text);
616 if (editor.client() && editor.client()->performTwoStepDrop(*fragment, *range, isMove))
619 if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
620 ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment.get(), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting, EditActionInsertFromDrop)->apply();
623 if (rootEditableElement) {
624 if (Frame* frame = rootEditableElement->document().frame())
625 frame->eventHandler().updateDragStateAfterEditDragIfNeeded(*rootEditableElement);
631 bool DragController::canProcessDrag(const DragData& dragData)
633 IntPoint point = m_page.mainFrame().view()->windowToContents(dragData.clientPosition());
634 HitTestResult result = HitTestResult(point);
635 if (!m_page.mainFrame().contentRenderer())
638 result = m_page.mainFrame().eventHandler().hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
640 if (!result.innerNonSharedNode())
643 DragData::DraggingPurpose dragPurpose = DragData::DraggingPurpose::ForEditing;
644 if (asFileInput(*result.innerNonSharedNode()))
645 dragPurpose = DragData::DraggingPurpose::ForFileUpload;
647 if (!dragData.containsCompatibleContent(dragPurpose))
650 if (dragPurpose == DragData::DraggingPurpose::ForFileUpload)
653 if (is<HTMLPlugInElement>(*result.innerNonSharedNode())) {
654 if (!downcast<HTMLPlugInElement>(result.innerNonSharedNode())->canProcessDrag() && !result.innerNonSharedNode()->hasEditableStyle())
656 } else if (!result.innerNonSharedNode()->hasEditableStyle())
659 if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
665 static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
667 // This is designed to match IE's operation fallback for the case where
668 // the page calls preventDefault() in a drag event but doesn't set dropEffect.
669 if (srcOpMask == DragOperationEvery)
670 return DragOperationCopy;
671 if (srcOpMask == DragOperationNone)
672 return DragOperationNone;
673 if (srcOpMask & DragOperationMove)
674 return DragOperationMove;
675 if (srcOpMask & DragOperationGeneric)
676 return DragController::platformGenericDragOperation();
677 if (srcOpMask & DragOperationCopy)
678 return DragOperationCopy;
679 if (srcOpMask & DragOperationLink)
680 return DragOperationLink;
682 // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
683 return DragOperationGeneric;
686 bool DragController::tryDHTMLDrag(const DragData& dragData, DragOperation& operation)
688 ASSERT(m_documentUnderMouse);
689 Ref<MainFrame> mainFrame(m_page.mainFrame());
690 RefPtr<FrameView> viewProtector = mainFrame->view();
694 DragOperation sourceOperation = dragData.draggingSourceOperationMask();
695 auto targetResponse = mainFrame->eventHandler().updateDragAndDrop(createMouseEvent(dragData), [&dragData]() { return Pasteboard::createForDragAndDrop(dragData); }, sourceOperation, dragData.containsFiles());
696 if (!targetResponse.accept)
699 if (!targetResponse.operation)
700 operation = defaultOperationForDrag(sourceOperation);
701 else if (!(sourceOperation & targetResponse.operation.value())) // The element picked an operation which is not supported by the source
702 operation = DragOperationNone;
704 operation = targetResponse.operation.value();
709 static bool imageElementIsDraggable(const HTMLImageElement& image, const Frame& sourceFrame)
711 if (sourceFrame.settings().loadsImagesAutomatically())
714 auto* renderer = image.renderer();
715 if (!is<RenderImage>(renderer))
718 auto* cachedImage = downcast<RenderImage>(*renderer).cachedImage();
719 return cachedImage && !cachedImage->errorOccurred() && cachedImage->imageForRenderer(renderer);
722 Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
724 state.type = (sourceFrame->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
727 #if ENABLE(ATTACHMENT_ELEMENT)
728 if (is<HTMLAttachmentElement>(startElement)) {
729 auto selection = sourceFrame->selection().selection();
730 bool isSingleAttachmentSelection = selection.start() == Position(startElement, Position::PositionIsBeforeAnchor) && selection.end() == Position(startElement, Position::PositionIsAfterAnchor);
731 bool isAttachmentElementInCurrentSelection = false;
732 if (auto selectedRange = selection.toNormalizedRange()) {
733 auto compareResult = selectedRange->compareNode(*startElement);
734 isAttachmentElementInCurrentSelection = !compareResult.hasException() && compareResult.releaseReturnValue() == Range::NODE_INSIDE;
737 if (!isAttachmentElementInCurrentSelection || isSingleAttachmentSelection) {
738 state.type = DragSourceActionAttachment;
744 for (auto* element = startElement; element; element = element->parentOrShadowHostElement()) {
745 auto* renderer = element->renderer();
749 EUserDrag dragMode = renderer->style().userDrag();
750 if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
751 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
754 if (dragMode == DRAG_AUTO) {
755 if ((m_dragSourceAction & DragSourceActionImage)
756 && is<HTMLImageElement>(*element)
757 && imageElementIsDraggable(downcast<HTMLImageElement>(*element), *sourceFrame)) {
758 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
761 if ((m_dragSourceAction & DragSourceActionLink) && isDraggableLink(*element)) {
762 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
765 #if ENABLE(ATTACHMENT_ELEMENT)
766 if ((m_dragSourceAction & DragSourceActionAttachment)
767 && is<HTMLAttachmentElement>(*element)
768 && downcast<HTMLAttachmentElement>(*element).file()) {
769 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionAttachment);
776 // We either have nothing to drag or we have a selection and we're not over a draggable element.
777 return (state.type & DragSourceActionSelection) ? startElement : nullptr;
780 static CachedImage* getCachedImage(Element& element)
782 RenderObject* renderer = element.renderer();
783 if (!is<RenderImage>(renderer))
785 auto& image = downcast<RenderImage>(*renderer);
786 return image.cachedImage();
789 static Image* getImage(Element& element)
791 CachedImage* cachedImage = getCachedImage(element);
792 // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
793 // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
794 // which would be empty when asking the cached BitmapImages.
795 return (cachedImage && !cachedImage->errorOccurred()) ?
796 cachedImage->image() : nullptr;
799 static void selectElement(Element& element)
801 RefPtr<Range> range = element.document().createRange();
802 range->selectNode(element);
803 element.document().frame()->selection().setSelection(VisibleSelection(*range, DOWNSTREAM));
806 static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
808 // dragImageOffset is the cursor position relative to the lower-left corner of the image.
810 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
811 const int yOffset = dragImageOffset.y();
813 const int yOffset = -dragImageOffset.y();
817 return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
819 return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
822 static FloatPoint dragImageAnchorPointForSelectionDrag(Frame& frame, const IntPoint& mouseDraggedPoint)
824 IntRect draggingRect = enclosingIntRect(frame.selection().selectionBounds());
826 float x = (mouseDraggedPoint.x() - draggingRect.x()) / (float)draggingRect.width();
827 float y = (mouseDraggedPoint.y() - draggingRect.y()) / (float)draggingRect.height();
829 return FloatPoint { x, y };
832 static IntPoint dragLocForSelectionDrag(Frame& src)
834 IntRect draggingRect = enclosingIntRect(src.selection().selectionBounds());
835 int xpos = draggingRect.maxX();
836 xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
837 int ypos = draggingRect.maxY();
839 // Deal with flipped coordinates on Mac
840 ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
842 ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
844 return IntPoint(xpos, ypos);
847 bool DragController::startDrag(Frame& src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin, HasNonDefaultPasteboardData hasData)
849 if (!src.view() || !src.contentRenderer() || !state.source)
852 Ref<Frame> protector(src);
853 HitTestResult hitTestResult = src.eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
855 // FIXME(136836): Investigate whether all elements should use the containsIncludingShadowDOM() path here.
856 bool includeShadowDOM = false;
858 includeShadowDOM = state.source->isMediaElement();
860 bool sourceContainsHitNode;
861 if (!includeShadowDOM)
862 sourceContainsHitNode = state.source->contains(hitTestResult.innerNode());
864 sourceContainsHitNode = state.source->containsIncludingShadowDOM(hitTestResult.innerNode());
866 if (!sourceContainsHitNode) {
867 // The original node being dragged isn't under the drag origin anymore... maybe it was
868 // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
869 // something that's not actually under the drag origin.
873 URL linkURL = hitTestResult.absoluteLinkURL();
874 URL imageURL = hitTestResult.absoluteImageURL();
876 IntPoint mouseDraggedPoint = src.view()->windowToContents(dragEvent.position());
878 m_draggingImageURL = URL();
879 m_sourceDragOperation = srcOp;
882 IntPoint dragLoc(0, 0);
883 IntPoint dragImageOffset(0, 0);
885 ASSERT(state.dataTransfer);
887 DataTransfer& dataTransfer = *state.dataTransfer;
888 if (state.type == DragSourceActionDHTML) {
889 dragImage = DragImage { dataTransfer.createDragImage(dragImageOffset) };
890 // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
891 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
893 dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
894 m_dragOffset = dragImageOffset;
898 if (state.type == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty()) {
899 // Selection, image, and link drags receive a default set of allowed drag operations that
901 // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
902 m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
905 ASSERT(state.source);
906 Element& element = *state.source;
908 bool mustUseLegacyDragClient = hasData == HasNonDefaultPasteboardData::Yes || m_client.useLegacyDragClient();
910 IntRect dragImageBounds;
911 Image* image = getImage(element);
912 if (state.type == DragSourceActionSelection) {
913 PasteboardWriterData pasteboardWriterData;
915 if (hasData == HasNonDefaultPasteboardData::No) {
916 if (src.selection().selection().isNone()) {
917 // The page may have cleared out the selection in the dragstart handler, in which case we should bail
918 // out of the drag, since there is no content to write to the pasteboard.
922 // FIXME: This entire block is almost identical to the code in Editor::copy, and the code should be shared.
923 RefPtr<Range> selectionRange = src.selection().toNormalizedRange();
924 ASSERT(selectionRange);
926 src.editor().willWriteSelectionToPasteboard(selectionRange.get());
928 if (enclosingTextFormControl(src.selection().selection().start())) {
929 if (mustUseLegacyDragClient)
930 dataTransfer.pasteboard().writePlainText(src.editor().selectedTextForDataTransfer(), Pasteboard::CannotSmartReplace);
932 PasteboardWriterData::PlainText plainText;
933 plainText.canSmartCopyOrDelete = false;
934 plainText.text = src.editor().selectedTextForDataTransfer();
935 pasteboardWriterData.setPlainText(WTFMove(plainText));
938 if (mustUseLegacyDragClient) {
939 #if PLATFORM(COCOA) || PLATFORM(GTK)
940 src.editor().writeSelectionToPasteboard(dataTransfer.pasteboard());
942 // FIXME: Convert all other platforms to match Mac and delete this.
943 dataTransfer.pasteboard().writeSelection(*selectionRange, src.editor().canSmartCopyOrDelete(), src, IncludeImageAltTextForDataTransfer);
947 src.editor().writeSelection(pasteboardWriterData);
952 src.editor().didWriteSelectionToPasteboard();
954 m_client.willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, dataTransfer);
956 TextIndicatorData textIndicator;
957 dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
958 if (textIndicator.contentImage)
959 dragImage.setIndicatorData(textIndicator);
960 dragLoc = dragLocForSelectionDrag(src);
961 m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
967 if (mustUseLegacyDragClient) {
968 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
973 dragItem.imageAnchorPoint = dragImageAnchorPointForSelectionDrag(src, mouseDraggedPoint);
974 dragItem.image = WTFMove(dragImage);
975 dragItem.data = WTFMove(pasteboardWriterData);
977 beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);
982 if (!src.document()->securityOrigin().canDisplay(linkURL)) {
983 src.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to drag local resource: " + linkURL.stringCenterEllipsizedToLength());
987 if (!imageURL.isEmpty() && image && !image->isNull() && (m_dragSourceAction & DragSourceActionImage)) {
988 // We shouldn't be starting a drag for an image that can't provide an extension.
989 // This is an early detection for problems encountered later upon drop.
990 ASSERT(!image->filenameExtension().isEmpty());
991 if (hasData == HasNonDefaultPasteboardData::No) {
992 m_draggingImageURL = imageURL;
993 if (element.isContentRichlyEditable())
994 selectElement(element);
995 declareAndWriteDragImage(dataTransfer, element, !linkURL.isEmpty() ? linkURL : imageURL, hitTestResult.altDisplayString());
998 m_client.willPerformDragSourceAction(DragSourceActionImage, dragOrigin, dataTransfer);
1001 doImageDrag(element, dragOrigin, hitTestResult.imageRect(), src, m_dragOffset, state);
1003 // DHTML defined drag image
1004 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1010 if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
1011 PasteboardWriterData pasteboardWriterData;
1013 String textContentWithSimplifiedWhiteSpace = hitTestResult.textContent().simplifyWhiteSpace();
1015 if (hasData == HasNonDefaultPasteboardData::No) {
1016 // Simplify whitespace so the title put on the dataTransfer resembles what the user sees
1017 // on the web page. This includes replacing newlines with spaces.
1018 if (mustUseLegacyDragClient)
1019 src.editor().copyURL(linkURL, textContentWithSimplifiedWhiteSpace, dataTransfer.pasteboard());
1021 pasteboardWriterData.setURL(src.editor().pasteboardWriterURL(linkURL, textContentWithSimplifiedWhiteSpace));
1023 // Make sure the pasteboard also contains trustworthy link data
1024 // but don't overwrite more general pasteboard types.
1025 PasteboardURL pasteboardURL;
1026 pasteboardURL.url = linkURL;
1027 pasteboardURL.title = hitTestResult.textContent();
1028 dataTransfer.pasteboard().writeTrustworthyWebURLsPboardType(pasteboardURL);
1031 const VisibleSelection& sourceSelection = src.selection().selection();
1032 if (sourceSelection.isCaret() && sourceSelection.isContentEditable()) {
1033 // a user can initiate a drag on a link without having any text
1034 // selected. In this case, we should expand the selection to
1035 // the enclosing anchor element
1036 Position pos = sourceSelection.base();
1037 Node* node = enclosingAnchorElement(pos);
1039 src.selection().setSelection(VisibleSelection::selectionFromContentsOfNode(node));
1042 m_client.willPerformDragSourceAction(DragSourceActionLink, dragOrigin, dataTransfer);
1044 TextIndicatorData textIndicator;
1045 dragImage = DragImage { createDragImageForLink(element, linkURL, textContentWithSimplifiedWhiteSpace, textIndicator, src.settings().fontRenderingMode(), m_page.deviceScaleFactor()) };
1047 m_dragOffset = dragOffsetForLinkDragImage(dragImage.get());
1048 dragLoc = IntPoint(dragOrigin.x() + m_dragOffset.x(), dragOrigin.y() + m_dragOffset.y());
1049 dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
1050 if (textIndicator.contentImage)
1051 dragImage.setIndicatorData(textIndicator);
1055 if (mustUseLegacyDragClient) {
1056 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1061 dragItem.imageAnchorPoint = dragImage ? anchorPointForLinkDragImage(dragImage.get()) : FloatPoint();
1062 dragItem.image = WTFMove(dragImage);
1063 dragItem.data = WTFMove(pasteboardWriterData);
1065 beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);
1070 #if ENABLE(ATTACHMENT_ELEMENT)
1071 if (is<HTMLAttachmentElement>(element) && m_dragSourceAction & DragSourceActionAttachment) {
1072 auto& attachment = downcast<HTMLAttachmentElement>(element);
1073 auto* attachmentRenderer = attachment.attachmentRenderer();
1074 if (!attachmentRenderer)
1077 src.editor().setIgnoreSelectionChanges(true);
1078 auto previousSelection = src.selection().selection();
1079 if (hasData == HasNonDefaultPasteboardData::No) {
1080 selectElement(element);
1081 if (!dragAttachmentElement(src, attachment) && src.editor().client()) {
1083 // Otherwise, if no file URL is specified, call out to the injected bundle to populate the pasteboard with data.
1084 auto& editor = src.editor();
1085 editor.willWriteSelectionToPasteboard(src.selection().toNormalizedRange().get());
1086 editor.writeSelectionToPasteboard(dataTransfer.pasteboard());
1087 editor.didWriteSelectionToPasteboard();
1092 m_client.willPerformDragSourceAction(DragSourceActionAttachment, dragOrigin, dataTransfer);
1095 TextIndicatorData textIndicator;
1096 attachmentRenderer->setShouldDrawBorder(false);
1097 dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
1098 attachmentRenderer->setShouldDrawBorder(true);
1099 if (textIndicator.contentImage)
1100 dragImage.setIndicatorData(textIndicator);
1101 dragLoc = dragLocForSelectionDrag(src);
1102 m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
1104 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1105 src.selection().setSelection(previousSelection);
1106 src.editor().setIgnoreSelectionChanges(false);
1111 if (state.type == DragSourceActionDHTML && dragImage) {
1112 ASSERT(m_dragSourceAction & DragSourceActionDHTML);
1113 m_client.willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, dataTransfer);
1114 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1121 void DragController::doImageDrag(Element& element, const IntPoint& dragOrigin, const IntRect& layoutRect, Frame& frame, IntPoint& dragImageOffset, const DragState& state)
1123 IntPoint mouseDownPoint = dragOrigin;
1124 DragImage dragImage;
1125 IntPoint scaledOrigin;
1127 if (!element.renderer())
1130 ImageOrientationDescription orientationDescription(element.renderer()->shouldRespectImageOrientation(), element.renderer()->style().imageOrientation());
1132 Image* image = getImage(element);
1133 if (image && shouldUseCachedImageForDragImage(*image) && (dragImage = DragImage { createDragImageFromImage(image, element.renderer() ? orientationDescription : ImageOrientationDescription()) })) {
1134 dragImage = DragImage { fitDragImageToMaxSize(dragImage.get(), layoutRect.size(), maxDragImageSize()) };
1135 IntSize fittedSize = dragImageSize(dragImage.get());
1137 dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
1138 dragImage = DragImage { dissolveDragImageToFraction(dragImage.get(), DragImageAlpha) };
1140 // Properly orient the drag image and orient it differently if it's smaller than the original.
1141 float scale = fittedSize.width() / (float)layoutRect.width();
1142 float dx = scale * (layoutRect.x() - mouseDownPoint.x());
1143 float originY = layoutRect.y();
1145 // Compensate for accursed flipped coordinates in Cocoa.
1146 originY += layoutRect.height();
1148 float dy = scale * (originY - mouseDownPoint.y());
1149 scaledOrigin = IntPoint((int)(dx + 0.5), (int)(dy + 0.5));
1151 if (CachedImage* cachedImage = getCachedImage(element)) {
1152 dragImage = DragImage { createDragImageIconForCachedImageFilename(cachedImage->response().suggestedFilename()) };
1154 dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
1155 scaledOrigin = IntPoint(DragIconRightInset - dragImageSize(dragImage.get()).width(), DragIconBottomInset);
1163 dragImageOffset = mouseDownPoint + scaledOrigin;
1164 doSystemDrag(WTFMove(dragImage), dragImageOffset, dragOrigin, frame, state);
1167 void DragController::beginDrag(DragItem dragItem, Frame& frame, const IntPoint& mouseDownPoint, const IntPoint& mouseDraggedPoint, DataTransfer& dataTransfer, DragSourceAction dragSourceAction)
1169 ASSERT(!m_client.useLegacyDragClient());
1171 m_didInitiateDrag = true;
1172 m_dragInitiator = frame.document();
1174 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
1175 Ref<MainFrame> mainFrameProtector(m_page.mainFrame());
1176 RefPtr<FrameView> viewProtector = mainFrameProtector->view();
1178 auto mouseDownPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDownPoint));
1179 auto mouseDraggedPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDraggedPoint));
1181 m_client.beginDrag(WTFMove(dragItem), frame, mouseDownPointInRootViewCoordinates, mouseDraggedPointInRootViewCoordinates, dataTransfer, dragSourceAction);
1183 // DragClient::beginDrag can cause the drag controller to be deleted.
1184 if (!mainFrameProtector->page())
1187 // FIXME: This shouldn't be needed.
1188 cleanupAfterSystemDrag();
1191 void DragController::doSystemDrag(DragImage image, const IntPoint& dragLoc, const IntPoint& eventPos, Frame& frame, const DragState& state)
1193 m_didInitiateDrag = true;
1194 m_dragInitiator = frame.document();
1195 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
1196 Ref<MainFrame> frameProtector(m_page.mainFrame());
1197 RefPtr<FrameView> viewProtector = frameProtector->view();
1200 item.image = WTFMove(image);
1201 item.sourceAction = state.type;
1203 auto eventPositionInRootViewCoordinates = frame.view()->contentsToRootView(eventPos);
1204 auto dragLocationInRootViewCoordinates = frame.view()->contentsToRootView(dragLoc);
1205 item.eventPositionInContentCoordinates = viewProtector->rootViewToContents(eventPositionInRootViewCoordinates);
1206 item.dragLocationInContentCoordinates = viewProtector->rootViewToContents(dragLocationInRootViewCoordinates);
1207 item.eventPositionInWindowCoordinates = frame.view()->contentsToWindow(item.eventPositionInContentCoordinates);
1208 item.dragLocationInWindowCoordinates = frame.view()->contentsToWindow(item.dragLocationInContentCoordinates);
1209 if (auto element = state.source) {
1210 auto dataTransferImageElement = state.dataTransfer->dragImageElement();
1211 if (state.type == DragSourceActionDHTML) {
1212 // If the drag image has been customized, fall back to positioning the preview relative to the drag event location.
1213 IntSize dragPreviewSize;
1214 if (dataTransferImageElement)
1215 dragPreviewSize = dataTransferImageElement->boundsInRootViewSpace().size();
1217 dragPreviewSize = dragImageSize(item.image.get());
1218 if (auto* page = frame.page())
1219 dragPreviewSize.scale(1 / page->deviceScaleFactor());
1221 item.dragPreviewFrameInRootViewCoordinates = { dragLocationInRootViewCoordinates, WTFMove(dragPreviewSize) };
1223 // We can position the preview using the bounds of the drag source element.
1224 item.dragPreviewFrameInRootViewCoordinates = element->boundsInRootViewSpace();
1227 RefPtr<Element> link;
1228 if (element->isLink())
1231 for (auto& currentElement : elementLineage(element.get())) {
1232 if (currentElement.isLink()) {
1233 link = ¤tElement;
1239 auto titleAttribute = link->attributeWithoutSynchronization(HTMLNames::titleAttr);
1240 item.title = titleAttribute.isEmpty() ? link->innerText() : titleAttribute.string();
1241 item.url = frame.document()->completeURL(stripLeadingAndTrailingHTMLSpaces(link->getAttribute(HTMLNames::hrefAttr)));
1244 m_client.startDrag(WTFMove(item), *state.dataTransfer, frameProtector.get());
1245 // DragClient::startDrag can cause our Page to dispear, deallocating |this|.
1246 if (!frameProtector->page())
1249 cleanupAfterSystemDrag();
1252 // Manual drag caret manipulation
1253 void DragController::placeDragCaret(const IntPoint& windowPoint)
1255 mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(windowPoint));
1256 if (!m_documentUnderMouse)
1258 Frame* frame = m_documentUnderMouse->frame();
1259 FrameView* frameView = frame->view();
1262 IntPoint framePoint = frameView->windowToContents(windowPoint);
1264 m_page.dragCaretController().setCaretPosition(frame->visiblePositionForPoint(framePoint));
1267 bool DragController::shouldUseCachedImageForDragImage(const Image& image) const
1269 #if ENABLE(DATA_INTERACTION)
1270 UNUSED_PARAM(image);
1273 return image.size().height() * image.size().width() <= MaxOriginalImageArea;
1277 #if ENABLE(ATTACHMENT_ELEMENT)
1279 bool DragController::dragAttachmentElement(Frame& frame, HTMLAttachmentElement& attachment)
1281 if (!attachment.file())
1284 Vector<String> additionalTypes;
1285 Vector<RefPtr<SharedBuffer>> additionalData;
1287 if (frame.editor().client())
1288 frame.editor().getPasteboardTypesAndDataForAttachment(attachment, additionalTypes, additionalData);
1291 auto& file = *attachment.file();
1292 auto blobURL = file.url().string();
1293 bool isFileBacked = !file.path().isEmpty();
1294 auto blobType = isFileBacked ? PromisedBlobType::FileBacked : PromisedBlobType::DataBacked;
1295 m_client.prepareToDragPromisedBlob({ blobURL, file.type(), file.name(), blobType, additionalTypes, additionalData });
1300 #endif // ENABLE(ATTACHMENT_ELEMENT)
1302 #endif // ENABLE(DRAG_SUPPORT)
1304 } // namespace WebCore