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 void DragController::dragExited(const DragData& dragData)
225 if (RefPtr<FrameView> v = m_page.mainFrame().view()) {
226 #if ENABLE(DASHBOARD_SUPPORT)
227 DataTransferAccessPolicy policy = (m_page.mainFrame().settings().usesDashboardBackwardCompatibilityMode() && (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin().isLocal()))
228 ? DataTransferAccessPolicy::Readable : DataTransferAccessPolicy::TypesReadable;
230 DataTransferAccessPolicy policy = DataTransferAccessPolicy::TypesReadable;
232 auto dataTransfer = DataTransfer::createForDrop(policy, dragData);
233 dataTransfer->setSourceOperation(dragData.draggingSourceOperationMask());
234 m_page.mainFrame().eventHandler().cancelDragAndDrop(createMouseEvent(dragData), dataTransfer);
235 dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb); // Invalidate dataTransfer here for security.
237 mouseMovedIntoDocument(nullptr);
238 if (m_fileInputElementUnderMouse)
239 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
240 m_fileInputElementUnderMouse = nullptr;
243 DragOperation DragController::dragUpdated(const DragData& dragData)
245 return dragEnteredOrUpdated(dragData);
248 inline static bool dragIsHandledByDocument(DragController::DragHandlingMethod dragHandlingMethod)
250 if (dragHandlingMethod == DragController::DragHandlingMethod::None)
253 if (dragHandlingMethod == DragController::DragHandlingMethod::PageLoad)
259 bool DragController::performDragOperation(const DragData& dragData)
261 SetForScope<bool> isPerformingDrop(m_isPerformingDrop, true);
262 TemporarySelectionChange ignoreSelectionChanges(m_page.focusController().focusedOrMainFrame(), std::nullopt, TemporarySelectionOptionIgnoreSelectionChanges);
264 m_documentUnderMouse = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
266 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = ShouldOpenExternalURLsPolicy::ShouldNotAllow;
267 if (m_documentUnderMouse)
268 shouldOpenExternalURLsPolicy = m_documentUnderMouse->shouldOpenExternalURLsPolicyToPropagate();
270 if ((m_dragDestinationAction & DragDestinationActionDHTML) && dragIsHandledByDocument(m_dragHandlingMethod)) {
271 m_client.willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
272 Ref<MainFrame> mainFrame(m_page.mainFrame());
273 bool preventedDefault = false;
274 if (mainFrame->view()) {
275 // Sending an event can result in the destruction of the view and part.
276 auto dataTransfer = DataTransfer::createForDrop(DataTransferAccessPolicy::Readable, dragData);
277 dataTransfer->setSourceOperation(dragData.draggingSourceOperationMask());
278 preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), dataTransfer);
279 dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb); // Invalidate dataTransfer here for security.
281 if (preventedDefault) {
283 m_documentUnderMouse = nullptr;
288 if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
289 m_client.didConcludeEditDrag();
290 m_documentUnderMouse = nullptr;
295 m_documentUnderMouse = nullptr;
298 if (operationForLoad(dragData) == DragOperationNone)
301 auto urlString = dragData.asURL();
302 if (urlString.isEmpty())
305 m_client.willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
306 m_page.mainFrame().loader().load(FrameLoadRequest(m_page.mainFrame(), { urlString }, shouldOpenExternalURLsPolicy));
310 void DragController::mouseMovedIntoDocument(Document* newDocument)
312 if (m_documentUnderMouse == newDocument)
315 // If we were over another document clear the selection
316 if (m_documentUnderMouse)
318 m_documentUnderMouse = newDocument;
321 DragOperation DragController::dragEnteredOrUpdated(const DragData& dragData)
323 mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(dragData.clientPosition()));
325 m_dragDestinationAction = dragData.dragDestinationAction();
326 if (m_dragDestinationAction == DragDestinationActionNone) {
327 clearDragCaret(); // FIXME: Why not call mouseMovedIntoDocument(nullptr)?
328 return DragOperationNone;
331 DragOperation dragOperation = DragOperationNone;
332 m_dragHandlingMethod = tryDocumentDrag(dragData, m_dragDestinationAction, dragOperation);
333 if (m_dragHandlingMethod == DragHandlingMethod::None && (m_dragDestinationAction & DragDestinationActionLoad)) {
334 dragOperation = operationForLoad(dragData);
335 if (dragOperation != DragOperationNone)
336 m_dragHandlingMethod = DragHandlingMethod::PageLoad;
339 updateSupportedTypeIdentifiersForDragHandlingMethod(m_dragHandlingMethod, dragData);
340 return dragOperation;
343 static HTMLInputElement* asFileInput(Node& node)
345 if (!is<HTMLInputElement>(node))
348 auto* inputElement = &downcast<HTMLInputElement>(node);
350 // If this is a button inside of the a file input, move up to the file input.
351 if (inputElement->isTextButton() && is<ShadowRoot>(inputElement->treeScope().rootNode())) {
352 auto& host = *downcast<ShadowRoot>(inputElement->treeScope().rootNode()).host();
353 inputElement = is<HTMLInputElement>(host) ? &downcast<HTMLInputElement>(host) : nullptr;
356 return inputElement && inputElement->isFileUpload() ? inputElement : nullptr;
359 // This can return null if an empty document is loaded.
360 static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
362 Frame* frame = documentUnderMouse->frame();
363 float zoomFactor = frame ? frame->pageZoomFactor() : 1;
364 LayoutPoint point(p.x() * zoomFactor, p.y() * zoomFactor);
366 HitTestResult result(point);
367 documentUnderMouse->renderView()->hitTest(HitTestRequest(), result);
369 Node* node = result.innerNode();
370 while (node && !is<Element>(*node))
371 node = node->parentNode();
373 node = node->deprecatedShadowAncestorNode();
375 return downcast<Element>(node);
378 #if !ENABLE(DATA_INTERACTION)
380 void DragController::updateSupportedTypeIdentifiersForDragHandlingMethod(DragHandlingMethod, const DragData&) const
386 DragController::DragHandlingMethod DragController::tryDocumentDrag(const DragData& dragData, DragDestinationAction actionMask, DragOperation& dragOperation)
388 if (!m_documentUnderMouse)
389 return DragHandlingMethod::None;
391 if (m_dragInitiator && !m_documentUnderMouse->securityOrigin().canReceiveDragData(m_dragInitiator->securityOrigin()))
392 return DragHandlingMethod::None;
394 bool isHandlingDrag = false;
395 if (actionMask & DragDestinationActionDHTML) {
396 isHandlingDrag = tryDHTMLDrag(dragData, dragOperation);
397 // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
398 // tryDHTMLDrag fires dragenter event. The event listener that listens
399 // to this event may create a nested message loop (open a modal dialog),
400 // which could process dragleave event and reset m_documentUnderMouse in
402 if (!m_documentUnderMouse)
403 return DragHandlingMethod::None;
406 // It's unclear why this check is after tryDHTMLDrag.
407 // We send drag events in tryDHTMLDrag and that may be the reason.
408 RefPtr<FrameView> frameView = m_documentUnderMouse->view();
410 return DragHandlingMethod::None;
412 if (isHandlingDrag) {
414 return DragHandlingMethod::NonDefault;
417 if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
418 if (dragData.containsColor()) {
419 dragOperation = DragOperationGeneric;
420 return DragHandlingMethod::SetColor;
423 IntPoint point = frameView->windowToContents(dragData.clientPosition());
424 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
426 return DragHandlingMethod::None;
428 HTMLInputElement* elementAsFileInput = asFileInput(*element);
429 if (m_fileInputElementUnderMouse != elementAsFileInput) {
430 if (m_fileInputElementUnderMouse)
431 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
432 m_fileInputElementUnderMouse = elementAsFileInput;
435 if (!m_fileInputElementUnderMouse)
436 m_page.dragCaretController().setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
440 Frame* innerFrame = element->document().frame();
441 dragOperation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
442 m_numberOfItemsToBeAccepted = 0;
444 unsigned numberOfFiles = dragData.numberOfFiles();
445 if (m_fileInputElementUnderMouse) {
446 if (m_fileInputElementUnderMouse->isDisabledFormControl())
447 m_numberOfItemsToBeAccepted = 0;
448 else if (m_fileInputElementUnderMouse->multiple())
449 m_numberOfItemsToBeAccepted = numberOfFiles;
450 else if (numberOfFiles > 1)
451 m_numberOfItemsToBeAccepted = 0;
453 m_numberOfItemsToBeAccepted = 1;
455 if (!m_numberOfItemsToBeAccepted)
456 dragOperation = DragOperationNone;
457 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(m_numberOfItemsToBeAccepted);
459 // We are not over a file input element. The dragged item(s) will only
460 // be loaded into the view the number of dragged items is 1.
461 m_numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
464 if (m_fileInputElementUnderMouse)
465 return DragHandlingMethod::UploadFile;
467 if (m_page.dragCaretController().isContentRichlyEditable())
468 return DragHandlingMethod::EditRichText;
470 return DragHandlingMethod::EditPlainText;
473 // We are not over an editable region. Make sure we're clearing any prior drag cursor.
475 if (m_fileInputElementUnderMouse)
476 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
477 m_fileInputElementUnderMouse = nullptr;
478 return DragHandlingMethod::None;
481 DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
483 m_dragSourceAction = m_client.dragSourceActionMaskForPoint(rootViewPoint);
484 return m_dragSourceAction;
487 DragOperation DragController::operationForLoad(const DragData& dragData)
489 Document* document = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
491 bool pluginDocumentAcceptsDrags = false;
493 if (is<PluginDocument>(document)) {
494 const Widget* widget = downcast<PluginDocument>(*document).pluginWidget();
495 const PluginViewBase* pluginView = is<PluginViewBase>(widget) ? downcast<PluginViewBase>(widget) : nullptr;
498 pluginDocumentAcceptsDrags = pluginView->shouldAllowNavigationFromDrags();
501 if (document && (m_didInitiateDrag || (is<PluginDocument>(*document) && !pluginDocumentAcceptsDrags) || document->hasEditableStyle()))
502 return DragOperationNone;
503 return dragOperation(dragData);
506 static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
508 Ref<Frame> protector(*frame);
509 frame->selection().setSelection(dragCaret);
510 if (frame->selection().selection().isNone()) {
511 dragCaret = frame->visiblePositionForPoint(point);
512 frame->selection().setSelection(dragCaret);
513 range = dragCaret.toNormalizedRange();
515 return !frame->selection().isNone() && frame->selection().selection().isContentEditable();
518 bool DragController::dispatchTextInputEventFor(Frame* innerFrame, const DragData& dragData)
520 ASSERT(m_page.dragCaretController().hasCaret());
521 String text = m_page.dragCaretController().isContentRichlyEditable() ? emptyString() : dragData.asPlainText();
522 Element* target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
523 return target->dispatchEvent(TextEvent::createForDrop(innerFrame->document()->domWindow(), text));
526 bool DragController::concludeEditDrag(const DragData& dragData)
528 RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
529 if (m_fileInputElementUnderMouse) {
530 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
531 m_fileInputElementUnderMouse = nullptr;
534 if (!m_documentUnderMouse)
537 IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData.clientPosition());
538 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
541 RefPtr<Frame> innerFrame = element->document().frame();
544 if (m_page.dragCaretController().hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
547 if (dragData.containsColor()) {
548 Color color = dragData.asColor();
549 if (!color.isValid())
551 RefPtr<Range> innerRange = innerFrame->selection().toNormalizedRange();
552 RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
553 style->setProperty(CSSPropertyColor, color.serialized(), false);
554 if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
556 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
557 innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
561 if (dragData.containsFiles() && fileInput) {
562 // fileInput should be the element we hit tested for, unless it was made
563 // display:none in a drop event handler.
564 ASSERT(fileInput == element || !fileInput->renderer());
565 if (fileInput->isDisabledFormControl())
568 return fileInput->receiveDroppedFiles(dragData);
571 if (!m_page.dragController().canProcessDrag(dragData))
574 VisibleSelection dragCaret = m_page.dragCaretController().caretPosition();
575 RefPtr<Range> range = dragCaret.toNormalizedRange();
576 RefPtr<Element> rootEditableElement = innerFrame->selection().selection().rootEditableElement();
578 // For range to be null a WebKit client must have done something bad while
579 // manually controlling drag behaviour
583 ResourceCacheValidationSuppressor validationSuppressor(range->ownerDocument().cachedResourceLoader());
584 auto& editor = innerFrame->editor();
585 bool isMove = dragIsMove(innerFrame->selection(), dragData);
586 if (isMove || dragCaret.isContentRichlyEditable()) {
587 bool chosePlainText = false;
588 RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, *innerFrame, *range, true, chosePlainText);
589 if (!fragment || !editor.shouldInsertFragment(*fragment, range.get(), EditorInsertAction::Dropped))
592 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
594 if (editor.client() && editor.client()->performTwoStepDrop(*fragment, *range, isMove))
598 // NSTextView behavior is to always smart delete on moving a selection,
599 // but only to smart insert if the selection granularity is word granularity.
600 bool smartDelete = editor.smartInsertDeleteEnabled();
601 bool smartInsert = smartDelete && innerFrame->selection().granularity() == WordGranularity && dragData.canSmartReplace();
602 MoveSelectionCommand::create(fragment.releaseNonNull(), dragCaret.base(), smartInsert, smartDelete)->apply();
604 if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
605 ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
606 if (dragData.canSmartReplace())
607 options |= ReplaceSelectionCommand::SmartReplace;
609 options |= ReplaceSelectionCommand::MatchStyle;
610 ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment.releaseNonNull(), options, EditActionInsertFromDrop)->apply();
614 String text = dragData.asPlainText();
615 if (text.isEmpty() || !editor.shouldInsertText(text, range.get(), EditorInsertAction::Dropped))
618 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
619 RefPtr<DocumentFragment> fragment = createFragmentFromText(*range, text);
623 if (editor.client() && editor.client()->performTwoStepDrop(*fragment, *range, isMove))
626 if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
627 ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment.get(), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting, EditActionInsertFromDrop)->apply();
630 if (rootEditableElement) {
631 if (Frame* frame = rootEditableElement->document().frame())
632 frame->eventHandler().updateDragStateAfterEditDragIfNeeded(*rootEditableElement);
638 bool DragController::canProcessDrag(const DragData& dragData)
640 IntPoint point = m_page.mainFrame().view()->windowToContents(dragData.clientPosition());
641 HitTestResult result = HitTestResult(point);
642 if (!m_page.mainFrame().contentRenderer())
645 result = m_page.mainFrame().eventHandler().hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
647 if (!result.innerNonSharedNode())
650 DragData::DraggingPurpose dragPurpose = DragData::DraggingPurpose::ForEditing;
651 if (asFileInput(*result.innerNonSharedNode()))
652 dragPurpose = DragData::DraggingPurpose::ForFileUpload;
654 if (!dragData.containsCompatibleContent(dragPurpose))
657 if (dragPurpose == DragData::DraggingPurpose::ForFileUpload)
660 if (is<HTMLPlugInElement>(*result.innerNonSharedNode())) {
661 if (!downcast<HTMLPlugInElement>(result.innerNonSharedNode())->canProcessDrag() && !result.innerNonSharedNode()->hasEditableStyle())
663 } else if (!result.innerNonSharedNode()->hasEditableStyle())
666 if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
672 static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
674 // This is designed to match IE's operation fallback for the case where
675 // the page calls preventDefault() in a drag event but doesn't set dropEffect.
676 if (srcOpMask == DragOperationEvery)
677 return DragOperationCopy;
678 if (srcOpMask == DragOperationNone)
679 return DragOperationNone;
680 if (srcOpMask & DragOperationMove)
681 return DragOperationMove;
682 if (srcOpMask & DragOperationGeneric)
683 return DragController::platformGenericDragOperation();
684 if (srcOpMask & DragOperationCopy)
685 return DragOperationCopy;
686 if (srcOpMask & DragOperationLink)
687 return DragOperationLink;
689 // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
690 return DragOperationGeneric;
693 bool DragController::tryDHTMLDrag(const DragData& dragData, DragOperation& operation)
695 ASSERT(m_documentUnderMouse);
696 Ref<MainFrame> mainFrame(m_page.mainFrame());
697 RefPtr<FrameView> viewProtector = mainFrame->view();
701 #if ENABLE(DASHBOARD_SUPPORT)
702 DataTransferAccessPolicy policy = (mainFrame->settings().usesDashboardBackwardCompatibilityMode() && m_documentUnderMouse->securityOrigin().isLocal()) ?
703 DataTransferAccessPolicy::Readable : DataTransferAccessPolicy::TypesReadable;
705 DataTransferAccessPolicy policy = DataTransferAccessPolicy::TypesReadable;
707 auto dataTransfer = DataTransfer::createForDrop(policy, dragData);
708 DragOperation srcOpMask = dragData.draggingSourceOperationMask();
709 dataTransfer->setSourceOperation(srcOpMask);
711 PlatformMouseEvent event = createMouseEvent(dragData);
712 if (!mainFrame->eventHandler().updateDragAndDrop(event, dataTransfer)) {
713 dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb); // Invalidate dataTransfer here for security.
717 operation = dataTransfer->destinationOperation();
718 if (dataTransfer->dropEffectIsUninitialized())
719 operation = defaultOperationForDrag(srcOpMask);
720 else if (!(srcOpMask & operation)) {
721 // The element picked an operation which is not supported by the source
722 operation = DragOperationNone;
725 dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb); // Invalidate dataTransfer here for security.
729 static bool imageElementIsDraggable(const HTMLImageElement& image, const Frame& sourceFrame)
731 if (sourceFrame.settings().loadsImagesAutomatically())
734 auto* renderer = image.renderer();
735 if (!is<RenderImage>(renderer))
738 auto* cachedImage = downcast<RenderImage>(*renderer).cachedImage();
739 return cachedImage && !cachedImage->errorOccurred() && cachedImage->imageForRenderer(renderer);
742 Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
744 state.type = (sourceFrame->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
747 #if ENABLE(ATTACHMENT_ELEMENT)
748 if (is<HTMLAttachmentElement>(startElement)) {
749 auto selection = sourceFrame->selection().selection();
750 bool isSingleAttachmentSelection = selection.start() == Position(startElement, Position::PositionIsBeforeAnchor) && selection.end() == Position(startElement, Position::PositionIsAfterAnchor);
751 bool isAttachmentElementInCurrentSelection = false;
752 if (auto selectedRange = selection.toNormalizedRange()) {
753 auto compareResult = selectedRange->compareNode(*startElement);
754 isAttachmentElementInCurrentSelection = !compareResult.hasException() && compareResult.releaseReturnValue() == Range::NODE_INSIDE;
757 if (!isAttachmentElementInCurrentSelection || isSingleAttachmentSelection) {
758 state.type = DragSourceActionAttachment;
764 for (auto* element = startElement; element; element = element->parentOrShadowHostElement()) {
765 auto* renderer = element->renderer();
769 EUserDrag dragMode = renderer->style().userDrag();
770 if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
771 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
774 if (dragMode == DRAG_AUTO) {
775 if ((m_dragSourceAction & DragSourceActionImage)
776 && is<HTMLImageElement>(*element)
777 && imageElementIsDraggable(downcast<HTMLImageElement>(*element), *sourceFrame)) {
778 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
781 if ((m_dragSourceAction & DragSourceActionLink) && isDraggableLink(*element)) {
782 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
785 #if ENABLE(ATTACHMENT_ELEMENT)
786 if ((m_dragSourceAction & DragSourceActionAttachment)
787 && is<HTMLAttachmentElement>(*element)
788 && downcast<HTMLAttachmentElement>(*element).file()) {
789 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionAttachment);
796 // We either have nothing to drag or we have a selection and we're not over a draggable element.
797 return (state.type & DragSourceActionSelection) ? startElement : nullptr;
800 static CachedImage* getCachedImage(Element& element)
802 RenderObject* renderer = element.renderer();
803 if (!is<RenderImage>(renderer))
805 auto& image = downcast<RenderImage>(*renderer);
806 return image.cachedImage();
809 static Image* getImage(Element& element)
811 CachedImage* cachedImage = getCachedImage(element);
812 // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
813 // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
814 // which would be empty when asking the cached BitmapImages.
815 return (cachedImage && !cachedImage->errorOccurred()) ?
816 cachedImage->image() : nullptr;
819 static void selectElement(Element& element)
821 RefPtr<Range> range = element.document().createRange();
822 range->selectNode(element);
823 element.document().frame()->selection().setSelection(VisibleSelection(*range, DOWNSTREAM));
826 static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
828 // dragImageOffset is the cursor position relative to the lower-left corner of the image.
830 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
831 const int yOffset = dragImageOffset.y();
833 const int yOffset = -dragImageOffset.y();
837 return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
839 return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
842 static FloatPoint dragImageAnchorPointForSelectionDrag(Frame& frame, const IntPoint& mouseDraggedPoint)
844 IntRect draggingRect = enclosingIntRect(frame.selection().selectionBounds());
846 float x = (mouseDraggedPoint.x() - draggingRect.x()) / (float)draggingRect.width();
847 float y = (mouseDraggedPoint.y() - draggingRect.y()) / (float)draggingRect.height();
849 return FloatPoint { x, y };
852 static IntPoint dragLocForSelectionDrag(Frame& src)
854 IntRect draggingRect = enclosingIntRect(src.selection().selectionBounds());
855 int xpos = draggingRect.maxX();
856 xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
857 int ypos = draggingRect.maxY();
859 // Deal with flipped coordinates on Mac
860 ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
862 ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
864 return IntPoint(xpos, ypos);
867 bool DragController::startDrag(Frame& src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
869 if (!src.view() || !src.contentRenderer() || !state.source)
872 Ref<Frame> protector(src);
873 HitTestResult hitTestResult = src.eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
875 // FIXME(136836): Investigate whether all elements should use the containsIncludingShadowDOM() path here.
876 bool includeShadowDOM = false;
878 includeShadowDOM = state.source->isMediaElement();
880 bool sourceContainsHitNode;
881 if (!includeShadowDOM)
882 sourceContainsHitNode = state.source->contains(hitTestResult.innerNode());
884 sourceContainsHitNode = state.source->containsIncludingShadowDOM(hitTestResult.innerNode());
886 if (!sourceContainsHitNode) {
887 // The original node being dragged isn't under the drag origin anymore... maybe it was
888 // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
889 // something that's not actually under the drag origin.
893 URL linkURL = hitTestResult.absoluteLinkURL();
894 URL imageURL = hitTestResult.absoluteImageURL();
895 #if ENABLE(ATTACHMENT_ELEMENT)
896 URL attachmentURL = hitTestResult.absoluteAttachmentURL();
897 m_draggingAttachmentURL = URL();
900 IntPoint mouseDraggedPoint = src.view()->windowToContents(dragEvent.position());
902 m_draggingImageURL = URL();
903 m_sourceDragOperation = srcOp;
906 IntPoint dragLoc(0, 0);
907 IntPoint dragImageOffset(0, 0);
909 ASSERT(state.dataTransfer);
911 DataTransfer& dataTransfer = *state.dataTransfer;
912 if (state.type == DragSourceActionDHTML) {
913 dragImage = DragImage { dataTransfer.createDragImage(dragImageOffset) };
914 // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
915 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
917 dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
918 m_dragOffset = dragImageOffset;
922 if (state.type == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty()) {
923 // Selection, image, and link drags receive a default set of allowed drag operations that
925 // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
926 m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
929 ASSERT(state.source);
930 Element& element = *state.source;
932 bool mustUseLegacyDragClient = dataTransfer.pasteboard().hasData() || m_client.useLegacyDragClient();
934 IntRect dragImageBounds;
935 Image* image = getImage(element);
936 if (state.type == DragSourceActionSelection) {
937 PasteboardWriterData pasteboardWriterData;
939 if (!dataTransfer.pasteboard().hasData()) {
940 if (src.selection().selection().isNone()) {
941 // The page may have cleared out the selection in the dragstart handler, in which case we should bail
942 // out of the drag, since there is no content to write to the pasteboard.
946 // FIXME: This entire block is almost identical to the code in Editor::copy, and the code should be shared.
947 RefPtr<Range> selectionRange = src.selection().toNormalizedRange();
948 ASSERT(selectionRange);
950 src.editor().willWriteSelectionToPasteboard(selectionRange.get());
952 if (enclosingTextFormControl(src.selection().selection().start())) {
953 if (mustUseLegacyDragClient)
954 dataTransfer.pasteboard().writePlainText(src.editor().selectedTextForDataTransfer(), Pasteboard::CannotSmartReplace);
956 PasteboardWriterData::PlainText plainText;
957 plainText.canSmartCopyOrDelete = false;
958 plainText.text = src.editor().selectedTextForDataTransfer();
959 pasteboardWriterData.setPlainText(WTFMove(plainText));
962 if (mustUseLegacyDragClient) {
963 #if PLATFORM(COCOA) || PLATFORM(GTK)
964 src.editor().writeSelectionToPasteboard(dataTransfer.pasteboard());
966 // FIXME: Convert all other platforms to match Mac and delete this.
967 dataTransfer.pasteboard().writeSelection(*selectionRange, src.editor().canSmartCopyOrDelete(), src, IncludeImageAltTextForDataTransfer);
971 src.editor().writeSelection(pasteboardWriterData);
976 src.editor().didWriteSelectionToPasteboard();
978 m_client.willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, dataTransfer);
980 TextIndicatorData textIndicator;
981 dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
982 if (textIndicator.contentImage)
983 dragImage.setIndicatorData(textIndicator);
984 dragLoc = dragLocForSelectionDrag(src);
985 m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
991 if (mustUseLegacyDragClient) {
992 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
997 dragItem.imageAnchorPoint = dragImageAnchorPointForSelectionDrag(src, mouseDraggedPoint);
998 dragItem.image = WTFMove(dragImage);
999 dragItem.data = WTFMove(pasteboardWriterData);
1001 beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);
1006 if (!src.document()->securityOrigin().canDisplay(linkURL)) {
1007 src.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to drag local resource: " + linkURL.stringCenterEllipsizedToLength());
1011 if (!imageURL.isEmpty() && image && !image->isNull() && (m_dragSourceAction & DragSourceActionImage)) {
1012 // We shouldn't be starting a drag for an image that can't provide an extension.
1013 // This is an early detection for problems encountered later upon drop.
1014 ASSERT(!image->filenameExtension().isEmpty());
1015 if (!dataTransfer.pasteboard().hasData()) {
1016 m_draggingImageURL = imageURL;
1017 if (element.isContentRichlyEditable())
1018 selectElement(element);
1019 declareAndWriteDragImage(dataTransfer, element, !linkURL.isEmpty() ? linkURL : imageURL, hitTestResult.altDisplayString());
1022 m_client.willPerformDragSourceAction(DragSourceActionImage, dragOrigin, dataTransfer);
1025 doImageDrag(element, dragOrigin, hitTestResult.imageRect(), src, m_dragOffset, state);
1027 // DHTML defined drag image
1028 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1034 if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
1035 PasteboardWriterData pasteboardWriterData;
1037 String textContentWithSimplifiedWhiteSpace = hitTestResult.textContent().simplifyWhiteSpace();
1039 if (!dataTransfer.pasteboard().hasData()) {
1040 // Simplify whitespace so the title put on the dataTransfer resembles what the user sees
1041 // on the web page. This includes replacing newlines with spaces.
1042 if (mustUseLegacyDragClient)
1043 src.editor().copyURL(linkURL, textContentWithSimplifiedWhiteSpace, dataTransfer.pasteboard());
1045 pasteboardWriterData.setURL(src.editor().pasteboardWriterURL(linkURL, textContentWithSimplifiedWhiteSpace));
1047 // Make sure the pasteboard also contains trustworthy link data
1048 // but don't overwrite more general pasteboard types.
1049 PasteboardURL pasteboardURL;
1050 pasteboardURL.url = linkURL;
1051 pasteboardURL.title = hitTestResult.textContent();
1052 dataTransfer.pasteboard().writeTrustworthyWebURLsPboardType(pasteboardURL);
1055 const VisibleSelection& sourceSelection = src.selection().selection();
1056 if (sourceSelection.isCaret() && sourceSelection.isContentEditable()) {
1057 // a user can initiate a drag on a link without having any text
1058 // selected. In this case, we should expand the selection to
1059 // the enclosing anchor element
1060 Position pos = sourceSelection.base();
1061 Node* node = enclosingAnchorElement(pos);
1063 src.selection().setSelection(VisibleSelection::selectionFromContentsOfNode(node));
1066 m_client.willPerformDragSourceAction(DragSourceActionLink, dragOrigin, dataTransfer);
1068 TextIndicatorData textIndicator;
1069 dragImage = DragImage { createDragImageForLink(element, linkURL, textContentWithSimplifiedWhiteSpace, textIndicator, src.settings().fontRenderingMode(), m_page.deviceScaleFactor()) };
1071 m_dragOffset = dragOffsetForLinkDragImage(dragImage.get());
1072 dragLoc = IntPoint(dragOrigin.x() + m_dragOffset.x(), dragOrigin.y() + m_dragOffset.y());
1073 dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
1074 if (textIndicator.contentImage)
1075 dragImage.setIndicatorData(textIndicator);
1079 if (mustUseLegacyDragClient) {
1080 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1085 dragItem.imageAnchorPoint = dragImage ? anchorPointForLinkDragImage(dragImage.get()) : FloatPoint();
1086 dragItem.image = WTFMove(dragImage);
1087 dragItem.data = WTFMove(pasteboardWriterData);
1089 beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);
1094 #if ENABLE(ATTACHMENT_ELEMENT)
1095 if (is<HTMLAttachmentElement>(element) && m_dragSourceAction & DragSourceActionAttachment) {
1096 auto* attachmentRenderer = downcast<HTMLAttachmentElement>(element).renderer();
1097 if (!attachmentRenderer)
1100 src.editor().setIgnoreSelectionChanges(true);
1101 auto previousSelection = src.selection().selection();
1102 if (!dataTransfer.pasteboard().hasData()) {
1103 selectElement(element);
1104 if (!attachmentURL.isEmpty()) {
1105 // Use the attachment URL specified by the file attribute to populate the pasteboard.
1106 m_draggingAttachmentURL = attachmentURL;
1107 declareAndWriteAttachment(dataTransfer, element, attachmentURL);
1108 } else if (src.editor().client()) {
1110 // Otherwise, if no file URL is specified, call out to the injected bundle to populate the pasteboard with data.
1111 auto& editor = src.editor();
1112 editor.willWriteSelectionToPasteboard(src.selection().toNormalizedRange().get());
1113 editor.writeSelectionToPasteboard(dataTransfer.pasteboard());
1114 editor.didWriteSelectionToPasteboard();
1119 m_client.willPerformDragSourceAction(DragSourceActionAttachment, dragOrigin, dataTransfer);
1122 TextIndicatorData textIndicator;
1123 attachmentRenderer->setShouldDrawBorder(false);
1124 dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
1125 attachmentRenderer->setShouldDrawBorder(true);
1126 if (textIndicator.contentImage)
1127 dragImage.setIndicatorData(textIndicator);
1128 dragLoc = dragLocForSelectionDrag(src);
1129 m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
1131 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1132 src.selection().setSelection(previousSelection);
1133 src.editor().setIgnoreSelectionChanges(false);
1138 if (state.type == DragSourceActionDHTML && dragImage) {
1139 ASSERT(m_dragSourceAction & DragSourceActionDHTML);
1140 m_client.willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, dataTransfer);
1141 doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, src, state);
1148 void DragController::doImageDrag(Element& element, const IntPoint& dragOrigin, const IntRect& layoutRect, Frame& frame, IntPoint& dragImageOffset, const DragState& state)
1150 IntPoint mouseDownPoint = dragOrigin;
1151 DragImage dragImage;
1152 IntPoint scaledOrigin;
1154 if (!element.renderer())
1157 ImageOrientationDescription orientationDescription(element.renderer()->shouldRespectImageOrientation(), element.renderer()->style().imageOrientation());
1159 Image* image = getImage(element);
1160 if (image && shouldUseCachedImageForDragImage(*image) && (dragImage = DragImage { createDragImageFromImage(image, element.renderer() ? orientationDescription : ImageOrientationDescription()) })) {
1161 dragImage = DragImage { fitDragImageToMaxSize(dragImage.get(), layoutRect.size(), maxDragImageSize()) };
1162 IntSize fittedSize = dragImageSize(dragImage.get());
1164 dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
1165 dragImage = DragImage { dissolveDragImageToFraction(dragImage.get(), DragImageAlpha) };
1167 // Properly orient the drag image and orient it differently if it's smaller than the original.
1168 float scale = fittedSize.width() / (float)layoutRect.width();
1169 float dx = scale * (layoutRect.x() - mouseDownPoint.x());
1170 float originY = layoutRect.y();
1172 // Compensate for accursed flipped coordinates in Cocoa.
1173 originY += layoutRect.height();
1175 float dy = scale * (originY - mouseDownPoint.y());
1176 scaledOrigin = IntPoint((int)(dx + 0.5), (int)(dy + 0.5));
1178 if (CachedImage* cachedImage = getCachedImage(element)) {
1179 dragImage = DragImage { createDragImageIconForCachedImageFilename(cachedImage->response().suggestedFilename()) };
1181 scaledOrigin = IntPoint(DragIconRightInset - dragImageSize(dragImage.get()).width(), DragIconBottomInset);
1188 dragImageOffset = mouseDownPoint + scaledOrigin;
1189 doSystemDrag(WTFMove(dragImage), dragImageOffset, dragOrigin, frame, state);
1192 void DragController::beginDrag(DragItem dragItem, Frame& frame, const IntPoint& mouseDownPoint, const IntPoint& mouseDraggedPoint, DataTransfer& dataTransfer, DragSourceAction dragSourceAction)
1194 ASSERT(!m_client.useLegacyDragClient());
1196 m_didInitiateDrag = true;
1197 m_dragInitiator = frame.document();
1199 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
1200 Ref<MainFrame> mainFrameProtector(m_page.mainFrame());
1201 RefPtr<FrameView> viewProtector = mainFrameProtector->view();
1203 auto mouseDownPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDownPoint));
1204 auto mouseDraggedPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDraggedPoint));
1206 m_client.beginDrag(WTFMove(dragItem), frame, mouseDownPointInRootViewCoordinates, mouseDraggedPointInRootViewCoordinates, dataTransfer, dragSourceAction);
1208 // DragClient::beginDrag can cause the drag controller to be deleted.
1209 if (!mainFrameProtector->page())
1212 // FIXME: This shouldn't be needed.
1213 cleanupAfterSystemDrag();
1216 void DragController::doSystemDrag(DragImage image, const IntPoint& dragLoc, const IntPoint& eventPos, Frame& frame, const DragState& state)
1218 m_didInitiateDrag = true;
1219 m_dragInitiator = frame.document();
1220 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
1221 Ref<MainFrame> frameProtector(m_page.mainFrame());
1222 RefPtr<FrameView> viewProtector = frameProtector->view();
1225 item.image = WTFMove(image);
1226 item.sourceAction = state.type;
1227 item.eventPositionInContentCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(eventPos));
1228 item.dragLocationInContentCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(dragLoc));
1229 item.eventPositionInWindowCoordinates = frame.view()->contentsToWindow(item.eventPositionInContentCoordinates);
1230 item.dragLocationInWindowCoordinates = frame.view()->contentsToWindow(item.dragLocationInContentCoordinates);
1231 if (auto element = state.source) {
1232 item.elementBounds = element->boundsInRootViewSpace();
1233 RefPtr<Element> link;
1234 if (element->isLink())
1237 for (auto& currentElement : elementLineage(element.get())) {
1238 if (currentElement.isLink()) {
1239 link = ¤tElement;
1245 auto titleAttribute = link->attributeWithoutSynchronization(HTMLNames::titleAttr);
1246 item.title = titleAttribute.isEmpty() ? link->innerText() : titleAttribute.string();
1247 item.url = frame.document()->completeURL(stripLeadingAndTrailingHTMLSpaces(link->getAttribute(HTMLNames::hrefAttr)));
1250 m_client.startDrag(WTFMove(item), *state.dataTransfer, frameProtector.get());
1251 // DragClient::startDrag can cause our Page to dispear, deallocating |this|.
1252 if (!frameProtector->page())
1255 cleanupAfterSystemDrag();
1258 // Manual drag caret manipulation
1259 void DragController::placeDragCaret(const IntPoint& windowPoint)
1261 mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(windowPoint));
1262 if (!m_documentUnderMouse)
1264 Frame* frame = m_documentUnderMouse->frame();
1265 FrameView* frameView = frame->view();
1268 IntPoint framePoint = frameView->windowToContents(windowPoint);
1270 m_page.dragCaretController().setCaretPosition(frame->visiblePositionForPoint(framePoint));
1273 bool DragController::shouldUseCachedImageForDragImage(const Image& image) const
1275 #if ENABLE(DATA_INTERACTION)
1276 UNUSED_PARAM(image);
1279 return image.size().height() * image.size().width() <= MaxOriginalImageArea;
1283 #endif // ENABLE(DRAG_SUPPORT)
1285 } // namespace WebCore