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"
48 #include "FloatRect.h"
49 #include "FocusController.h"
50 #include "FrameLoadRequest.h"
51 #include "FrameLoader.h"
52 #include "FrameSelection.h"
53 #include "FrameView.h"
54 #include "HTMLAttachmentElement.h"
55 #include "HTMLImageElement.h"
56 #include "HTMLInputElement.h"
57 #include "HTMLParserIdioms.h"
58 #include "HTMLPlugInElement.h"
59 #include "HitTestRequest.h"
60 #include "HitTestResult.h"
62 #include "ImageOrientation.h"
63 #include "MainFrame.h"
64 #include "MoveSelectionCommand.h"
66 #include "Pasteboard.h"
67 #include "PlatformKeyboardEvent.h"
68 #include "PluginDocument.h"
69 #include "PluginViewBase.h"
71 #include "RenderAttachment.h"
72 #include "RenderFileUploadControl.h"
73 #include "RenderImage.h"
74 #include "RenderView.h"
75 #include "ReplaceSelectionCommand.h"
76 #include "ResourceRequest.h"
77 #include "SecurityOrigin.h"
79 #include "ShadowRoot.h"
80 #include "StyleProperties.h"
82 #include "TextEvent.h"
83 #include "VisiblePosition.h"
86 #if ENABLE(DATA_INTERACTION)
87 #include "SelectionRect.h"
90 #include <wtf/CurrentTime.h>
91 #include <wtf/RefPtr.h>
92 #include <wtf/SetForScope.h>
95 #if ENABLE(DATA_DETECTION)
96 #include "DataDetection.h"
101 bool isDraggableLink(const Element& element)
103 if (is<HTMLAnchorElement>(element)) {
104 auto& anchorElement = downcast<HTMLAnchorElement>(element);
105 if (!anchorElement.isLiveLink())
107 #if ENABLE(DATA_DETECTION)
108 return !DataDetection::isDataDetectorURL(anchorElement.href());
113 if (is<SVGAElement>(element))
114 return element.isLink();
118 #if ENABLE(DRAG_SUPPORT)
120 static PlatformMouseEvent createMouseEvent(const DragData& dragData)
122 bool shiftKey = false;
123 bool ctrlKey = false;
125 bool metaKey = false;
127 PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
129 return PlatformMouseEvent(dragData.clientPosition(), dragData.globalPosition(),
130 LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
131 metaKey, currentTime(), ForceAtClick, NoTap);
134 DragController::DragController(Page& page, DragClient& client)
137 , m_numberOfItemsToBeAccepted(0)
138 , m_dragHandlingMethod(DragHandlingMethod::None)
139 , m_dragDestinationAction(DragDestinationActionNone)
140 , m_dragSourceAction(DragSourceActionNone)
141 , m_didInitiateDrag(false)
142 , m_sourceDragOperation(DragOperationNone)
146 DragController::~DragController()
148 m_client.dragControllerDestroyed();
151 static RefPtr<DocumentFragment> documentFragmentFromDragData(const DragData& dragData, Frame& frame, Range& context, bool allowPlainText, bool& chosePlainText)
153 chosePlainText = false;
155 Document& document = context.ownerDocument();
156 if (dragData.containsCompatibleContent()) {
157 if (auto fragment = frame.editor().webContentFromPasteboard(*Pasteboard::createForDragAndDrop(dragData), context, allowPlainText, chosePlainText))
160 if (dragData.containsURL(DragData::DoNotConvertFilenames)) {
162 String url = dragData.asURL(DragData::DoNotConvertFilenames, &title);
163 if (!url.isEmpty()) {
164 auto anchor = HTMLAnchorElement::create(document);
165 anchor->setHref(url);
166 if (title.isEmpty()) {
167 // Try the plain text first because the url might be normalized or escaped.
168 if (dragData.containsPlainText())
169 title = dragData.asPlainText();
173 anchor->appendChild(document.createTextNode(title));
174 auto fragment = document.createDocumentFragment();
175 fragment->appendChild(anchor);
176 return WTFMove(fragment);
180 if (allowPlainText && dragData.containsPlainText()) {
181 chosePlainText = true;
182 return createFragmentFromText(context, dragData.asPlainText()).ptr();
190 DragOperation DragController::platformGenericDragOperation()
192 return DragOperationMove;
197 bool DragController::dragIsMove(FrameSelection& selection, const DragData& dragData)
199 const VisibleSelection& visibleSelection = selection.selection();
200 return m_documentUnderMouse == m_dragInitiator && visibleSelection.isContentEditable() && visibleSelection.isRange() && !isCopyKeyDown(dragData);
203 void DragController::clearDragCaret()
205 m_page.dragCaretController().clear();
208 void DragController::dragEnded()
210 m_dragInitiator = nullptr;
211 m_didInitiateDrag = false;
212 m_documentUnderMouse = nullptr;
215 m_client.dragEnded();
218 DragOperation DragController::dragEntered(const DragData& dragData)
220 return dragEnteredOrUpdated(dragData);
223 static Ref<DataTransfer> createDataTransferToUpdateDrag(const DragData& dragData, const Settings& settings, RefPtr<Document>&& documentUnderMouse)
225 auto accessMode = DataTransfer::StoreMode::Protected;
227 #if ENABLE(DASHBOARD_SUPPORT)
228 if (settings.usesDashboardBackwardCompatibilityMode() && (!documentUnderMouse || documentUnderMouse->securityOrigin().isLocal()))
229 accessMode = DataTransfer::StoreMode::Readonly;
231 UNUSED_PARAM(settings);
232 UNUSED_PARAM(documentUnderMouse);
235 auto dataTransfer = DataTransfer::createForDrop(accessMode, dragData);
236 dataTransfer->setSourceOperation(dragData.draggingSourceOperationMask());
241 void DragController::dragExited(const DragData& dragData)
243 if (RefPtr<FrameView> v = m_page.mainFrame().view()) {
244 auto dataTransfer = createDataTransferToUpdateDrag(dragData, m_page.mainFrame().settings(), m_documentUnderMouse.copyRef());
245 m_page.mainFrame().eventHandler().cancelDragAndDrop(createMouseEvent(dragData), dataTransfer);
246 dataTransfer->makeInvalidForSecurity();
248 mouseMovedIntoDocument(nullptr);
249 if (m_fileInputElementUnderMouse)
250 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
251 m_fileInputElementUnderMouse = nullptr;
254 DragOperation DragController::dragUpdated(const DragData& dragData)
256 return dragEnteredOrUpdated(dragData);
259 inline static bool dragIsHandledByDocument(DragController::DragHandlingMethod dragHandlingMethod)
261 if (dragHandlingMethod == DragController::DragHandlingMethod::None)
264 if (dragHandlingMethod == DragController::DragHandlingMethod::PageLoad)
270 bool DragController::performDragOperation(const DragData& dragData)
272 SetForScope<bool> isPerformingDrop(m_isPerformingDrop, true);
273 TemporarySelectionChange ignoreSelectionChanges(m_page.focusController().focusedOrMainFrame(), std::nullopt, TemporarySelectionOptionIgnoreSelectionChanges);
275 m_documentUnderMouse = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
277 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = ShouldOpenExternalURLsPolicy::ShouldNotAllow;
278 if (m_documentUnderMouse)
279 shouldOpenExternalURLsPolicy = m_documentUnderMouse->shouldOpenExternalURLsPolicyToPropagate();
281 if ((m_dragDestinationAction & DragDestinationActionDHTML) && dragIsHandledByDocument(m_dragHandlingMethod)) {
282 m_client.willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
283 Ref<MainFrame> mainFrame(m_page.mainFrame());
284 bool preventedDefault = false;
285 if (mainFrame->view()) {
286 // Sending an event can result in the destruction of the view and part.
287 auto dataTransfer = DataTransfer::createForDrop(DataTransfer::StoreMode::Readonly, dragData);
288 dataTransfer->setSourceOperation(dragData.draggingSourceOperationMask());
289 preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), dataTransfer);
290 dataTransfer->makeInvalidForSecurity();
292 if (preventedDefault) {
294 m_documentUnderMouse = nullptr;
299 if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
300 m_client.didConcludeEditDrag();
301 m_documentUnderMouse = nullptr;
306 m_documentUnderMouse = nullptr;
309 if (operationForLoad(dragData) == DragOperationNone)
312 auto urlString = dragData.asURL();
313 if (urlString.isEmpty())
316 m_client.willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
317 m_page.mainFrame().loader().load(FrameLoadRequest(m_page.mainFrame(), { urlString }, shouldOpenExternalURLsPolicy));
321 void DragController::mouseMovedIntoDocument(Document* newDocument)
323 if (m_documentUnderMouse == newDocument)
326 // If we were over another document clear the selection
327 if (m_documentUnderMouse)
329 m_documentUnderMouse = newDocument;
332 DragOperation DragController::dragEnteredOrUpdated(const DragData& dragData)
334 mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(dragData.clientPosition()));
336 m_dragDestinationAction = dragData.dragDestinationAction();
337 if (m_dragDestinationAction == DragDestinationActionNone) {
338 clearDragCaret(); // FIXME: Why not call mouseMovedIntoDocument(nullptr)?
339 return DragOperationNone;
342 DragOperation dragOperation = DragOperationNone;
343 m_dragHandlingMethod = tryDocumentDrag(dragData, m_dragDestinationAction, dragOperation);
344 if (m_dragHandlingMethod == DragHandlingMethod::None && (m_dragDestinationAction & DragDestinationActionLoad)) {
345 dragOperation = operationForLoad(dragData);
346 if (dragOperation != DragOperationNone)
347 m_dragHandlingMethod = DragHandlingMethod::PageLoad;
350 updateSupportedTypeIdentifiersForDragHandlingMethod(m_dragHandlingMethod, dragData);
351 return dragOperation;
354 static HTMLInputElement* asFileInput(Node& node)
356 if (!is<HTMLInputElement>(node))
359 auto* inputElement = &downcast<HTMLInputElement>(node);
361 // If this is a button inside of the a file input, move up to the file input.
362 if (inputElement->isTextButton() && is<ShadowRoot>(inputElement->treeScope().rootNode())) {
363 auto& host = *downcast<ShadowRoot>(inputElement->treeScope().rootNode()).host();
364 inputElement = is<HTMLInputElement>(host) ? &downcast<HTMLInputElement>(host) : nullptr;
367 return inputElement && inputElement->isFileUpload() ? inputElement : nullptr;
370 // This can return null if an empty document is loaded.
371 static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
373 Frame* frame = documentUnderMouse->frame();
374 float zoomFactor = frame ? frame->pageZoomFactor() : 1;
375 LayoutPoint point(p.x() * zoomFactor, p.y() * zoomFactor);
377 HitTestResult result(point);
378 documentUnderMouse->renderView()->hitTest(HitTestRequest(), result);
380 Node* node = result.innerNode();
381 while (node && !is<Element>(*node))
382 node = node->parentNode();
384 node = node->deprecatedShadowAncestorNode();
386 return downcast<Element>(node);
389 #if !ENABLE(DATA_INTERACTION)
391 void DragController::updateSupportedTypeIdentifiersForDragHandlingMethod(DragHandlingMethod, const DragData&) const
397 DragController::DragHandlingMethod DragController::tryDocumentDrag(const DragData& dragData, DragDestinationAction actionMask, DragOperation& dragOperation)
399 if (!m_documentUnderMouse)
400 return DragHandlingMethod::None;
402 if (m_dragInitiator && !m_documentUnderMouse->securityOrigin().canReceiveDragData(m_dragInitiator->securityOrigin()))
403 return DragHandlingMethod::None;
405 bool isHandlingDrag = false;
406 if (actionMask & DragDestinationActionDHTML) {
407 isHandlingDrag = tryDHTMLDrag(dragData, dragOperation);
408 // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
409 // tryDHTMLDrag fires dragenter event. The event listener that listens
410 // to this event may create a nested message loop (open a modal dialog),
411 // which could process dragleave event and reset m_documentUnderMouse in
413 if (!m_documentUnderMouse)
414 return DragHandlingMethod::None;
417 // It's unclear why this check is after tryDHTMLDrag.
418 // We send drag events in tryDHTMLDrag and that may be the reason.
419 RefPtr<FrameView> frameView = m_documentUnderMouse->view();
421 return DragHandlingMethod::None;
423 if (isHandlingDrag) {
425 return DragHandlingMethod::NonDefault;
428 if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
429 if (dragData.containsColor()) {
430 dragOperation = DragOperationGeneric;
431 return DragHandlingMethod::SetColor;
434 IntPoint point = frameView->windowToContents(dragData.clientPosition());
435 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
437 return DragHandlingMethod::None;
439 HTMLInputElement* elementAsFileInput = asFileInput(*element);
440 if (m_fileInputElementUnderMouse != elementAsFileInput) {
441 if (m_fileInputElementUnderMouse)
442 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
443 m_fileInputElementUnderMouse = elementAsFileInput;
446 if (!m_fileInputElementUnderMouse)
447 m_page.dragCaretController().setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
451 Frame* innerFrame = element->document().frame();
452 dragOperation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
453 m_numberOfItemsToBeAccepted = 0;
455 unsigned numberOfFiles = dragData.numberOfFiles();
456 if (m_fileInputElementUnderMouse) {
457 if (m_fileInputElementUnderMouse->isDisabledFormControl())
458 m_numberOfItemsToBeAccepted = 0;
459 else if (m_fileInputElementUnderMouse->multiple())
460 m_numberOfItemsToBeAccepted = numberOfFiles;
461 else if (numberOfFiles > 1)
462 m_numberOfItemsToBeAccepted = 0;
464 m_numberOfItemsToBeAccepted = 1;
466 if (!m_numberOfItemsToBeAccepted)
467 dragOperation = DragOperationNone;
468 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(m_numberOfItemsToBeAccepted);
470 // We are not over a file input element. The dragged item(s) will only
471 // be loaded into the view the number of dragged items is 1.
472 m_numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
475 if (m_fileInputElementUnderMouse)
476 return DragHandlingMethod::UploadFile;
478 if (m_page.dragCaretController().isContentRichlyEditable())
479 return DragHandlingMethod::EditRichText;
481 return DragHandlingMethod::EditPlainText;
484 // We are not over an editable region. Make sure we're clearing any prior drag cursor.
486 if (m_fileInputElementUnderMouse)
487 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
488 m_fileInputElementUnderMouse = nullptr;
489 return DragHandlingMethod::None;
492 DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
494 m_dragSourceAction = m_client.dragSourceActionMaskForPoint(rootViewPoint);
495 return m_dragSourceAction;
498 DragOperation DragController::operationForLoad(const DragData& dragData)
500 Document* document = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
502 bool pluginDocumentAcceptsDrags = false;
504 if (is<PluginDocument>(document)) {
505 const Widget* widget = downcast<PluginDocument>(*document).pluginWidget();
506 const PluginViewBase* pluginView = is<PluginViewBase>(widget) ? downcast<PluginViewBase>(widget) : nullptr;
509 pluginDocumentAcceptsDrags = pluginView->shouldAllowNavigationFromDrags();
512 if (document && (m_didInitiateDrag || (is<PluginDocument>(*document) && !pluginDocumentAcceptsDrags) || document->hasEditableStyle()))
513 return DragOperationNone;
514 return dragOperation(dragData);
517 static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
519 Ref<Frame> protector(*frame);
520 frame->selection().setSelection(dragCaret);
521 if (frame->selection().selection().isNone()) {
522 dragCaret = frame->visiblePositionForPoint(point);
523 frame->selection().setSelection(dragCaret);
524 range = dragCaret.toNormalizedRange();
526 return !frame->selection().isNone() && frame->selection().selection().isContentEditable();
529 bool DragController::dispatchTextInputEventFor(Frame* innerFrame, const DragData& dragData)
531 ASSERT(m_page.dragCaretController().hasCaret());
532 String text = m_page.dragCaretController().isContentRichlyEditable() ? emptyString() : dragData.asPlainText();
533 Element* target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
534 return target->dispatchEvent(TextEvent::createForDrop(innerFrame->document()->domWindow(), text));
537 bool DragController::concludeEditDrag(const DragData& dragData)
539 RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
540 if (m_fileInputElementUnderMouse) {
541 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
542 m_fileInputElementUnderMouse = nullptr;
545 if (!m_documentUnderMouse)
548 IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData.clientPosition());
549 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
552 RefPtr<Frame> innerFrame = element->document().frame();
555 if (m_page.dragCaretController().hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
558 if (dragData.containsColor()) {
559 Color color = dragData.asColor();
560 if (!color.isValid())
562 RefPtr<Range> innerRange = innerFrame->selection().toNormalizedRange();
563 RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
564 style->setProperty(CSSPropertyColor, color.serialized(), false);
565 if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
567 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
568 innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
572 if (dragData.containsFiles() && fileInput) {
573 // fileInput should be the element we hit tested for, unless it was made
574 // display:none in a drop event handler.
575 ASSERT(fileInput == element || !fileInput->renderer());
576 if (fileInput->isDisabledFormControl())
579 return fileInput->receiveDroppedFiles(dragData);
582 if (!m_page.dragController().canProcessDrag(dragData))
585 VisibleSelection dragCaret = m_page.dragCaretController().caretPosition();
586 RefPtr<Range> range = dragCaret.toNormalizedRange();
587 RefPtr<Element> rootEditableElement = innerFrame->selection().selection().rootEditableElement();
589 // For range to be null a WebKit client must have done something bad while
590 // manually controlling drag behaviour
594 ResourceCacheValidationSuppressor validationSuppressor(range->ownerDocument().cachedResourceLoader());
595 auto& editor = innerFrame->editor();
596 bool isMove = dragIsMove(innerFrame->selection(), dragData);
597 if (isMove || dragCaret.isContentRichlyEditable()) {
598 bool chosePlainText = false;
599 RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, *innerFrame, *range, true, chosePlainText);
600 if (!fragment || !editor.shouldInsertFragment(*fragment, range.get(), EditorInsertAction::Dropped))
603 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
605 if (editor.client() && editor.client()->performTwoStepDrop(*fragment, *range, isMove))
609 // NSTextView behavior is to always smart delete on moving a selection,
610 // but only to smart insert if the selection granularity is word granularity.
611 bool smartDelete = editor.smartInsertDeleteEnabled();
612 bool smartInsert = smartDelete && innerFrame->selection().granularity() == WordGranularity && dragData.canSmartReplace();
613 MoveSelectionCommand::create(fragment.releaseNonNull(), dragCaret.base(), smartInsert, smartDelete)->apply();
615 if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
616 ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
617 if (dragData.canSmartReplace())
618 options |= ReplaceSelectionCommand::SmartReplace;
620 options |= ReplaceSelectionCommand::MatchStyle;
621 ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment.releaseNonNull(), options, EditActionInsertFromDrop)->apply();
625 String text = dragData.asPlainText();
626 if (text.isEmpty() || !editor.shouldInsertText(text, range.get(), EditorInsertAction::Dropped))
629 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
630 RefPtr<DocumentFragment> fragment = createFragmentFromText(*range, text);
634 if (editor.client() && editor.client()->performTwoStepDrop(*fragment, *range, isMove))
637 if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
638 ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment.get(), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting, EditActionInsertFromDrop)->apply();
641 if (rootEditableElement) {
642 if (Frame* frame = rootEditableElement->document().frame())
643 frame->eventHandler().updateDragStateAfterEditDragIfNeeded(*rootEditableElement);
649 bool DragController::canProcessDrag(const DragData& dragData)
651 IntPoint point = m_page.mainFrame().view()->windowToContents(dragData.clientPosition());
652 HitTestResult result = HitTestResult(point);
653 if (!m_page.mainFrame().contentRenderer())
656 result = m_page.mainFrame().eventHandler().hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
658 if (!result.innerNonSharedNode())
661 DragData::DraggingPurpose dragPurpose = DragData::DraggingPurpose::ForEditing;
662 if (asFileInput(*result.innerNonSharedNode()))
663 dragPurpose = DragData::DraggingPurpose::ForFileUpload;
665 if (!dragData.containsCompatibleContent(dragPurpose))
668 if (dragPurpose == DragData::DraggingPurpose::ForFileUpload)
671 if (is<HTMLPlugInElement>(*result.innerNonSharedNode())) {
672 if (!downcast<HTMLPlugInElement>(result.innerNonSharedNode())->canProcessDrag() && !result.innerNonSharedNode()->hasEditableStyle())
674 } else if (!result.innerNonSharedNode()->hasEditableStyle())
677 if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
683 static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
685 // This is designed to match IE's operation fallback for the case where
686 // the page calls preventDefault() in a drag event but doesn't set dropEffect.
687 if (srcOpMask == DragOperationEvery)
688 return DragOperationCopy;
689 if (srcOpMask == DragOperationNone)
690 return DragOperationNone;
691 if (srcOpMask & DragOperationMove)
692 return DragOperationMove;
693 if (srcOpMask & DragOperationGeneric)
694 return DragController::platformGenericDragOperation();
695 if (srcOpMask & DragOperationCopy)
696 return DragOperationCopy;
697 if (srcOpMask & DragOperationLink)
698 return DragOperationLink;
700 // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
701 return DragOperationGeneric;
704 bool DragController::tryDHTMLDrag(const DragData& dragData, DragOperation& operation)
706 ASSERT(m_documentUnderMouse);
707 Ref<MainFrame> mainFrame(m_page.mainFrame());
708 RefPtr<FrameView> viewProtector = mainFrame->view();
712 auto dataTransfer = createDataTransferToUpdateDrag(dragData, mainFrame->settings(), m_documentUnderMouse.copyRef());
714 PlatformMouseEvent event = createMouseEvent(dragData);
715 if (!mainFrame->eventHandler().updateDragAndDrop(event, dataTransfer)) {
716 dataTransfer->makeInvalidForSecurity();
720 operation = dataTransfer->destinationOperation();
721 DragOperation srcOpMask = dragData.draggingSourceOperationMask();
722 if (dataTransfer->dropEffectIsUninitialized())
723 operation = defaultOperationForDrag(srcOpMask);
724 else if (!(srcOpMask & operation)) {
725 // The element picked an operation which is not supported by the source
726 operation = DragOperationNone;
729 dataTransfer->makeInvalidForSecurity();
733 static bool imageElementIsDraggable(const HTMLImageElement& image, const Frame& sourceFrame)
735 if (sourceFrame.settings().loadsImagesAutomatically())
738 auto* renderer = image.renderer();
739 if (!is<RenderImage>(renderer))
742 auto* cachedImage = downcast<RenderImage>(*renderer).cachedImage();
743 return cachedImage && !cachedImage->errorOccurred() && cachedImage->imageForRenderer(renderer);
746 Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
748 state.type = (sourceFrame->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
751 #if ENABLE(ATTACHMENT_ELEMENT)
752 if (is<HTMLAttachmentElement>(startElement)) {
753 auto selection = sourceFrame->selection().selection();
754 bool isSingleAttachmentSelection = selection.start() == Position(startElement, Position::PositionIsBeforeAnchor) && selection.end() == Position(startElement, Position::PositionIsAfterAnchor);
755 bool isAttachmentElementInCurrentSelection = false;
756 if (auto selectedRange = selection.toNormalizedRange()) {
757 auto compareResult = selectedRange->compareNode(*startElement);
758 isAttachmentElementInCurrentSelection = !compareResult.hasException() && compareResult.releaseReturnValue() == Range::NODE_INSIDE;
761 if (!isAttachmentElementInCurrentSelection || isSingleAttachmentSelection) {
762 state.type = DragSourceActionAttachment;
768 for (auto* element = startElement; element; element = element->parentOrShadowHostElement()) {
769 auto* renderer = element->renderer();
773 EUserDrag dragMode = renderer->style().userDrag();
774 if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
775 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
778 if (dragMode == DRAG_AUTO) {
779 if ((m_dragSourceAction & DragSourceActionImage)
780 && is<HTMLImageElement>(*element)
781 && imageElementIsDraggable(downcast<HTMLImageElement>(*element), *sourceFrame)) {
782 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
785 if ((m_dragSourceAction & DragSourceActionLink) && isDraggableLink(*element)) {
786 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
789 #if ENABLE(ATTACHMENT_ELEMENT)
790 if ((m_dragSourceAction & DragSourceActionAttachment)
791 && is<HTMLAttachmentElement>(*element)
792 && downcast<HTMLAttachmentElement>(*element).file()) {
793 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionAttachment);
800 // We either have nothing to drag or we have a selection and we're not over a draggable element.
801 return (state.type & DragSourceActionSelection) ? startElement : nullptr;
804 static CachedImage* getCachedImage(Element& element)
806 RenderObject* renderer = element.renderer();
807 if (!is<RenderImage>(renderer))
809 auto& image = downcast<RenderImage>(*renderer);
810 return image.cachedImage();
813 static Image* getImage(Element& element)
815 CachedImage* cachedImage = getCachedImage(element);
816 // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
817 // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
818 // which would be empty when asking the cached BitmapImages.
819 return (cachedImage && !cachedImage->errorOccurred()) ?
820 cachedImage->image() : nullptr;
823 static void selectElement(Element& element)
825 RefPtr<Range> range = element.document().createRange();
826 range->selectNode(element);
827 element.document().frame()->selection().setSelection(VisibleSelection(*range, DOWNSTREAM));
830 static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
832 // dragImageOffset is the cursor position relative to the lower-left corner of the image.
834 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
835 const int yOffset = dragImageOffset.y();
837 const int yOffset = -dragImageOffset.y();
841 return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
843 return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
846 static FloatPoint dragImageAnchorPointForSelectionDrag(Frame& frame, const IntPoint& mouseDraggedPoint)
848 IntRect draggingRect = enclosingIntRect(frame.selection().selectionBounds());
850 float x = (mouseDraggedPoint.x() - draggingRect.x()) / (float)draggingRect.width();
851 float y = (mouseDraggedPoint.y() - draggingRect.y()) / (float)draggingRect.height();
853 return FloatPoint { x, y };
856 static IntPoint dragLocForSelectionDrag(Frame& src)
858 IntRect draggingRect = enclosingIntRect(src.selection().selectionBounds());
859 int xpos = draggingRect.maxX();
860 xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
861 int ypos = draggingRect.maxY();
863 // Deal with flipped coordinates on Mac
864 ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
866 ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
868 return IntPoint(xpos, ypos);
871 bool DragController::startDrag(Frame& src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
873 if (!src.view() || !src.contentRenderer() || !state.source)
876 Ref<Frame> protector(src);
877 HitTestResult hitTestResult = src.eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
879 // FIXME(136836): Investigate whether all elements should use the containsIncludingShadowDOM() path here.
880 bool includeShadowDOM = false;
882 includeShadowDOM = state.source->isMediaElement();
884 bool sourceContainsHitNode;
885 if (!includeShadowDOM)
886 sourceContainsHitNode = state.source->contains(hitTestResult.innerNode());
888 sourceContainsHitNode = state.source->containsIncludingShadowDOM(hitTestResult.innerNode());
890 if (!sourceContainsHitNode) {
891 // The original node being dragged isn't under the drag origin anymore... maybe it was
892 // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
893 // something that's not actually under the drag origin.
897 URL linkURL = hitTestResult.absoluteLinkURL();
898 URL imageURL = hitTestResult.absoluteImageURL();
899 #if ENABLE(ATTACHMENT_ELEMENT)
900 URL attachmentURL = hitTestResult.absoluteAttachmentURL();
901 m_draggingAttachmentURL = URL();
904 IntPoint mouseDraggedPoint = src.view()->windowToContents(dragEvent.position());
906 m_draggingImageURL = URL();
907 m_sourceDragOperation = srcOp;
910 IntPoint dragLoc(0, 0);
911 IntPoint dragImageOffset(0, 0);
913 ASSERT(state.dataTransfer);
915 DataTransfer& dataTransfer = *state.dataTransfer;
916 if (state.type == DragSourceActionDHTML) {
917 dragImage = DragImage { dataTransfer.createDragImage(dragImageOffset) };
918 // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
919 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
921 dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
922 m_dragOffset = dragImageOffset;
926 if (state.type == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty()) {
927 // Selection, image, and link drags receive a default set of allowed drag operations that
929 // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
930 m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
933 ASSERT(state.source);
934 Element& element = *state.source;
936 bool mustUseLegacyDragClient = dataTransfer.pasteboard().hasData() || m_client.useLegacyDragClient();
938 IntRect dragImageBounds;
939 Image* image = getImage(element);
940 if (state.type == DragSourceActionSelection) {
941 PasteboardWriterData pasteboardWriterData;
943 if (!dataTransfer.pasteboard().hasData()) {
944 if (src.selection().selection().isNone()) {
945 // The page may have cleared out the selection in the dragstart handler, in which case we should bail
946 // out of the drag, since there is no content to write to the pasteboard.
950 // FIXME: This entire block is almost identical to the code in Editor::copy, and the code should be shared.
951 RefPtr<Range> selectionRange = src.selection().toNormalizedRange();
952 ASSERT(selectionRange);
954 src.editor().willWriteSelectionToPasteboard(selectionRange.get());
956 if (enclosingTextFormControl(src.selection().selection().start())) {
957 if (mustUseLegacyDragClient)
958 dataTransfer.pasteboard().writePlainText(src.editor().selectedTextForDataTransfer(), Pasteboard::CannotSmartReplace);
960 PasteboardWriterData::PlainText plainText;
961 plainText.canSmartCopyOrDelete = false;
962 plainText.text = src.editor().selectedTextForDataTransfer();
963 pasteboardWriterData.setPlainText(WTFMove(plainText));
966 if (mustUseLegacyDragClient) {
967 #if PLATFORM(COCOA) || PLATFORM(GTK)
968 src.editor().writeSelectionToPasteboard(dataTransfer.pasteboard());
970 // FIXME: Convert all other platforms to match Mac and delete this.
971 dataTransfer.pasteboard().writeSelection(*selectionRange, src.editor().canSmartCopyOrDelete(), src, IncludeImageAltTextForDataTransfer);
975 src.editor().writeSelection(pasteboardWriterData);
980 src.editor().didWriteSelectionToPasteboard();
982 m_client.willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, dataTransfer);
984 TextIndicatorData textIndicator;
985 dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
986 if (textIndicator.contentImage)
987 dragImage.setIndicatorData(textIndicator);
988 dragLoc = dragLocForSelectionDrag(src);
989 m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
995 if (mustUseLegacyDragClient) {
996 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1001 dragItem.imageAnchorPoint = dragImageAnchorPointForSelectionDrag(src, mouseDraggedPoint);
1002 dragItem.image = WTFMove(dragImage);
1003 dragItem.data = WTFMove(pasteboardWriterData);
1005 beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);
1010 if (!src.document()->securityOrigin().canDisplay(linkURL)) {
1011 src.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to drag local resource: " + linkURL.stringCenterEllipsizedToLength());
1015 if (!imageURL.isEmpty() && image && !image->isNull() && (m_dragSourceAction & DragSourceActionImage)) {
1016 // We shouldn't be starting a drag for an image that can't provide an extension.
1017 // This is an early detection for problems encountered later upon drop.
1018 ASSERT(!image->filenameExtension().isEmpty());
1019 if (!dataTransfer.pasteboard().hasData()) {
1020 m_draggingImageURL = imageURL;
1021 if (element.isContentRichlyEditable())
1022 selectElement(element);
1023 declareAndWriteDragImage(dataTransfer, element, !linkURL.isEmpty() ? linkURL : imageURL, hitTestResult.altDisplayString());
1026 m_client.willPerformDragSourceAction(DragSourceActionImage, dragOrigin, dataTransfer);
1029 doImageDrag(element, dragOrigin, hitTestResult.imageRect(), src, m_dragOffset, state);
1031 // DHTML defined drag image
1032 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1038 if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
1039 PasteboardWriterData pasteboardWriterData;
1041 String textContentWithSimplifiedWhiteSpace = hitTestResult.textContent().simplifyWhiteSpace();
1043 if (!dataTransfer.pasteboard().hasData()) {
1044 // Simplify whitespace so the title put on the dataTransfer resembles what the user sees
1045 // on the web page. This includes replacing newlines with spaces.
1046 if (mustUseLegacyDragClient)
1047 src.editor().copyURL(linkURL, textContentWithSimplifiedWhiteSpace, dataTransfer.pasteboard());
1049 pasteboardWriterData.setURL(src.editor().pasteboardWriterURL(linkURL, textContentWithSimplifiedWhiteSpace));
1051 // Make sure the pasteboard also contains trustworthy link data
1052 // but don't overwrite more general pasteboard types.
1053 PasteboardURL pasteboardURL;
1054 pasteboardURL.url = linkURL;
1055 pasteboardURL.title = hitTestResult.textContent();
1056 dataTransfer.pasteboard().writeTrustworthyWebURLsPboardType(pasteboardURL);
1059 const VisibleSelection& sourceSelection = src.selection().selection();
1060 if (sourceSelection.isCaret() && sourceSelection.isContentEditable()) {
1061 // a user can initiate a drag on a link without having any text
1062 // selected. In this case, we should expand the selection to
1063 // the enclosing anchor element
1064 Position pos = sourceSelection.base();
1065 Node* node = enclosingAnchorElement(pos);
1067 src.selection().setSelection(VisibleSelection::selectionFromContentsOfNode(node));
1070 m_client.willPerformDragSourceAction(DragSourceActionLink, dragOrigin, dataTransfer);
1072 TextIndicatorData textIndicator;
1073 dragImage = DragImage { createDragImageForLink(element, linkURL, textContentWithSimplifiedWhiteSpace, textIndicator, src.settings().fontRenderingMode(), m_page.deviceScaleFactor()) };
1075 m_dragOffset = dragOffsetForLinkDragImage(dragImage.get());
1076 dragLoc = IntPoint(dragOrigin.x() + m_dragOffset.x(), dragOrigin.y() + m_dragOffset.y());
1077 dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
1078 if (textIndicator.contentImage)
1079 dragImage.setIndicatorData(textIndicator);
1083 if (mustUseLegacyDragClient) {
1084 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1089 dragItem.imageAnchorPoint = dragImage ? anchorPointForLinkDragImage(dragImage.get()) : FloatPoint();
1090 dragItem.image = WTFMove(dragImage);
1091 dragItem.data = WTFMove(pasteboardWriterData);
1093 beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);
1098 #if ENABLE(ATTACHMENT_ELEMENT)
1099 if (is<HTMLAttachmentElement>(element) && m_dragSourceAction & DragSourceActionAttachment) {
1100 auto* attachmentRenderer = downcast<HTMLAttachmentElement>(element).renderer();
1101 if (!attachmentRenderer)
1104 src.editor().setIgnoreSelectionChanges(true);
1105 auto previousSelection = src.selection().selection();
1106 if (!dataTransfer.pasteboard().hasData()) {
1107 selectElement(element);
1108 if (!attachmentURL.isEmpty()) {
1109 // Use the attachment URL specified by the file attribute to populate the pasteboard.
1110 m_draggingAttachmentURL = attachmentURL;
1111 declareAndWriteAttachment(dataTransfer, element, attachmentURL);
1112 } else if (src.editor().client()) {
1114 // Otherwise, if no file URL is specified, call out to the injected bundle to populate the pasteboard with data.
1115 auto& editor = src.editor();
1116 editor.willWriteSelectionToPasteboard(src.selection().toNormalizedRange().get());
1117 editor.writeSelectionToPasteboard(dataTransfer.pasteboard());
1118 editor.didWriteSelectionToPasteboard();
1123 m_client.willPerformDragSourceAction(DragSourceActionAttachment, dragOrigin, dataTransfer);
1126 TextIndicatorData textIndicator;
1127 attachmentRenderer->setShouldDrawBorder(false);
1128 dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
1129 attachmentRenderer->setShouldDrawBorder(true);
1130 if (textIndicator.contentImage)
1131 dragImage.setIndicatorData(textIndicator);
1132 dragLoc = dragLocForSelectionDrag(src);
1133 m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
1135 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1136 src.selection().setSelection(previousSelection);
1137 src.editor().setIgnoreSelectionChanges(false);
1142 if (state.type == DragSourceActionDHTML && dragImage) {
1143 ASSERT(m_dragSourceAction & DragSourceActionDHTML);
1144 m_client.willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, dataTransfer);
1145 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1152 void DragController::doImageDrag(Element& element, const IntPoint& dragOrigin, const IntRect& layoutRect, Frame& frame, IntPoint& dragImageOffset, const DragState& state)
1154 IntPoint mouseDownPoint = dragOrigin;
1155 DragImage dragImage;
1156 IntPoint scaledOrigin;
1158 if (!element.renderer())
1161 ImageOrientationDescription orientationDescription(element.renderer()->shouldRespectImageOrientation(), element.renderer()->style().imageOrientation());
1163 Image* image = getImage(element);
1164 if (image && shouldUseCachedImageForDragImage(*image) && (dragImage = DragImage { createDragImageFromImage(image, element.renderer() ? orientationDescription : ImageOrientationDescription()) })) {
1165 dragImage = DragImage { fitDragImageToMaxSize(dragImage.get(), layoutRect.size(), maxDragImageSize()) };
1166 IntSize fittedSize = dragImageSize(dragImage.get());
1168 dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
1169 dragImage = DragImage { dissolveDragImageToFraction(dragImage.get(), DragImageAlpha) };
1171 // Properly orient the drag image and orient it differently if it's smaller than the original.
1172 float scale = fittedSize.width() / (float)layoutRect.width();
1173 float dx = scale * (layoutRect.x() - mouseDownPoint.x());
1174 float originY = layoutRect.y();
1176 // Compensate for accursed flipped coordinates in Cocoa.
1177 originY += layoutRect.height();
1179 float dy = scale * (originY - mouseDownPoint.y());
1180 scaledOrigin = IntPoint((int)(dx + 0.5), (int)(dy + 0.5));
1182 if (CachedImage* cachedImage = getCachedImage(element)) {
1183 dragImage = DragImage { createDragImageIconForCachedImageFilename(cachedImage->response().suggestedFilename()) };
1185 scaledOrigin = IntPoint(DragIconRightInset - dragImageSize(dragImage.get()).width(), DragIconBottomInset);
1192 dragImageOffset = mouseDownPoint + scaledOrigin;
1193 doSystemDrag(WTFMove(dragImage), dragImageOffset, dragOrigin, frame, state);
1196 void DragController::beginDrag(DragItem dragItem, Frame& frame, const IntPoint& mouseDownPoint, const IntPoint& mouseDraggedPoint, DataTransfer& dataTransfer, DragSourceAction dragSourceAction)
1198 ASSERT(!m_client.useLegacyDragClient());
1200 m_didInitiateDrag = true;
1201 m_dragInitiator = frame.document();
1203 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
1204 Ref<MainFrame> mainFrameProtector(m_page.mainFrame());
1205 RefPtr<FrameView> viewProtector = mainFrameProtector->view();
1207 auto mouseDownPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDownPoint));
1208 auto mouseDraggedPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDraggedPoint));
1210 m_client.beginDrag(WTFMove(dragItem), frame, mouseDownPointInRootViewCoordinates, mouseDraggedPointInRootViewCoordinates, dataTransfer, dragSourceAction);
1212 // DragClient::beginDrag can cause the drag controller to be deleted.
1213 if (!mainFrameProtector->page())
1216 // FIXME: This shouldn't be needed.
1217 cleanupAfterSystemDrag();
1220 void DragController::doSystemDrag(DragImage image, const IntPoint& dragLoc, const IntPoint& eventPos, Frame& frame, const DragState& state)
1222 m_didInitiateDrag = true;
1223 m_dragInitiator = frame.document();
1224 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
1225 Ref<MainFrame> frameProtector(m_page.mainFrame());
1226 RefPtr<FrameView> viewProtector = frameProtector->view();
1229 item.image = WTFMove(image);
1230 item.sourceAction = state.type;
1231 item.eventPositionInContentCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(eventPos));
1232 item.dragLocationInContentCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(dragLoc));
1233 item.eventPositionInWindowCoordinates = frame.view()->contentsToWindow(item.eventPositionInContentCoordinates);
1234 item.dragLocationInWindowCoordinates = frame.view()->contentsToWindow(item.dragLocationInContentCoordinates);
1235 if (auto element = state.source) {
1236 item.elementBounds = element->boundsInRootViewSpace();
1237 RefPtr<Element> link;
1238 if (element->isLink())
1241 for (auto& currentElement : elementLineage(element.get())) {
1242 if (currentElement.isLink()) {
1243 link = ¤tElement;
1249 auto titleAttribute = link->attributeWithoutSynchronization(HTMLNames::titleAttr);
1250 item.title = titleAttribute.isEmpty() ? link->innerText() : titleAttribute.string();
1251 item.url = frame.document()->completeURL(stripLeadingAndTrailingHTMLSpaces(link->getAttribute(HTMLNames::hrefAttr)));
1254 m_client.startDrag(WTFMove(item), *state.dataTransfer, frameProtector.get());
1255 // DragClient::startDrag can cause our Page to dispear, deallocating |this|.
1256 if (!frameProtector->page())
1259 cleanupAfterSystemDrag();
1262 // Manual drag caret manipulation
1263 void DragController::placeDragCaret(const IntPoint& windowPoint)
1265 mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(windowPoint));
1266 if (!m_documentUnderMouse)
1268 Frame* frame = m_documentUnderMouse->frame();
1269 FrameView* frameView = frame->view();
1272 IntPoint framePoint = frameView->windowToContents(windowPoint);
1274 m_page.dragCaretController().setCaretPosition(frame->visiblePositionForPoint(framePoint));
1277 bool DragController::shouldUseCachedImageForDragImage(const Image& image) const
1279 #if ENABLE(DATA_INTERACTION)
1280 UNUSED_PARAM(image);
1283 return image.size().height() * image.size().width() <= MaxOriginalImageArea;
1287 #endif // ENABLE(DRAG_SUPPORT)
1289 } // namespace WebCore