File inputs only accept UTI types that can be inserted into contenteditable areas...
[WebKit.git] / Source / WebCore / page / DragController.cpp
1 /*
2  * Copyright (C) 2007-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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. 
24  */
25
26 #include "config.h"
27 #include "DragController.h"
28
29 #include "HTMLAnchorElement.h"
30 #include "SVGAElement.h"
31
32 #if ENABLE(DRAG_SUPPORT)
33 #include "CachedImage.h"
34 #include "CachedResourceLoader.h"
35 #include "ClientRect.h"
36 #include "DataTransfer.h"
37 #include "Document.h"
38 #include "DocumentFragment.h"
39 #include "DragActions.h"
40 #include "DragClient.h"
41 #include "DragData.h"
42 #include "DragImage.h"
43 #include "DragState.h"
44 #include "Editing.h"
45 #include "Editor.h"
46 #include "EditorClient.h"
47 #include "EventHandler.h"
48 #include "FloatRect.h"
49 #include "FrameLoadRequest.h"
50 #include "FrameLoader.h"
51 #include "FrameSelection.h"
52 #include "FrameView.h"
53 #include "HTMLAttachmentElement.h"
54 #include "HTMLImageElement.h"
55 #include "HTMLInputElement.h"
56 #include "HTMLPlugInElement.h"
57 #include "HitTestRequest.h"
58 #include "HitTestResult.h"
59 #include "Image.h"
60 #include "ImageOrientation.h"
61 #include "MainFrame.h"
62 #include "MoveSelectionCommand.h"
63 #include "Page.h"
64 #include "Pasteboard.h"
65 #include "PlatformKeyboardEvent.h"
66 #include "PluginDocument.h"
67 #include "PluginViewBase.h"
68 #include "Position.h"
69 #include "RenderFileUploadControl.h"
70 #include "RenderImage.h"
71 #include "RenderView.h"
72 #include "ReplaceSelectionCommand.h"
73 #include "ResourceRequest.h"
74 #include "SecurityOrigin.h"
75 #include "Settings.h"
76 #include "ShadowRoot.h"
77 #include "StyleProperties.h"
78 #include "Text.h"
79 #include "TextEvent.h"
80 #include "VisiblePosition.h"
81 #include "markup.h"
82
83 #if ENABLE(DATA_INTERACTION)
84 #include "SelectionRect.h"
85 #endif
86
87 #include <wtf/CurrentTime.h>
88 #include <wtf/RefPtr.h>
89 #endif
90
91 namespace WebCore {
92
93 bool isDraggableLink(const Element& element)
94 {
95     if (is<HTMLAnchorElement>(element))
96         return downcast<HTMLAnchorElement>(element).isLiveLink();
97     if (is<SVGAElement>(element))
98         return element.isLink();
99     return false;
100 }
101
102 #if ENABLE(DRAG_SUPPORT)
103     
104 static PlatformMouseEvent createMouseEvent(const DragData& dragData)
105 {
106     bool shiftKey = false;
107     bool ctrlKey = false;
108     bool altKey = false;
109     bool metaKey = false;
110
111     PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
112
113     return PlatformMouseEvent(dragData.clientPosition(), dragData.globalPosition(),
114                               LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
115                               metaKey, currentTime(), ForceAtClick, NoTap);
116 }
117
118 DragController::DragController(Page& page, DragClient& client)
119     : m_page(page)
120     , m_client(client)
121     , m_numberOfItemsToBeAccepted(0)
122     , m_documentDragHandlingMethod(DragHandlingMethod::None)
123     , m_dragDestinationAction(DragDestinationActionNone)
124     , m_dragSourceAction(DragSourceActionNone)
125     , m_didInitiateDrag(false)
126     , m_sourceDragOperation(DragOperationNone)
127 {
128 }
129
130 DragController::~DragController()
131 {
132     m_client.dragControllerDestroyed();
133 }
134
135 static RefPtr<DocumentFragment> documentFragmentFromDragData(const DragData& dragData, Frame& frame, Range& context, bool allowPlainText, bool& chosePlainText)
136 {
137     chosePlainText = false;
138
139     Document& document = context.ownerDocument();
140     if (dragData.containsCompatibleContent()) {
141         if (auto fragment = frame.editor().webContentFromPasteboard(*Pasteboard::createForDragAndDrop(dragData), context, allowPlainText, chosePlainText))
142             return fragment;
143
144         if (dragData.containsURL(DragData::DoNotConvertFilenames)) {
145             String title;
146             String url = dragData.asURL(DragData::DoNotConvertFilenames, &title);
147             if (!url.isEmpty()) {
148                 auto anchor = HTMLAnchorElement::create(document);
149                 anchor->setHref(url);
150                 if (title.isEmpty()) {
151                     // Try the plain text first because the url might be normalized or escaped.
152                     if (dragData.containsPlainText())
153                         title = dragData.asPlainText();
154                     if (title.isEmpty())
155                         title = url;
156                 }
157                 anchor->appendChild(document.createTextNode(title));
158                 auto fragment = document.createDocumentFragment();
159                 fragment->appendChild(anchor);
160                 return WTFMove(fragment);
161             }
162         }
163     }
164     if (allowPlainText && dragData.containsPlainText()) {
165         chosePlainText = true;
166         return createFragmentFromText(context, dragData.asPlainText()).ptr();
167     }
168
169     return nullptr;
170 }
171
172 bool DragController::dragIsMove(FrameSelection& selection, const DragData& dragData)
173 {
174     const VisibleSelection& visibleSelection = selection.selection();
175     return m_documentUnderMouse == m_dragInitiator && visibleSelection.isContentEditable() && visibleSelection.isRange() && !isCopyKeyDown(dragData);
176 }
177
178 void DragController::clearDragCaret()
179 {
180     m_page.dragCaretController().clear();
181 }
182
183 void DragController::dragEnded()
184 {
185     m_dragInitiator = nullptr;
186     m_didInitiateDrag = false;
187     m_documentUnderMouse = nullptr;
188     clearDragCaret();
189     
190     m_client.dragEnded();
191 }
192
193 DragOperation DragController::dragEntered(const DragData& dragData)
194 {
195     return dragEnteredOrUpdated(dragData);
196 }
197
198 void DragController::dragExited(const DragData& dragData)
199 {
200     if (RefPtr<FrameView> v = m_page.mainFrame().view()) {
201 #if ENABLE(DASHBOARD_SUPPORT)
202         DataTransferAccessPolicy policy = (m_page.mainFrame().settings().usesDashboardBackwardCompatibilityMode() && (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin().isLocal()))
203             ? DataTransferAccessPolicy::Readable : DataTransferAccessPolicy::TypesReadable;
204 #else
205         DataTransferAccessPolicy policy = DataTransferAccessPolicy::TypesReadable;
206 #endif
207         auto dataTransfer = DataTransfer::createForDrop(policy, dragData);
208         dataTransfer->setSourceOperation(dragData.draggingSourceOperationMask());
209         m_page.mainFrame().eventHandler().cancelDragAndDrop(createMouseEvent(dragData), dataTransfer);
210         dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb); // Invalidate dataTransfer here for security.
211     }
212     mouseMovedIntoDocument(nullptr);
213     if (m_fileInputElementUnderMouse)
214         m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
215     m_fileInputElementUnderMouse = nullptr;
216 }
217
218 DragOperation DragController::dragUpdated(const DragData& dragData)
219 {
220     return dragEnteredOrUpdated(dragData);
221 }
222
223 bool DragController::performDragOperation(const DragData& dragData)
224 {
225     m_documentUnderMouse = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
226
227     ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = ShouldOpenExternalURLsPolicy::ShouldNotAllow;
228     if (m_documentUnderMouse)
229         shouldOpenExternalURLsPolicy = m_documentUnderMouse->shouldOpenExternalURLsPolicyToPropagate();
230
231     if ((m_dragDestinationAction & DragDestinationActionDHTML) && m_documentDragHandlingMethod != DragHandlingMethod::None) {
232         m_client.willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
233         Ref<MainFrame> mainFrame(m_page.mainFrame());
234         bool preventedDefault = false;
235         if (mainFrame->view()) {
236             // Sending an event can result in the destruction of the view and part.
237             auto dataTransfer = DataTransfer::createForDrop(DataTransferAccessPolicy::Readable, dragData);
238             dataTransfer->setSourceOperation(dragData.draggingSourceOperationMask());
239             preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), dataTransfer);
240             dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb); // Invalidate dataTransfer here for security.
241         }
242         if (preventedDefault) {
243             clearDragCaret();
244             m_documentUnderMouse = nullptr;
245             return true;
246         }
247     }
248
249     if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
250         m_client.didConcludeEditDrag();
251         m_documentUnderMouse = nullptr;
252         return true;
253     }
254
255     m_documentUnderMouse = nullptr;
256
257     if (operationForLoad(dragData) == DragOperationNone)
258         return false;
259
260     auto urlString = dragData.asURL();
261     if (urlString.isEmpty())
262         return false;
263
264     m_client.willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
265     m_page.mainFrame().loader().load(FrameLoadRequest(&m_page.mainFrame(), { urlString }, shouldOpenExternalURLsPolicy));
266     return true;
267 }
268
269 void DragController::mouseMovedIntoDocument(Document* newDocument)
270 {
271     if (m_documentUnderMouse == newDocument)
272         return;
273
274     // If we were over another document clear the selection
275     if (m_documentUnderMouse)
276         clearDragCaret();
277     m_documentUnderMouse = newDocument;
278 }
279
280 DragOperation DragController::dragEnteredOrUpdated(const DragData& dragData)
281 {
282     mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(dragData.clientPosition()));
283
284     m_dragDestinationAction = dragData.dragDestinationAction();
285     if (m_dragDestinationAction == DragDestinationActionNone) {
286         clearDragCaret(); // FIXME: Why not call mouseMovedIntoDocument(nullptr)?
287         return DragOperationNone;
288     }
289
290     DragOperation dragOperation = DragOperationNone;
291     m_documentDragHandlingMethod = tryDocumentDrag(dragData, m_dragDestinationAction, dragOperation);
292     if (m_documentDragHandlingMethod == DragHandlingMethod::None && (m_dragDestinationAction & DragDestinationActionLoad))
293         dragOperation = operationForLoad(dragData);
294     return dragOperation;
295 }
296
297 static HTMLInputElement* asFileInput(Node& node)
298 {
299     if (!is<HTMLInputElement>(node))
300         return nullptr;
301
302     auto* inputElement = &downcast<HTMLInputElement>(node);
303
304     // If this is a button inside of the a file input, move up to the file input.
305     if (inputElement->isTextButton() && is<ShadowRoot>(inputElement->treeScope().rootNode())) {
306         auto& host = *downcast<ShadowRoot>(inputElement->treeScope().rootNode()).host();
307         inputElement = is<HTMLInputElement>(host) ? &downcast<HTMLInputElement>(host) : nullptr;
308     }
309
310     return inputElement && inputElement->isFileUpload() ? inputElement : nullptr;
311 }
312
313 // This can return null if an empty document is loaded.
314 static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
315 {
316     Frame* frame = documentUnderMouse->frame();
317     float zoomFactor = frame ? frame->pageZoomFactor() : 1;
318     LayoutPoint point(p.x() * zoomFactor, p.y() * zoomFactor);
319
320     HitTestResult result(point);
321     documentUnderMouse->renderView()->hitTest(HitTestRequest(), result);
322
323     Node* node = result.innerNode();
324     while (node && !is<Element>(*node))
325         node = node->parentNode();
326     if (node)
327         node = node->deprecatedShadowAncestorNode();
328
329     return downcast<Element>(node);
330 }
331
332 DragController::DragHandlingMethod DragController::tryDocumentDrag(const DragData& dragData, DragDestinationAction actionMask, DragOperation& dragOperation)
333 {
334     if (!m_documentUnderMouse)
335         return DragHandlingMethod::None;
336
337     if (m_dragInitiator && !m_documentUnderMouse->securityOrigin().canReceiveDragData(m_dragInitiator->securityOrigin()))
338         return DragHandlingMethod::None;
339
340     bool isHandlingDrag = false;
341     if (actionMask & DragDestinationActionDHTML) {
342         isHandlingDrag = tryDHTMLDrag(dragData, dragOperation);
343         // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
344         // tryDHTMLDrag fires dragenter event. The event listener that listens
345         // to this event may create a nested message loop (open a modal dialog),
346         // which could process dragleave event and reset m_documentUnderMouse in
347         // dragExited.
348         if (!m_documentUnderMouse)
349             return DragHandlingMethod::None;
350     }
351
352     // It's unclear why this check is after tryDHTMLDrag.
353     // We send drag events in tryDHTMLDrag and that may be the reason.
354     RefPtr<FrameView> frameView = m_documentUnderMouse->view();
355     if (!frameView)
356         return DragHandlingMethod::None;
357
358     if (isHandlingDrag) {
359         clearDragCaret();
360         return DragHandlingMethod::NonDefault;
361     }
362
363     if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
364         if (dragData.containsColor()) {
365             dragOperation = DragOperationGeneric;
366             return DragHandlingMethod::Default;
367         }
368
369         IntPoint point = frameView->windowToContents(dragData.clientPosition());
370         Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
371         if (!element)
372             return DragHandlingMethod::None;
373         
374         HTMLInputElement* elementAsFileInput = asFileInput(*element);
375         if (m_fileInputElementUnderMouse != elementAsFileInput) {
376             if (m_fileInputElementUnderMouse)
377                 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
378             m_fileInputElementUnderMouse = elementAsFileInput;
379         }
380         
381         if (!m_fileInputElementUnderMouse)
382             m_page.dragCaretController().setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
383         else
384             clearDragCaret();
385
386         Frame* innerFrame = element->document().frame();
387         dragOperation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
388         m_numberOfItemsToBeAccepted = 0;
389
390         unsigned numberOfFiles = dragData.numberOfFiles();
391         if (m_fileInputElementUnderMouse) {
392             if (m_fileInputElementUnderMouse->isDisabledFormControl())
393                 m_numberOfItemsToBeAccepted = 0;
394             else if (m_fileInputElementUnderMouse->multiple())
395                 m_numberOfItemsToBeAccepted = numberOfFiles;
396             else if (numberOfFiles > 1)
397                 m_numberOfItemsToBeAccepted = 0;
398             else
399                 m_numberOfItemsToBeAccepted = 1;
400             
401             if (!m_numberOfItemsToBeAccepted)
402                 dragOperation = DragOperationNone;
403             m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(m_numberOfItemsToBeAccepted);
404         } else {
405             // We are not over a file input element. The dragged item(s) will only
406             // be loaded into the view the number of dragged items is 1.
407             m_numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
408         }
409         
410         return DragHandlingMethod::Default;
411     }
412     
413     // We are not over an editable region. Make sure we're clearing any prior drag cursor.
414     clearDragCaret();
415     if (m_fileInputElementUnderMouse)
416         m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
417     m_fileInputElementUnderMouse = nullptr;
418     return DragHandlingMethod::None;
419 }
420
421 DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
422 {
423     m_dragSourceAction = m_client.dragSourceActionMaskForPoint(rootViewPoint);
424     return m_dragSourceAction;
425 }
426
427 DragOperation DragController::operationForLoad(const DragData& dragData)
428 {
429     Document* document = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
430
431     bool pluginDocumentAcceptsDrags = false;
432
433     if (is<PluginDocument>(document)) {
434         const Widget* widget = downcast<PluginDocument>(*document).pluginWidget();
435         const PluginViewBase* pluginView = is<PluginViewBase>(widget) ? downcast<PluginViewBase>(widget) : nullptr;
436
437         if (pluginView)
438             pluginDocumentAcceptsDrags = pluginView->shouldAllowNavigationFromDrags();
439     }
440
441     if (document && (m_didInitiateDrag || (is<PluginDocument>(*document) && !pluginDocumentAcceptsDrags) || document->hasEditableStyle()))
442         return DragOperationNone;
443     return dragOperation(dragData);
444 }
445
446 static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
447 {
448     Ref<Frame> protector(*frame);
449     frame->selection().setSelection(dragCaret);
450     if (frame->selection().selection().isNone()) {
451         dragCaret = frame->visiblePositionForPoint(point);
452         frame->selection().setSelection(dragCaret);
453         range = dragCaret.toNormalizedRange();
454     }
455     return !frame->selection().isNone() && frame->selection().selection().isContentEditable();
456 }
457
458 bool DragController::dispatchTextInputEventFor(Frame* innerFrame, const DragData& dragData)
459 {
460     ASSERT(m_page.dragCaretController().hasCaret());
461     String text = m_page.dragCaretController().isContentRichlyEditable() ? emptyString() : dragData.asPlainText();
462     Node* target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
463     return target->dispatchEvent(TextEvent::createForDrop(innerFrame->document()->domWindow(), text));
464 }
465
466 bool DragController::concludeEditDrag(const DragData& dragData)
467 {
468     RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
469     if (m_fileInputElementUnderMouse) {
470         m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
471         m_fileInputElementUnderMouse = nullptr;
472     }
473
474     if (!m_documentUnderMouse)
475         return false;
476
477     IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData.clientPosition());
478     Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
479     if (!element)
480         return false;
481     RefPtr<Frame> innerFrame = element->document().frame();
482     ASSERT(innerFrame);
483
484     if (m_page.dragCaretController().hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
485         return true;
486
487     if (dragData.containsColor()) {
488         Color color = dragData.asColor();
489         if (!color.isValid())
490             return false;
491         RefPtr<Range> innerRange = innerFrame->selection().toNormalizedRange();
492         RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
493         style->setProperty(CSSPropertyColor, color.serialized(), false);
494         if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
495             return false;
496         m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
497         innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
498         return true;
499     }
500
501     if (dragData.containsFiles() && fileInput) {
502         // fileInput should be the element we hit tested for, unless it was made
503         // display:none in a drop event handler.
504         ASSERT(fileInput == element || !fileInput->renderer());
505         if (fileInput->isDisabledFormControl())
506             return false;
507
508         return fileInput->receiveDroppedFiles(dragData);
509     }
510
511     if (!m_page.dragController().canProcessDrag(dragData)) {
512         clearDragCaret();
513         return false;
514     }
515
516     VisibleSelection dragCaret = m_page.dragCaretController().caretPosition();
517     clearDragCaret();
518     RefPtr<Range> range = dragCaret.toNormalizedRange();
519     RefPtr<Element> rootEditableElement = innerFrame->selection().selection().rootEditableElement();
520
521     // For range to be null a WebKit client must have done something bad while
522     // manually controlling drag behaviour
523     if (!range)
524         return false;
525
526     ResourceCacheValidationSuppressor validationSuppressor(range->ownerDocument().cachedResourceLoader());
527     if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
528         bool chosePlainText = false;
529         RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, *innerFrame, *range, true, chosePlainText);
530         if (!fragment || !innerFrame->editor().shouldInsertFragment(fragment, range, EditorInsertAction::Dropped)) {
531             return false;
532         }
533
534         m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
535         if (dragIsMove(innerFrame->selection(), dragData)) {
536             // NSTextView behavior is to always smart delete on moving a selection,
537             // but only to smart insert if the selection granularity is word granularity.
538             bool smartDelete = innerFrame->editor().smartInsertDeleteEnabled();
539             bool smartInsert = smartDelete && innerFrame->selection().granularity() == WordGranularity && dragData.canSmartReplace();
540             applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
541         } else {
542             if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
543                 ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
544                 if (dragData.canSmartReplace())
545                     options |= ReplaceSelectionCommand::SmartReplace;
546                 if (chosePlainText)
547                     options |= ReplaceSelectionCommand::MatchStyle;
548                 applyCommand(ReplaceSelectionCommand::create(*m_documentUnderMouse, WTFMove(fragment), options, EditActionInsertFromDrop));
549             }
550         }
551     } else {
552         String text = dragData.asPlainText();
553         if (text.isEmpty() || !innerFrame->editor().shouldInsertText(text, range.get(), EditorInsertAction::Dropped)) {
554             return false;
555         }
556
557         m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
558         if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
559             applyCommand(ReplaceSelectionCommand::create(*m_documentUnderMouse, createFragmentFromText(*range, text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting, EditActionInsertFromDrop));
560     }
561
562     if (rootEditableElement) {
563         if (Frame* frame = rootEditableElement->document().frame())
564             frame->eventHandler().updateDragStateAfterEditDragIfNeeded(*rootEditableElement);
565     }
566
567     return true;
568 }
569
570 bool DragController::canProcessDrag(const DragData& dragData)
571 {
572     IntPoint point = m_page.mainFrame().view()->windowToContents(dragData.clientPosition());
573     HitTestResult result = HitTestResult(point);
574     if (!m_page.mainFrame().contentRenderer())
575         return false;
576
577     result = m_page.mainFrame().eventHandler().hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
578
579     if (!result.innerNonSharedNode())
580         return false;
581
582     DragData::DraggingPurpose dragPurpose = DragData::DraggingPurpose::ForEditing;
583     if (asFileInput(*result.innerNonSharedNode()))
584         dragPurpose = DragData::DraggingPurpose::ForFileUpload;
585
586     if (!dragData.containsCompatibleContent(dragPurpose))
587         return false;
588
589     if (dragPurpose == DragData::DraggingPurpose::ForFileUpload)
590         return true;
591
592     if (is<HTMLPlugInElement>(*result.innerNonSharedNode())) {
593         if (!downcast<HTMLPlugInElement>(result.innerNonSharedNode())->canProcessDrag() && !result.innerNonSharedNode()->hasEditableStyle())
594             return false;
595     } else if (!result.innerNonSharedNode()->hasEditableStyle())
596         return false;
597
598     if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
599         return false;
600
601     return true;
602 }
603
604 static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
605 {
606     // This is designed to match IE's operation fallback for the case where
607     // the page calls preventDefault() in a drag event but doesn't set dropEffect.
608     if (srcOpMask == DragOperationEvery)
609         return DragOperationCopy;
610     if (srcOpMask == DragOperationNone)
611         return DragOperationNone;
612     if (srcOpMask & DragOperationMove || srcOpMask & DragOperationGeneric)
613         return DragOperationMove;
614     if (srcOpMask & DragOperationCopy)
615         return DragOperationCopy;
616     if (srcOpMask & DragOperationLink)
617         return DragOperationLink;
618     
619     // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
620     return DragOperationGeneric;
621 }
622
623 bool DragController::tryDHTMLDrag(const DragData& dragData, DragOperation& operation)
624 {
625     ASSERT(m_documentUnderMouse);
626     Ref<MainFrame> mainFrame(m_page.mainFrame());
627     RefPtr<FrameView> viewProtector = mainFrame->view();
628     if (!viewProtector)
629         return false;
630
631 #if ENABLE(DASHBOARD_SUPPORT)
632     DataTransferAccessPolicy policy = (mainFrame->settings().usesDashboardBackwardCompatibilityMode() && m_documentUnderMouse->securityOrigin().isLocal()) ?
633         DataTransferAccessPolicy::Readable : DataTransferAccessPolicy::TypesReadable;
634 #else
635     DataTransferAccessPolicy policy = DataTransferAccessPolicy::TypesReadable;
636 #endif
637     auto dataTransfer = DataTransfer::createForDrop(policy, dragData);
638     DragOperation srcOpMask = dragData.draggingSourceOperationMask();
639     dataTransfer->setSourceOperation(srcOpMask);
640
641     PlatformMouseEvent event = createMouseEvent(dragData);
642     if (!mainFrame->eventHandler().updateDragAndDrop(event, dataTransfer)) {
643         dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb); // Invalidate dataTransfer here for security.
644         return false;
645     }
646
647     operation = dataTransfer->destinationOperation();
648     if (dataTransfer->dropEffectIsUninitialized())
649         operation = defaultOperationForDrag(srcOpMask);
650     else if (!(srcOpMask & operation)) {
651         // The element picked an operation which is not supported by the source
652         operation = DragOperationNone;
653     }
654
655     dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb); // Invalidate dataTransfer here for security.
656     return true;
657 }
658
659 Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
660 {
661     state.type = (sourceFrame->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
662     if (!startElement)
663         return nullptr;
664 #if ENABLE(ATTACHMENT_ELEMENT)
665     if (is<HTMLAttachmentElement>(startElement)) {
666         auto selection = sourceFrame->selection().selection();
667         bool isSingleAttachmentSelection = selection.start() == Position(startElement, Position::PositionIsBeforeAnchor) && selection.end() == Position(startElement, Position::PositionIsAfterAnchor);
668         bool isAttachmentElementInCurrentSelection = false;
669         if (auto selectedRange = selection.toNormalizedRange()) {
670             auto compareResult = selectedRange->compareNode(*startElement);
671             isAttachmentElementInCurrentSelection = !compareResult.hasException() && compareResult.releaseReturnValue() == Range::NODE_INSIDE;
672         }
673
674         if (!isAttachmentElementInCurrentSelection || isSingleAttachmentSelection) {
675             state.type = DragSourceActionAttachment;
676             return startElement;
677         }
678     }
679 #endif
680
681     for (auto* element = startElement; element; element = element->parentOrShadowHostElement()) {
682         auto* renderer = element->renderer();
683         if (!renderer)
684             continue;
685
686         EUserDrag dragMode = renderer->style().userDrag();
687         if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
688             state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
689             return element;
690         }
691         if (dragMode == DRAG_AUTO) {
692             if ((m_dragSourceAction & DragSourceActionImage)
693                 && is<HTMLImageElement>(*element)
694                 && sourceFrame->settings().loadsImagesAutomatically()) {
695                 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
696                 return element;
697             }
698             if ((m_dragSourceAction & DragSourceActionLink) && isDraggableLink(*element)) {
699                 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
700                 return element;
701             }
702 #if ENABLE(ATTACHMENT_ELEMENT)
703             if ((m_dragSourceAction & DragSourceActionAttachment)
704                 && is<HTMLAttachmentElement>(*element)
705                 && downcast<HTMLAttachmentElement>(*element).file()) {
706                 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionAttachment);
707                 return element;
708             }
709 #endif
710         }
711     }
712
713     // We either have nothing to drag or we have a selection and we're not over a draggable element.
714     return (state.type & DragSourceActionSelection) ? startElement : nullptr;
715 }
716
717 static CachedImage* getCachedImage(Element& element)
718 {
719     RenderObject* renderer = element.renderer();
720     if (!is<RenderImage>(renderer))
721         return nullptr;
722     auto& image = downcast<RenderImage>(*renderer);
723     return image.cachedImage();
724 }
725
726 static Image* getImage(Element& element)
727 {
728     CachedImage* cachedImage = getCachedImage(element);
729     // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
730     // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
731     // which would be empty when asking the cached BitmapImages.
732     return (cachedImage && !cachedImage->errorOccurred()) ?
733         cachedImage->image() : nullptr;
734 }
735
736 static void selectElement(Element& element)
737 {
738     RefPtr<Range> range = element.document().createRange();
739     range->selectNode(element);
740     element.document().frame()->selection().setSelection(VisibleSelection(*range, DOWNSTREAM));
741 }
742
743 static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
744 {
745     // dragImageOffset is the cursor position relative to the lower-left corner of the image.
746 #if PLATFORM(COCOA)
747     // We add in the Y dimension because we are a flipped view, so adding moves the image down.
748     const int yOffset = dragImageOffset.y();
749 #else
750     const int yOffset = -dragImageOffset.y();
751 #endif
752
753     if (isLinkImage)
754         return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
755
756     return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
757 }
758
759 static FloatPoint dragImageAnchorPointForSelectionDrag(Frame& frame, const IntPoint& mouseDraggedPoint)
760 {
761     IntRect draggingRect = enclosingIntRect(frame.selection().selectionBounds());
762
763     float x = (mouseDraggedPoint.x() - draggingRect.x()) / (float)draggingRect.width();
764     float y = (mouseDraggedPoint.y() - draggingRect.y()) / (float)draggingRect.height();
765
766     return FloatPoint { x, y };
767 }
768
769 static IntPoint dragLocForSelectionDrag(Frame& src)
770 {
771     IntRect draggingRect = enclosingIntRect(src.selection().selectionBounds());
772     int xpos = draggingRect.maxX();
773     xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
774     int ypos = draggingRect.maxY();
775 #if PLATFORM(COCOA)
776     // Deal with flipped coordinates on Mac
777     ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
778 #else
779     ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
780 #endif
781     return IntPoint(xpos, ypos);
782 }
783
784 bool DragController::startDrag(Frame& src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
785 {
786     if (!src.view() || !src.contentRenderer() || !state.source)
787         return false;
788
789     Ref<Frame> protector(src);
790     HitTestResult hitTestResult = src.eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
791
792     // FIXME(136836): Investigate whether all elements should use the containsIncludingShadowDOM() path here.
793     bool includeShadowDOM = false;
794 #if ENABLE(VIDEO)
795     includeShadowDOM = state.source->isMediaElement();
796 #endif
797     bool sourceContainsHitNode;
798     if (!includeShadowDOM)
799         sourceContainsHitNode = state.source->contains(hitTestResult.innerNode());
800     else
801         sourceContainsHitNode = state.source->containsIncludingShadowDOM(hitTestResult.innerNode());
802
803     if (!sourceContainsHitNode) {
804         // The original node being dragged isn't under the drag origin anymore... maybe it was
805         // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
806         // something that's not actually under the drag origin.
807         return false;
808     }
809
810     URL linkURL = hitTestResult.absoluteLinkURL();
811     URL imageURL = hitTestResult.absoluteImageURL();
812 #if ENABLE(ATTACHMENT_ELEMENT)
813     URL attachmentURL = hitTestResult.absoluteAttachmentURL();
814     m_draggingAttachmentURL = URL();
815 #endif
816
817     IntPoint mouseDraggedPoint = src.view()->windowToContents(dragEvent.position());
818
819     m_draggingImageURL = URL();
820     m_sourceDragOperation = srcOp;
821
822     DragImage dragImage;
823     FloatPoint dragImageAnchorPoint;
824     IntPoint dragLoc(0, 0);
825     IntPoint dragImageOffset(0, 0);
826
827     ASSERT(state.dataTransfer);
828
829     DataTransfer& dataTransfer = *state.dataTransfer;
830     if (state.type == DragSourceActionDHTML) {
831         dragImage = DragImage { dataTransfer.createDragImage(dragImageOffset) };
832         // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
833         // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
834         if (dragImage) {
835             dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
836             m_dragOffset = dragImageOffset;
837         }
838     }
839
840     if (state.type == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty()) {
841         // Selection, image, and link drags receive a default set of allowed drag operations that
842         // follows from:
843         // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
844         m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
845     }
846
847     ASSERT(state.source);
848     Element& element = *state.source;
849
850     bool mustUseLegacyDragClient = dataTransfer.pasteboard().hasData() || m_client.useLegacyDragClient();
851
852     IntRect dragImageBounds;
853     Image* image = getImage(element);
854     if (state.type == DragSourceActionSelection) {
855         PasteboardWriterData pasteboardWriterData;
856
857         if (!dataTransfer.pasteboard().hasData()) {
858             // FIXME: This entire block is almost identical to the code in Editor::copy, and the code should be shared.
859             RefPtr<Range> selectionRange = src.selection().toNormalizedRange();
860             ASSERT(selectionRange);
861
862 #if ENABLE(DATA_INTERACTION)
863             Vector<SelectionRect> selectionRects;
864             selectionRange->collectSelectionRects(selectionRects);
865             for (auto selectionRect : selectionRects)
866                 dragImageBounds.unite(selectionRect.rect());
867             dragImageBounds.inflate(SelectionDragImagePadding);
868 #endif
869
870             src.editor().willWriteSelectionToPasteboard(selectionRange.get());
871
872             if (enclosingTextFormControl(src.selection().selection().start())) {
873                 if (mustUseLegacyDragClient)
874                     dataTransfer.pasteboard().writePlainText(src.editor().selectedTextForDataTransfer(), Pasteboard::CannotSmartReplace);
875                 else {
876                     PasteboardWriterData::PlainText plainText;
877                     plainText.canSmartCopyOrDelete = false;
878                     plainText.text = src.editor().selectedTextForDataTransfer();
879                     pasteboardWriterData.setPlainText(WTFMove(plainText));
880                 }
881             } else {
882                 if (mustUseLegacyDragClient) {
883 #if PLATFORM(COCOA) || PLATFORM(GTK)
884                     src.editor().writeSelectionToPasteboard(dataTransfer.pasteboard());
885 #else
886                     // FIXME: Convert all other platforms to match Mac and delete this.
887                     dataTransfer.pasteboard().writeSelection(*selectionRange, src.editor().canSmartCopyOrDelete(), src, IncludeImageAltTextForDataTransfer);
888 #endif
889                 } else {
890 #if PLATFORM(COCOA)
891                     src.editor().writeSelection(pasteboardWriterData);
892 #endif
893                 }
894             }
895
896             src.editor().didWriteSelectionToPasteboard();
897         }
898         m_client.willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, dataTransfer);
899         if (!dragImage) {
900             TextIndicatorData textIndicator;
901             dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
902             if (textIndicator.contentImage)
903                 dragImage.setIndicatorData(textIndicator);
904             dragLoc = dragLocForSelectionDrag(src);
905             dragImageAnchorPoint = dragImageAnchorPointForSelectionDrag(src, mouseDraggedPoint);
906             m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
907         }
908
909         if (!dragImage)
910             return false;
911
912         if (mustUseLegacyDragClient) {
913             doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, dragImageBounds, dataTransfer, src, DragSourceActionSelection);
914             return true;
915         }
916
917         DragItem dragItem;
918         dragItem.image = WTFMove(dragImage);
919         dragItem.imageAnchorPoint = dragImageAnchorPoint;
920         dragItem.data = WTFMove(pasteboardWriterData);
921
922         beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);
923
924         return true;
925     }
926
927     if (!src.document()->securityOrigin().canDisplay(linkURL)) {
928         src.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not allowed to drag local resource: " + linkURL.stringCenterEllipsizedToLength());
929         return false;
930     }
931
932     if (!imageURL.isEmpty() && image && !image->isNull() && (m_dragSourceAction & DragSourceActionImage)) {
933         // We shouldn't be starting a drag for an image that can't provide an extension.
934         // This is an early detection for problems encountered later upon drop.
935         ASSERT(!image->filenameExtension().isEmpty());
936         if (!dataTransfer.pasteboard().hasData()) {
937             m_draggingImageURL = imageURL;
938             if (element.isContentRichlyEditable())
939                 selectElement(element);
940             declareAndWriteDragImage(dataTransfer, element, !linkURL.isEmpty() ? linkURL : imageURL, hitTestResult.altDisplayString());
941         }
942
943         m_client.willPerformDragSourceAction(DragSourceActionImage, dragOrigin, dataTransfer);
944
945         if (!dragImage) {
946             IntRect imageRect = hitTestResult.imageRect();
947             imageRect.setLocation(m_page.mainFrame().view()->rootViewToContents(src.view()->contentsToRootView(imageRect.location())));
948             doImageDrag(element, dragOrigin, hitTestResult.imageRect(), dataTransfer, src, m_dragOffset);
949         } else {
950             // DHTML defined drag image
951             doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, { }, dataTransfer, src, DragSourceActionImage);
952         }
953
954         return true;
955     }
956
957     if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
958         PasteboardWriterData pasteboardWriterData;
959
960         if (!dataTransfer.pasteboard().hasData()) {
961             // Simplify whitespace so the title put on the dataTransfer resembles what the user sees
962             // on the web page. This includes replacing newlines with spaces.
963             if (mustUseLegacyDragClient)
964                 src.editor().copyURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), dataTransfer.pasteboard());
965             else
966                 pasteboardWriterData.setURL(src.editor().pasteboardWriterURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace()));
967         } else {
968             // Make sure the pasteboard also contains trustworthy link data
969             // but don't overwrite more general pasteboard types.
970             PasteboardURL pasteboardURL;
971             pasteboardURL.url = linkURL;
972             pasteboardURL.title = hitTestResult.textContent();
973             dataTransfer.pasteboard().writeTrustworthyWebURLsPboardType(pasteboardURL);
974         }
975
976         const VisibleSelection& sourceSelection = src.selection().selection();
977         if (sourceSelection.isCaret() && sourceSelection.isContentEditable()) {
978             // a user can initiate a drag on a link without having any text
979             // selected.  In this case, we should expand the selection to
980             // the enclosing anchor element
981             Position pos = sourceSelection.base();
982             Node* node = enclosingAnchorElement(pos);
983             if (node)
984                 src.selection().setSelection(VisibleSelection::selectionFromContentsOfNode(node));
985         }
986
987         m_client.willPerformDragSourceAction(DragSourceActionLink, dragOrigin, dataTransfer);
988         if (!dragImage) {
989             TextIndicatorData textIndicator;
990             dragImage = DragImage { createDragImageForLink(element, linkURL, hitTestResult.textContent(), textIndicator, src.settings().fontRenderingMode(), m_page.deviceScaleFactor()) };
991             if (dragImage) {
992                 IntSize size = dragImageSize(dragImage.get());
993                 m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
994                 dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
995                 dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
996                 if (textIndicator.contentImage)
997                     dragImage.setIndicatorData(textIndicator);
998                 dragImageAnchorPoint = FloatPoint { 0.5, static_cast<float>((size.height() - LinkDragBorderInset) / size.height()) };
999             }
1000         }
1001
1002         if (mustUseLegacyDragClient) {
1003             doSystemDrag(WTFMove(dragImage), dragLoc, mouseDraggedPoint, { }, dataTransfer, src, DragSourceActionLink);
1004             return true;
1005         }
1006
1007         DragItem dragItem;
1008         dragItem.image = WTFMove(dragImage);
1009         dragItem.imageAnchorPoint = dragImageAnchorPoint;
1010         dragItem.data = WTFMove(pasteboardWriterData);
1011
1012         beginDrag(WTFMove(dragItem), src, dragOrigin, mouseDraggedPoint, dataTransfer, DragSourceActionSelection);
1013
1014         return true;
1015     }
1016
1017 #if ENABLE(ATTACHMENT_ELEMENT)
1018     if (is<HTMLAttachmentElement>(element) && m_dragSourceAction & DragSourceActionAttachment) {
1019         if (!dataTransfer.pasteboard().hasData()) {
1020             selectElement(element);
1021             if (!attachmentURL.isEmpty()) {
1022                 // Use the attachment URL specified by the file attribute to populate the pasteboard.
1023                 m_draggingAttachmentURL = attachmentURL;
1024                 declareAndWriteAttachment(dataTransfer, element, attachmentURL);
1025             } else if (src.editor().client()) {
1026 #if PLATFORM(COCOA)
1027                 // Otherwise, if no file URL is specified, call out to the injected bundle to populate the pasteboard with data.
1028                 auto& editor = src.editor();
1029                 editor.willWriteSelectionToPasteboard(src.selection().toNormalizedRange());
1030                 editor.writeSelectionToPasteboard(dataTransfer.pasteboard());
1031                 editor.didWriteSelectionToPasteboard();
1032 #endif
1033             }
1034         }
1035         
1036         m_client.willPerformDragSourceAction(DragSourceActionAttachment, dragOrigin, dataTransfer);
1037         
1038         if (!dragImage) {
1039             TextIndicatorData textIndicator;
1040             dragImage = DragImage { dissolveDragImageToFraction(createDragImageForSelection(src, textIndicator), DragImageAlpha) };
1041             if (textIndicator.contentImage)
1042                 dragImage.setIndicatorData(textIndicator);
1043             dragLoc = dragLocForSelectionDrag(src);
1044             m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
1045         }
1046         doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, { }, dataTransfer, src, DragSourceActionAttachment);
1047         return true;
1048     }
1049 #endif
1050
1051     if (state.type == DragSourceActionDHTML && dragImage) {
1052         ASSERT(m_dragSourceAction & DragSourceActionDHTML);
1053         m_client.willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, dataTransfer);
1054         doSystemDrag(WTFMove(dragImage), dragLoc, dragOrigin, { }, dataTransfer, src, DragSourceActionDHTML);
1055         return true;
1056     }
1057
1058     return false;
1059 }
1060
1061 void DragController::doImageDrag(Element& element, const IntPoint& dragOrigin, const IntRect& layoutRect, DataTransfer& dataTransfer, Frame& frame, IntPoint& dragImageOffset)
1062 {
1063     IntPoint mouseDownPoint = dragOrigin;
1064     DragImage dragImage;
1065     IntPoint scaledOrigin;
1066
1067     if (!element.renderer())
1068         return;
1069
1070     ImageOrientationDescription orientationDescription(element.renderer()->shouldRespectImageOrientation(), element.renderer()->style().imageOrientation());
1071
1072     Image* image = getImage(element);
1073     if (image && shouldUseCachedImageForDragImage(*image) && (dragImage = DragImage { createDragImageFromImage(image, element.renderer() ? orientationDescription : ImageOrientationDescription()) })) {
1074         dragImage = DragImage { fitDragImageToMaxSize(dragImage.get(), layoutRect.size(), maxDragImageSize()) };
1075         IntSize fittedSize = dragImageSize(dragImage.get());
1076
1077         dragImage = DragImage { platformAdjustDragImageForDeviceScaleFactor(dragImage.get(), m_page.deviceScaleFactor()) };
1078         dragImage = DragImage { dissolveDragImageToFraction(dragImage.get(), DragImageAlpha) };
1079
1080         // Properly orient the drag image and orient it differently if it's smaller than the original.
1081         float scale = fittedSize.width() / (float)layoutRect.width();
1082         float dx = scale * (layoutRect.x() - mouseDownPoint.x());
1083         float originY = layoutRect.y();
1084 #if PLATFORM(COCOA)
1085         // Compensate for accursed flipped coordinates in Cocoa.
1086         originY += layoutRect.height();
1087 #endif
1088         float dy = scale * (originY - mouseDownPoint.y());
1089         scaledOrigin = IntPoint((int)(dx + 0.5), (int)(dy + 0.5));
1090     } else {
1091         if (CachedImage* cachedImage = getCachedImage(element)) {
1092             dragImage = DragImage { createDragImageIconForCachedImageFilename(cachedImage->response().suggestedFilename()) };
1093             if (dragImage)
1094                 scaledOrigin = IntPoint(DragIconRightInset - dragImageSize(dragImage.get()).width(), DragIconBottomInset);
1095         }
1096     }
1097
1098     if (!dragImage)
1099         return;
1100
1101     dragImageOffset = mouseDownPoint + scaledOrigin;
1102     doSystemDrag(WTFMove(dragImage), dragImageOffset, dragOrigin, element.boundsInRootViewSpace(), dataTransfer, frame, DragSourceActionImage);
1103 }
1104
1105 void DragController::beginDrag(DragItem dragItem, Frame& frame, const IntPoint& mouseDownPoint, const IntPoint& mouseDraggedPoint, DataTransfer& dataTransfer, DragSourceAction dragSourceAction)
1106 {
1107     ASSERT(!m_client.useLegacyDragClient());
1108
1109     m_didInitiateDrag = true;
1110     m_dragInitiator = frame.document();
1111
1112     // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
1113     Ref<MainFrame> mainFrameProtector(m_page.mainFrame());
1114     RefPtr<FrameView> viewProtector = mainFrameProtector->view();
1115
1116     auto mouseDownPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDownPoint));
1117     auto mouseDraggedPointInRootViewCoordinates = viewProtector->rootViewToContents(frame.view()->contentsToRootView(mouseDraggedPoint));
1118
1119     m_client.beginDrag(WTFMove(dragItem), frame, mouseDownPointInRootViewCoordinates, mouseDraggedPointInRootViewCoordinates, dataTransfer, dragSourceAction);
1120
1121     // DragClient::beginDrag can cause the drag controller to be deleted.
1122     if (!mainFrameProtector->page())
1123         return;
1124
1125     // FIXME: This shouldn't be needed.
1126     cleanupAfterSystemDrag();
1127 }
1128
1129 void DragController::doSystemDrag(DragImage image, const IntPoint& dragLoc, const IntPoint& eventPos, const IntRect& dragImageBounds, DataTransfer& dataTransfer, Frame& frame, DragSourceAction dragSourceAction)
1130 {
1131     FloatPoint dragImageAnchor = { 0.5, 0.5 };
1132     if (dragSourceAction == DragSourceActionLink)
1133         dragImageAnchor.setY(1);
1134     else if (!dragImageBounds.isEmpty()) {
1135         dragImageAnchor.setX((eventPos.x() - dragImageBounds.x()) / (float)dragImageBounds.width());
1136         dragImageAnchor.setY((eventPos.y() - dragImageBounds.y()) / (float)dragImageBounds.height());
1137     }
1138
1139     m_didInitiateDrag = true;
1140     m_dragInitiator = frame.document();
1141     // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
1142     Ref<MainFrame> frameProtector(m_page.mainFrame());
1143     RefPtr<FrameView> viewProtector = frameProtector->view();
1144     m_client.startDrag(WTFMove(image), viewProtector->rootViewToContents(frame.view()->contentsToRootView(dragLoc)), viewProtector->rootViewToContents(frame.view()->contentsToRootView(eventPos)), dragImageAnchor, dataTransfer, frameProtector.get(), dragSourceAction);
1145     // DragClient::startDrag can cause our Page to dispear, deallocating |this|.
1146     if (!frameProtector->page())
1147         return;
1148
1149     cleanupAfterSystemDrag();
1150 }
1151
1152 // Manual drag caret manipulation
1153 void DragController::placeDragCaret(const IntPoint& windowPoint)
1154 {
1155     mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(windowPoint));
1156     if (!m_documentUnderMouse)
1157         return;
1158     Frame* frame = m_documentUnderMouse->frame();
1159     FrameView* frameView = frame->view();
1160     if (!frameView)
1161         return;
1162     IntPoint framePoint = frameView->windowToContents(windowPoint);
1163
1164     m_page.dragCaretController().setCaretPosition(frame->visiblePositionForPoint(framePoint));
1165 }
1166
1167 bool DragController::shouldUseCachedImageForDragImage(const Image& image) const
1168 {
1169 #if ENABLE(DATA_INTERACTION)
1170     UNUSED_PARAM(image);
1171     return true;
1172 #else
1173     return image.size().height() * image.size().width() <= MaxOriginalImageArea;
1174 #endif
1175 }
1176
1177 #endif // ENABLE(DRAG_SUPPORT)
1178
1179 } // namespace WebCore