2 * Copyright (C) 2007, 2009, 2010, 2013 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 COMPUTER, 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 COMPUTER, 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 #if ENABLE(DRAG_SUPPORT)
31 #include "CachedImage.h"
32 #include "Clipboard.h"
33 #include "ClipboardAccessPolicy.h"
34 #include "CachedResourceLoader.h"
36 #include "DocumentFragment.h"
37 #include "DragActions.h"
38 #include "DragClient.h"
40 #include "DragImage.h"
41 #include "DragSession.h"
42 #include "DragState.h"
44 #include "EditorClient.h"
46 #include "EventHandler.h"
47 #include "ExceptionCodePlaceholder.h"
48 #include "FloatRect.h"
49 #include "FrameLoadRequest.h"
50 #include "FrameLoader.h"
51 #include "FrameSelection.h"
52 #include "FrameView.h"
53 #include "HTMLAnchorElement.h"
54 #include "HTMLImageElement.h"
55 #include "HTMLInputElement.h"
56 #include "HTMLNames.h"
57 #include "HTMLPlugInElement.h"
58 #include "HitTestRequest.h"
59 #include "HitTestResult.h"
61 #include "ImageOrientation.h"
62 #include "MainFrame.h"
63 #include "MoveSelectionCommand.h"
65 #include "Pasteboard.h"
66 #include "PlatformKeyboardEvent.h"
67 #include "PluginDocument.h"
68 #include "PluginViewBase.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"
76 #include "ShadowRoot.h"
77 #include "StyleProperties.h"
79 #include "TextEvent.h"
80 #include "htmlediting.h"
82 #include <wtf/CurrentTime.h>
83 #include <wtf/RefPtr.h>
87 static PlatformMouseEvent createMouseEvent(DragData& dragData)
89 bool shiftKey, ctrlKey, altKey, metaKey;
90 shiftKey = ctrlKey = altKey = metaKey = false;
91 int keyState = dragData.modifierKeyState();
92 shiftKey = static_cast<bool>(keyState & PlatformEvent::ShiftKey);
93 ctrlKey = static_cast<bool>(keyState & PlatformEvent::CtrlKey);
94 altKey = static_cast<bool>(keyState & PlatformEvent::AltKey);
95 metaKey = static_cast<bool>(keyState & PlatformEvent::MetaKey);
97 return PlatformMouseEvent(dragData.clientPosition(), dragData.globalPosition(),
98 LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
99 metaKey, currentTime());
102 DragController::DragController(Page& page, DragClient& client)
105 , m_documentUnderMouse(0)
107 , m_fileInputElementUnderMouse(0)
108 , m_documentIsHandlingDrag(false)
109 , m_dragDestinationAction(DragDestinationActionNone)
110 , m_dragSourceAction(DragSourceActionNone)
111 , m_didInitiateDrag(false)
112 , m_sourceDragOperation(DragOperationNone)
116 DragController::~DragController()
118 m_client.dragControllerDestroyed();
121 static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData& dragData, Frame* frame, Range& context, bool allowPlainText, bool& chosePlainText)
123 chosePlainText = false;
125 Document& document = context.ownerDocument();
126 if (dragData.containsCompatibleContent()) {
127 if (PassRefPtr<DocumentFragment> fragment = dragData.asFragment(frame, context, allowPlainText, chosePlainText))
130 if (dragData.containsURL(frame, DragData::DoNotConvertFilenames)) {
132 String url = dragData.asURL(frame, DragData::DoNotConvertFilenames, &title);
133 if (!url.isEmpty()) {
134 RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(document);
135 anchor->setHref(url);
136 if (title.isEmpty()) {
137 // Try the plain text first because the url might be normalized or escaped.
138 if (dragData.containsPlainText())
139 title = dragData.asPlainText(frame);
143 RefPtr<Node> anchorText = document.createTextNode(title);
144 anchor->appendChild(anchorText, IGNORE_EXCEPTION);
145 RefPtr<DocumentFragment> fragment = document.createDocumentFragment();
146 fragment->appendChild(anchor, IGNORE_EXCEPTION);
147 return fragment.get();
151 if (allowPlainText && dragData.containsPlainText()) {
152 chosePlainText = true;
153 return createFragmentFromText(context, dragData.asPlainText(frame)).get();
159 bool DragController::dragIsMove(FrameSelection& selection, DragData& dragData)
161 return m_documentUnderMouse == m_dragInitiator && selection.isContentEditable() && selection.isRange() && !isCopyKeyDown(dragData);
164 // FIXME: This method is poorly named. We're just clearing the selection from the document this drag is exiting.
165 void DragController::cancelDrag()
167 m_page.dragCaretController().clear();
170 void DragController::dragEnded()
173 m_didInitiateDrag = false;
174 m_page.dragCaretController().clear();
176 m_client.dragEnded();
179 DragSession DragController::dragEntered(DragData& dragData)
181 return dragEnteredOrUpdated(dragData);
184 void DragController::dragExited(DragData& dragData)
186 if (RefPtr<FrameView> v = m_page.mainFrame().view()) {
187 ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
188 RefPtr<Clipboard> clipboard = Clipboard::createForDragAndDrop(policy, dragData);
189 clipboard->setSourceOperation(dragData.draggingSourceOperationMask());
190 m_page.mainFrame().eventHandler().cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
191 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
193 mouseMovedIntoDocument(0);
194 if (m_fileInputElementUnderMouse)
195 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
196 m_fileInputElementUnderMouse = 0;
199 DragSession DragController::dragUpdated(DragData& dragData)
201 return dragEnteredOrUpdated(dragData);
204 bool DragController::performDrag(DragData& dragData)
206 m_documentUnderMouse = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
207 if ((m_dragDestinationAction & DragDestinationActionDHTML) && m_documentIsHandlingDrag) {
208 m_client.willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
209 Ref<MainFrame> mainFrame(m_page.mainFrame());
210 bool preventedDefault = false;
211 if (mainFrame->view()) {
212 // Sending an event can result in the destruction of the view and part.
213 RefPtr<Clipboard> clipboard = Clipboard::createForDragAndDrop(ClipboardReadable, dragData);
214 clipboard->setSourceOperation(dragData.draggingSourceOperationMask());
215 preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), clipboard.get());
216 clipboard->setAccessPolicy(ClipboardNumb); // Invalidate clipboard here for security
218 if (preventedDefault) {
219 m_documentUnderMouse = 0;
224 if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
225 m_documentUnderMouse = 0;
229 m_documentUnderMouse = 0;
231 if (operationForLoad(dragData) == DragOperationNone)
234 m_client.willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
235 m_page.mainFrame().loader().load(FrameLoadRequest(&m_page.mainFrame(), ResourceRequest(dragData.asURL(&m_page.mainFrame()))));
239 void DragController::mouseMovedIntoDocument(Document* newDocument)
241 if (m_documentUnderMouse == newDocument)
244 // If we were over another document clear the selection
245 if (m_documentUnderMouse)
247 m_documentUnderMouse = newDocument;
250 DragSession DragController::dragEnteredOrUpdated(DragData& dragData)
252 mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(dragData.clientPosition()));
254 m_dragDestinationAction = m_client.actionMaskForDrag(dragData);
255 if (m_dragDestinationAction == DragDestinationActionNone) {
256 cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
257 return DragSession();
260 DragSession dragSession;
261 m_documentIsHandlingDrag = tryDocumentDrag(dragData, m_dragDestinationAction, dragSession);
262 if (!m_documentIsHandlingDrag && (m_dragDestinationAction & DragDestinationActionLoad))
263 dragSession.operation = operationForLoad(dragData);
267 static HTMLInputElement* asFileInput(Node* node)
271 HTMLInputElement* inputElement = node->toInputElement();
273 // If this is a button inside of the a file input, move up to the file input.
274 if (inputElement && inputElement->isTextButton() && inputElement->treeScope().rootNode()->isShadowRoot())
275 inputElement = toShadowRoot(inputElement->treeScope().rootNode())->hostElement()->toInputElement();
277 return inputElement && inputElement->isFileUpload() ? inputElement : 0;
280 // This can return null if an empty document is loaded.
281 static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
283 Frame* frame = documentUnderMouse->frame();
284 float zoomFactor = frame ? frame->pageZoomFactor() : 1;
285 LayoutPoint point = roundedLayoutPoint(FloatPoint(p.x() * zoomFactor, p.y() * zoomFactor));
287 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
288 HitTestResult result(point);
289 documentUnderMouse->renderView()->hitTest(request, result);
291 Node* n = result.innerNode();
292 while (n && !n->isElementNode())
295 n = n->deprecatedShadowAncestorNode();
300 bool DragController::tryDocumentDrag(DragData& dragData, DragDestinationAction actionMask, DragSession& dragSession)
302 if (!m_documentUnderMouse)
305 if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
308 bool isHandlingDrag = false;
309 if (actionMask & DragDestinationActionDHTML) {
310 isHandlingDrag = tryDHTMLDrag(dragData, dragSession.operation);
311 // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
312 // tryDHTMLDrag fires dragenter event. The event listener that listens
313 // to this event may create a nested message loop (open a modal dialog),
314 // which could process dragleave event and reset m_documentUnderMouse in
316 if (!m_documentUnderMouse)
320 // It's unclear why this check is after tryDHTMLDrag.
321 // We send drag events in tryDHTMLDrag and that may be the reason.
322 RefPtr<FrameView> frameView = m_documentUnderMouse->view();
326 if (isHandlingDrag) {
327 m_page.dragCaretController().clear();
331 if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
332 if (dragData.containsColor()) {
333 dragSession.operation = DragOperationGeneric;
337 IntPoint point = frameView->windowToContents(dragData.clientPosition());
338 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
342 HTMLInputElement* elementAsFileInput = asFileInput(element);
343 if (m_fileInputElementUnderMouse != elementAsFileInput) {
344 if (m_fileInputElementUnderMouse)
345 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
346 m_fileInputElementUnderMouse = elementAsFileInput;
349 if (!m_fileInputElementUnderMouse)
350 m_page.dragCaretController().setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
352 Frame* innerFrame = element->document().frame();
353 dragSession.operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
354 dragSession.mouseIsOverFileInput = m_fileInputElementUnderMouse;
355 dragSession.numberOfItemsToBeAccepted = 0;
357 unsigned numberOfFiles = dragData.numberOfFiles();
358 if (m_fileInputElementUnderMouse) {
359 if (m_fileInputElementUnderMouse->isDisabledFormControl())
360 dragSession.numberOfItemsToBeAccepted = 0;
361 else if (m_fileInputElementUnderMouse->multiple())
362 dragSession.numberOfItemsToBeAccepted = numberOfFiles;
363 else if (numberOfFiles > 1)
364 dragSession.numberOfItemsToBeAccepted = 0;
366 dragSession.numberOfItemsToBeAccepted = 1;
368 if (!dragSession.numberOfItemsToBeAccepted)
369 dragSession.operation = DragOperationNone;
370 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(dragSession.numberOfItemsToBeAccepted);
372 // We are not over a file input element. The dragged item(s) will only
373 // be loaded into the view the number of dragged items is 1.
374 dragSession.numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
380 // We are not over an editable region. Make sure we're clearing any prior drag cursor.
381 m_page.dragCaretController().clear();
382 if (m_fileInputElementUnderMouse)
383 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
384 m_fileInputElementUnderMouse = 0;
388 DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
390 m_dragSourceAction = m_client.dragSourceActionMaskForPoint(rootViewPoint);
391 return m_dragSourceAction;
394 DragOperation DragController::operationForLoad(DragData& dragData)
396 Document* doc = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
398 bool pluginDocumentAcceptsDrags = false;
400 if (doc && doc->isPluginDocument()) {
401 const Widget* widget = toPluginDocument(doc)->pluginWidget();
402 const PluginViewBase* pluginView = (widget && widget->isPluginViewBase()) ? toPluginViewBase(widget) : nullptr;
405 pluginDocumentAcceptsDrags = pluginView->shouldAllowNavigationFromDrags();
408 if (doc && (m_didInitiateDrag || (doc->isPluginDocument() && !pluginDocumentAcceptsDrags) || doc->hasEditableStyle()))
409 return DragOperationNone;
410 return dragOperation(dragData);
413 static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
415 frame->selection().setSelection(dragCaret);
416 if (frame->selection().isNone()) {
417 dragCaret = frame->visiblePositionForPoint(point);
418 frame->selection().setSelection(dragCaret);
419 range = dragCaret.toNormalizedRange();
421 return !frame->selection().isNone() && frame->selection().isContentEditable();
424 bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData& dragData)
426 ASSERT(m_page.dragCaretController().hasCaret());
427 String text = m_page.dragCaretController().isContentRichlyEditable() ? emptyString() : dragData.asPlainText(innerFrame);
428 Node* target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
429 return target->dispatchEvent(TextEvent::createForDrop(innerFrame->document()->domWindow(), text), IGNORE_EXCEPTION);
432 bool DragController::concludeEditDrag(DragData& dragData)
434 RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
435 if (m_fileInputElementUnderMouse) {
436 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
437 m_fileInputElementUnderMouse = 0;
440 if (!m_documentUnderMouse)
443 IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData.clientPosition());
444 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
447 RefPtr<Frame> innerFrame = element->document().frame();
450 if (m_page.dragCaretController().hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
453 if (dragData.containsColor()) {
454 Color color = dragData.asColor();
455 if (!color.isValid())
457 RefPtr<Range> innerRange = innerFrame->selection().toNormalizedRange();
458 RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
459 style->setProperty(CSSPropertyColor, color.serialized(), false);
460 if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
462 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
463 innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
467 if (dragData.containsFiles() && fileInput) {
468 // fileInput should be the element we hit tested for, unless it was made
469 // display:none in a drop event handler.
470 ASSERT(fileInput == element || !fileInput->renderer());
471 if (fileInput->isDisabledFormControl())
474 return fileInput->receiveDroppedFiles(dragData);
477 if (!m_page.dragController().canProcessDrag(dragData)) {
478 m_page.dragCaretController().clear();
482 VisibleSelection dragCaret = m_page.dragCaretController().caretPosition();
483 m_page.dragCaretController().clear();
484 RefPtr<Range> range = dragCaret.toNormalizedRange();
485 RefPtr<Element> rootEditableElement = innerFrame->selection().rootEditableElement();
487 // For range to be null a WebKit client must have done something bad while
488 // manually controlling drag behaviour
492 CachedResourceLoader* cachedResourceLoader = range->ownerDocument().cachedResourceLoader();
493 ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
494 if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
495 bool chosePlainText = false;
496 RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame.get(), *range, true, chosePlainText);
497 if (!fragment || !innerFrame->editor().shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
501 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
502 if (dragIsMove(innerFrame->selection(), dragData)) {
503 // NSTextView behavior is to always smart delete on moving a selection,
504 // but only to smart insert if the selection granularity is word granularity.
505 bool smartDelete = innerFrame->editor().smartInsertDeleteEnabled();
506 bool smartInsert = smartDelete && innerFrame->selection().granularity() == WordGranularity && dragData.canSmartReplace();
507 applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
509 if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
510 ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
511 if (dragData.canSmartReplace())
512 options |= ReplaceSelectionCommand::SmartReplace;
514 options |= ReplaceSelectionCommand::MatchStyle;
515 applyCommand(ReplaceSelectionCommand::create(*m_documentUnderMouse, fragment, options));
519 String text = dragData.asPlainText(innerFrame.get());
520 if (text.isEmpty() || !innerFrame->editor().shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
524 m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
525 if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
526 applyCommand(ReplaceSelectionCommand::create(*m_documentUnderMouse, createFragmentFromText(*range, text), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
529 if (rootEditableElement) {
530 if (Frame* frame = rootEditableElement->document().frame())
531 frame->eventHandler().updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
537 bool DragController::canProcessDrag(DragData& dragData)
539 if (!dragData.containsCompatibleContent())
542 IntPoint point = m_page.mainFrame().view()->windowToContents(dragData.clientPosition());
543 HitTestResult result = HitTestResult(point);
544 if (!m_page.mainFrame().contentRenderer())
547 result = m_page.mainFrame().eventHandler().hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
549 if (!result.innerNonSharedNode())
552 if (dragData.containsFiles() && asFileInput(result.innerNonSharedNode()))
555 if (result.innerNonSharedNode()->isPluginElement()) {
556 if (!toHTMLPlugInElement(result.innerNonSharedNode())->canProcessDrag() && !result.innerNonSharedNode()->hasEditableStyle())
558 } else if (!result.innerNonSharedNode()->hasEditableStyle())
561 if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
567 static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
569 // This is designed to match IE's operation fallback for the case where
570 // the page calls preventDefault() in a drag event but doesn't set dropEffect.
571 if (srcOpMask == DragOperationEvery)
572 return DragOperationCopy;
573 if (srcOpMask == DragOperationNone)
574 return DragOperationNone;
575 if (srcOpMask & DragOperationMove || srcOpMask & DragOperationGeneric)
576 return DragOperationMove;
577 if (srcOpMask & DragOperationCopy)
578 return DragOperationCopy;
579 if (srcOpMask & DragOperationLink)
580 return DragOperationLink;
582 // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
583 return DragOperationGeneric;
586 bool DragController::tryDHTMLDrag(DragData& dragData, DragOperation& operation)
588 ASSERT(m_documentUnderMouse);
589 Ref<MainFrame> mainFrame(m_page.mainFrame());
590 RefPtr<FrameView> viewProtector = mainFrame->view();
594 ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
595 RefPtr<Clipboard> clipboard = Clipboard::createForDragAndDrop(policy, dragData);
596 DragOperation srcOpMask = dragData.draggingSourceOperationMask();
597 clipboard->setSourceOperation(srcOpMask);
599 PlatformMouseEvent event = createMouseEvent(dragData);
600 if (!mainFrame->eventHandler().updateDragAndDrop(event, clipboard.get())) {
601 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
605 operation = clipboard->destinationOperation();
606 if (clipboard->dropEffectIsUninitialized())
607 operation = defaultOperationForDrag(srcOpMask);
608 else if (!(srcOpMask & operation)) {
609 // The element picked an operation which is not supported by the source
610 operation = DragOperationNone;
613 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
617 Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
619 state.type = (sourceFrame->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
623 for (auto renderer = startElement->renderer(); renderer; renderer = renderer->parent()) {
624 Element* element = renderer->nonPseudoElement();
626 // Anonymous render blocks don't correspond to actual DOM elements, so we skip over them
627 // for the purposes of finding a draggable element.
630 EUserDrag dragMode = renderer->style().userDrag();
631 if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
632 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
635 if (dragMode == DRAG_AUTO) {
636 if ((m_dragSourceAction & DragSourceActionImage)
637 && isHTMLImageElement(element)
638 && sourceFrame->settings().loadsImagesAutomatically()) {
639 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
642 if ((m_dragSourceAction & DragSourceActionLink)
643 && isHTMLAnchorElement(element)
644 && toHTMLAnchorElement(element)->isLiveLink()) {
645 state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
651 // We either have nothing to drag or we have a selection and we're not over a draggable element.
652 return (state.type & DragSourceActionSelection) ? startElement : 0;
655 static CachedImage* getCachedImage(Element& element)
657 RenderObject* renderer = element.renderer();
658 if (!renderer || !renderer->isRenderImage())
660 RenderImage* image = toRenderImage(renderer);
661 return image->cachedImage();
664 static Image* getImage(Element& element)
666 CachedImage* cachedImage = getCachedImage(element);
667 // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
668 // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
669 // which would be empty when asking the cached BitmapImages.
670 return (cachedImage && !cachedImage->errorOccurred()) ?
671 cachedImage->image() : 0;
674 static void selectElement(Element& element)
676 RefPtr<Range> range = element.document().createRange();
677 range->selectNode(&element);
678 element.document().frame()->selection().setSelection(VisibleSelection(range.get(), DOWNSTREAM));
681 static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
683 // dragImageOffset is the cursor position relative to the lower-left corner of the image.
685 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
686 const int yOffset = dragImageOffset.y();
688 const int yOffset = -dragImageOffset.y();
692 return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
694 return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
697 static IntPoint dragLocForSelectionDrag(Frame& src)
699 IntRect draggingRect = enclosingIntRect(src.selection().bounds());
700 int xpos = draggingRect.maxX();
701 xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
702 int ypos = draggingRect.maxY();
704 // Deal with flipped coordinates on Mac
705 ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
707 ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
709 return IntPoint(xpos, ypos);
712 bool DragController::startDrag(Frame& src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
714 if (!src.view() || !src.contentRenderer())
717 HitTestResult hitTestResult = src.eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
718 if (!state.source->contains(hitTestResult.innerNode()))
719 // The original node being dragged isn't under the drag origin anymore... maybe it was
720 // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
721 // something that's not actually under the drag origin.
723 URL linkURL = hitTestResult.absoluteLinkURL();
724 URL imageURL = hitTestResult.absoluteImageURL();
726 IntPoint mouseDraggedPoint = src.view()->windowToContents(dragEvent.position());
728 m_draggingImageURL = URL();
729 m_sourceDragOperation = srcOp;
731 DragImageRef dragImage = 0;
732 IntPoint dragLoc(0, 0);
733 IntPoint dragImageOffset(0, 0);
735 ASSERT(state.clipboard);
737 Clipboard& clipboard = *state.clipboard;
738 if (state.type == DragSourceActionDHTML)
739 dragImage = clipboard.createDragImage(dragImageOffset);
740 if (state.type == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty())
741 // Selection, image, and link drags receive a default set of allowed drag operations that
743 // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
744 m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
746 // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
747 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
749 dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
750 m_dragOffset = dragImageOffset;
753 bool startedDrag = true; // optimism - we almost always manage to start the drag
755 ASSERT(state.source);
756 Element& element = *state.source;
758 Image* image = getImage(element);
759 if (state.type == DragSourceActionSelection) {
760 if (!clipboard.pasteboard().hasData()) {
761 // FIXME: This entire block is almost identical to the code in Editor::copy, and the code should be shared.
763 RefPtr<Range> selectionRange = src.selection().toNormalizedRange();
764 ASSERT(selectionRange);
766 src.editor().willWriteSelectionToPasteboard(selectionRange.get());
768 if (enclosingTextFormControl(src.selection().start()))
769 clipboard.pasteboard().writePlainText(src.editor().selectedTextForClipboard(), Pasteboard::CannotSmartReplace);
771 #if PLATFORM(MAC) || PLATFORM(EFL)
772 src.editor().writeSelectionToPasteboard(clipboard.pasteboard());
774 // FIXME: Convert all other platforms to match Mac and delete this.
775 clipboard.pasteboard().writeSelection(*selectionRange, src.editor().canSmartCopyOrDelete(), src, IncludeImageAltTextForClipboard);
779 src.editor().didWriteSelectionToPasteboard();
781 m_client.willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, clipboard);
783 dragImage = dissolveDragImageToFraction(createDragImageForSelection(src), DragImageAlpha);
784 dragLoc = dragLocForSelectionDrag(src);
785 m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
787 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
788 } else if (!imageURL.isEmpty() && image && !image->isNull() && (m_dragSourceAction & DragSourceActionImage)) {
789 // We shouldn't be starting a drag for an image that can't provide an extension.
790 // This is an early detection for problems encountered later upon drop.
791 ASSERT(!image->filenameExtension().isEmpty());
792 if (!clipboard.pasteboard().hasData()) {
793 m_draggingImageURL = imageURL;
794 if (element.isContentRichlyEditable())
795 selectElement(element);
796 declareAndWriteDragImage(clipboard, element, !linkURL.isEmpty() ? linkURL : imageURL, hitTestResult.altDisplayString());
799 m_client.willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
802 IntRect imageRect = hitTestResult.imageRect();
803 imageRect.setLocation(m_page.mainFrame().view()->rootViewToContents(src.view()->contentsToRootView(imageRect.location())));
804 doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
806 // DHTML defined drag image
807 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
809 } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
810 if (!clipboard.pasteboard().hasData())
811 // Simplify whitespace so the title put on the clipboard resembles what the user sees
812 // on the web page. This includes replacing newlines with spaces.
813 src.editor().copyURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), clipboard.pasteboard());
815 if (src.selection().isCaret() && src.selection().isContentEditable()) {
816 // a user can initiate a drag on a link without having any text
817 // selected. In this case, we should expand the selection to
818 // the enclosing anchor element
819 Position pos = src.selection().base();
820 Node* node = enclosingAnchorElement(pos);
822 src.selection().setSelection(VisibleSelection::selectionFromContentsOfNode(node));
825 m_client.willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
827 dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src.settings().fontRenderingMode());
828 IntSize size = dragImageSize(dragImage);
829 m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
830 dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
831 // Later code expects the drag image to be scaled by device's scale factor.
832 dragImage = scaleDragImage(dragImage, FloatSize(m_page.deviceScaleFactor(), m_page.deviceScaleFactor()));
834 doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
835 } else if (state.type == DragSourceActionDHTML) {
837 ASSERT(m_dragSourceAction & DragSourceActionDHTML);
838 m_client.willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
839 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
843 // draggableElement() determined an image or link node was draggable, but it turns out the
844 // image or link had no URL, so there is nothing to drag.
849 deleteDragImage(dragImage);
853 void DragController::doImageDrag(Element& element, const IntPoint& dragOrigin, const IntRect& layoutRect, Clipboard& clipboard, Frame& frame, IntPoint& dragImageOffset)
855 IntPoint mouseDownPoint = dragOrigin;
856 DragImageRef dragImage = nullptr;
857 IntPoint scaledOrigin;
859 if (!element.renderer())
862 ImageOrientationDescription orientationDescription(element.renderer()->shouldRespectImageOrientation());
863 #if ENABLE(CSS_IMAGE_ORIENTATION)
864 orientationDescription.setImageOrientationEnum(element.renderer()->style().imageOrientation());
867 Image* image = getImage(element);
868 if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
869 && (dragImage = createDragImageFromImage(image, element.renderer() ? orientationDescription : ImageOrientationDescription()))) {
871 dragImage = fitDragImageToMaxSize(dragImage, layoutRect.size(), maxDragImageSize());
872 IntSize fittedSize = dragImageSize(dragImage);
874 dragImage = scaleDragImage(dragImage, FloatSize(m_page.deviceScaleFactor(), m_page.deviceScaleFactor()));
875 dragImage = dissolveDragImageToFraction(dragImage, DragImageAlpha);
877 // Properly orient the drag image and orient it differently if it's smaller than the original.
878 float scale = fittedSize.width() / (float)layoutRect.width();
879 float dx = scale * (layoutRect.x() - mouseDownPoint.x());
880 float originY = layoutRect.y();
882 // Compensate for accursed flipped coordinates in Cocoa.
883 originY += layoutRect.height();
885 float dy = scale * (originY - mouseDownPoint.y());
886 scaledOrigin = IntPoint((int)(dx + 0.5), (int)(dy + 0.5));
888 if (CachedImage* cachedImage = getCachedImage(element)) {
889 dragImage = createDragImageIconForCachedImageFilename(cachedImage->response().suggestedFilename());
891 scaledOrigin = IntPoint(DragIconRightInset - dragImageSize(dragImage).width(), DragIconBottomInset);
895 dragImageOffset = mouseDownPoint + scaledOrigin;
896 doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
898 deleteDragImage(dragImage);
901 void DragController::doSystemDrag(DragImageRef image, const IntPoint& dragLoc, const IntPoint& eventPos, Clipboard& clipboard, Frame& frame, bool forLink)
903 m_didInitiateDrag = true;
904 m_dragInitiator = frame.document();
905 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
906 Ref<MainFrame> frameProtector(m_page.mainFrame());
907 RefPtr<FrameView> viewProtector = frameProtector->view();
908 m_client.startDrag(image, viewProtector->rootViewToContents(frame.view()->contentsToRootView(dragLoc)),
909 viewProtector->rootViewToContents(frame.view()->contentsToRootView(eventPos)), clipboard, frameProtector.get(), forLink);
910 // DragClient::startDrag can cause our Page to dispear, deallocating |this|.
911 if (!frameProtector->page())
914 cleanupAfterSystemDrag();
917 // Manual drag caret manipulation
918 void DragController::placeDragCaret(const IntPoint& windowPoint)
920 mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(windowPoint));
921 if (!m_documentUnderMouse)
923 Frame* frame = m_documentUnderMouse->frame();
924 FrameView* frameView = frame->view();
927 IntPoint framePoint = frameView->windowToContents(windowPoint);
929 m_page.dragCaretController().setCaretPosition(frame->visiblePositionForPoint(framePoint));
932 } // namespace WebCore
934 #endif // ENABLE(DRAG_SUPPORT)