2 * Copyright (C) 2007, 2009, 2010 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)
30 #include "CSSStyleDeclaration.h"
31 #include "Clipboard.h"
32 #include "ClipboardAccessPolicy.h"
33 #include "CachedResourceLoader.h"
35 #include "DocumentFragment.h"
36 #include "DragActions.h"
37 #include "DragClient.h"
39 #include "DragSession.h"
41 #include "EditorClient.h"
43 #include "EventHandler.h"
44 #include "FloatRect.h"
46 #include "FrameLoader.h"
47 #include "FrameSelection.h"
48 #include "FrameView.h"
49 #include "HTMLAnchorElement.h"
50 #include "HTMLInputElement.h"
51 #include "HTMLNames.h"
52 #include "HitTestRequest.h"
53 #include "HitTestResult.h"
55 #include "MoveSelectionCommand.h"
58 #include "PlatformKeyboardEvent.h"
59 #include "RenderFileUploadControl.h"
60 #include "RenderImage.h"
61 #include "RenderLayer.h"
62 #include "RenderView.h"
63 #include "ReplaceSelectionCommand.h"
64 #include "ResourceRequest.h"
65 #include "SecurityOrigin.h"
68 #include "TextEvent.h"
69 #include "htmlediting.h"
71 #include <wtf/CurrentTime.h>
72 #include <wtf/RefPtr.h>
76 static PlatformMouseEvent createMouseEvent(DragData* dragData)
78 bool shiftKey, ctrlKey, altKey, metaKey;
79 shiftKey = ctrlKey = altKey = metaKey = false;
80 PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
81 return PlatformMouseEvent(dragData->clientPosition(), dragData->globalPosition(),
82 LeftButton, MouseEventMoved, 0, shiftKey, ctrlKey, altKey,
83 metaKey, currentTime());
86 DragController::DragController(Page* page, DragClient* client)
89 , m_documentUnderMouse(0)
91 , m_fileInputElementUnderMouse(0)
92 , m_dragDestinationAction(DragDestinationActionNone)
93 , m_dragSourceAction(DragSourceActionNone)
94 , m_didInitiateDrag(false)
95 , m_isHandlingDrag(false)
96 , m_sourceDragOperation(DragOperationNone)
100 DragController::~DragController()
102 m_client->dragControllerDestroyed();
105 static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, Frame* frame, RefPtr<Range> context,
106 bool allowPlainText, bool& chosePlainText)
109 chosePlainText = false;
111 Document* document = context->ownerDocument();
113 if (document && dragData->containsCompatibleContent()) {
114 if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(frame, context, allowPlainText, chosePlainText))
117 if (dragData->containsURL(frame, DragData::DoNotConvertFilenames)) {
119 String url = dragData->asURL(frame, DragData::DoNotConvertFilenames, &title);
120 if (!url.isEmpty()) {
121 RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(document);
122 anchor->setHref(url);
123 if (title.isEmpty()) {
124 // Try the plain text first because the url might be normalized or escaped.
125 if (dragData->containsPlainText())
126 title = dragData->asPlainText(frame);
130 RefPtr<Node> anchorText = document->createTextNode(title);
132 anchor->appendChild(anchorText, ec);
133 RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
134 fragment->appendChild(anchor, ec);
135 return fragment.get();
139 if (allowPlainText && dragData->containsPlainText()) {
140 chosePlainText = true;
141 return createFragmentFromText(context.get(), dragData->asPlainText(frame)).get();
147 bool DragController::dragIsMove(FrameSelection* selection, DragData* dragData)
149 return m_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && selection->isRange() && !isCopyKeyDown(dragData);
152 // FIXME: This method is poorly named. We're just clearing the selection from the document this drag is exiting.
153 void DragController::cancelDrag()
155 m_page->dragCaretController()->clear();
158 void DragController::dragEnded()
161 m_didInitiateDrag = false;
162 m_page->dragCaretController()->clear();
164 m_client->dragEnded();
167 DragSession DragController::dragEntered(DragData* dragData)
169 return dragEnteredOrUpdated(dragData);
172 void DragController::dragExited(DragData* dragData)
175 Frame* mainFrame = m_page->mainFrame();
177 if (RefPtr<FrameView> v = mainFrame->view()) {
178 ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
179 RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame);
180 clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
181 mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
182 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
184 mouseMovedIntoDocument(0);
185 if (m_fileInputElementUnderMouse)
186 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
187 m_fileInputElementUnderMouse = 0;
190 DragSession DragController::dragUpdated(DragData* dragData)
192 return dragEnteredOrUpdated(dragData);
195 bool DragController::performDrag(DragData* dragData)
198 m_documentUnderMouse = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
199 if (m_isHandlingDrag) {
200 ASSERT(m_dragDestinationAction & DragDestinationActionDHTML);
201 m_client->willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
202 RefPtr<Frame> mainFrame = m_page->mainFrame();
203 if (mainFrame->view()) {
204 // Sending an event can result in the destruction of the view and part.
205 RefPtr<Clipboard> clipboard = Clipboard::create(ClipboardReadable, dragData, mainFrame.get());
206 clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
207 mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
208 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
210 m_documentUnderMouse = 0;
214 if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
215 m_documentUnderMouse = 0;
219 m_documentUnderMouse = 0;
221 if (operationForLoad(dragData) == DragOperationNone)
224 m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
225 m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL(m_page->mainFrame())), false);
229 void DragController::mouseMovedIntoDocument(Document* newDocument)
231 if (m_documentUnderMouse == newDocument)
234 // If we were over another document clear the selection
235 if (m_documentUnderMouse)
237 m_documentUnderMouse = newDocument;
240 DragSession DragController::dragEnteredOrUpdated(DragData* dragData)
243 ASSERT(m_page->mainFrame()); // It is not possible in Mac WebKit to have a Page without a mainFrame()
244 mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(dragData->clientPosition()));
246 m_dragDestinationAction = m_client->actionMaskForDrag(dragData);
247 if (m_dragDestinationAction == DragDestinationActionNone) {
248 cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
249 return DragSession();
252 DragSession dragSession;
253 bool handledByDocument = tryDocumentDrag(dragData, m_dragDestinationAction, dragSession);
254 if (!handledByDocument && (m_dragDestinationAction & DragDestinationActionLoad))
255 dragSession.operation = operationForLoad(dragData);
259 static HTMLInputElement* asFileInput(Node* node)
263 HTMLInputElement* inputElement = node->toInputElement();
265 // If this is a button inside of the a file input, move up to the file input.
266 if (inputElement && inputElement->isTextButton() && inputElement->treeScope()->isShadowRoot())
267 inputElement = inputElement->treeScope()->shadowHost()->toInputElement();
269 return inputElement && inputElement->isFileUpload() ? inputElement : 0;
272 // This can return null if an empty document is loaded.
273 static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
275 Frame* frame = documentUnderMouse->frame();
276 float zoomFactor = frame ? frame->pageZoomFactor() : 1;
277 LayoutPoint point = roundedLayoutPoint(FloatPoint(p.x() * zoomFactor, p.y() * zoomFactor));
279 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
280 HitTestResult result(point);
281 documentUnderMouse->renderView()->layer()->hitTest(request, result);
283 Node* n = result.innerNode();
284 while (n && !n->isElementNode())
287 n = n->shadowAncestorNode();
289 return static_cast<Element*>(n);
292 bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragSession& dragSession)
296 if (!m_documentUnderMouse)
299 if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
302 m_isHandlingDrag = false;
303 if (actionMask & DragDestinationActionDHTML) {
304 m_isHandlingDrag = tryDHTMLDrag(dragData, dragSession.operation);
305 // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
306 // tryDHTMLDrag fires dragenter event. The event listener that listens
307 // to this event may create a nested message loop (open a modal dialog),
308 // which could process dragleave event and reset m_documentUnderMouse in
310 if (!m_documentUnderMouse)
314 // It's unclear why this check is after tryDHTMLDrag.
315 // We send drag events in tryDHTMLDrag and that may be the reason.
316 RefPtr<FrameView> frameView = m_documentUnderMouse->view();
320 if (m_isHandlingDrag) {
321 m_page->dragCaretController()->clear();
323 } else if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
324 if (dragData->containsColor()) {
325 dragSession.operation = DragOperationGeneric;
329 IntPoint point = frameView->windowToContents(dragData->clientPosition());
330 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
334 HTMLInputElement* elementAsFileInput = asFileInput(element);
335 if (m_fileInputElementUnderMouse != elementAsFileInput) {
336 if (m_fileInputElementUnderMouse)
337 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
338 m_fileInputElementUnderMouse = elementAsFileInput;
341 if (!m_fileInputElementUnderMouse)
342 m_page->dragCaretController()->setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
344 Frame* innerFrame = element->document()->frame();
345 dragSession.operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
346 dragSession.mouseIsOverFileInput = m_fileInputElementUnderMouse;
347 dragSession.numberOfItemsToBeAccepted = 0;
349 unsigned numberOfFiles = dragData->numberOfFiles();
350 if (m_fileInputElementUnderMouse) {
351 if (m_fileInputElementUnderMouse->disabled())
352 dragSession.numberOfItemsToBeAccepted = 0;
353 else if (m_fileInputElementUnderMouse->multiple())
354 dragSession.numberOfItemsToBeAccepted = numberOfFiles;
356 dragSession.numberOfItemsToBeAccepted = 1;
358 if (!dragSession.numberOfItemsToBeAccepted)
359 dragSession.operation = DragOperationNone;
360 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(dragSession.numberOfItemsToBeAccepted);
362 // We are not over a file input element. The dragged item(s) will only
363 // be loaded into the view the number of dragged items is 1.
364 dragSession.numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
370 // We are not over an editable region. Make sure we're clearing any prior drag cursor.
371 m_page->dragCaretController()->clear();
372 if (m_fileInputElementUnderMouse)
373 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
374 m_fileInputElementUnderMouse = 0;
378 DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
380 m_dragSourceAction = m_client->dragSourceActionMaskForPoint(rootViewPoint);
381 return m_dragSourceAction;
384 DragOperation DragController::operationForLoad(DragData* dragData)
387 Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
388 if (doc && (m_didInitiateDrag || doc->isPluginDocument() || doc->rendererIsEditable()))
389 return DragOperationNone;
390 return dragOperation(dragData);
393 static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
395 frame->selection()->setSelection(dragCaret);
396 if (frame->selection()->isNone()) {
397 dragCaret = frame->visiblePositionForPoint(point);
398 frame->selection()->setSelection(dragCaret);
399 range = dragCaret.toNormalizedRange();
401 return !frame->selection()->isNone() && frame->selection()->isContentEditable();
404 bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
406 ASSERT(m_page->dragCaretController()->hasCaret());
407 String text = m_page->dragCaretController()->isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
408 Node* target = innerFrame->editor()->findEventTargetFrom(m_page->dragCaretController()->caretPosition());
409 ExceptionCode ec = 0;
410 return target->dispatchEvent(TextEvent::createForDrop(innerFrame->domWindow(), text), ec);
413 bool DragController::concludeEditDrag(DragData* dragData)
416 ASSERT(!m_isHandlingDrag);
418 if (m_fileInputElementUnderMouse) {
419 m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
420 m_fileInputElementUnderMouse = 0;
423 if (!m_documentUnderMouse)
426 IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
427 Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
430 Frame* innerFrame = element->ownerDocument()->frame();
433 if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame, dragData))
436 if (dragData->containsColor()) {
437 Color color = dragData->asColor();
438 if (!color.isValid())
440 RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
441 RefPtr<CSSStyleDeclaration> style = m_documentUnderMouse->createCSSStyleDeclaration();
443 style->setProperty("color", color.serialized(), ec);
444 if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
446 m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
447 innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
451 if (!m_page->dragController()->canProcessDrag(dragData)) {
452 m_page->dragCaretController()->clear();
456 if (HTMLInputElement* fileInput = asFileInput(element)) {
457 if (fileInput->disabled())
460 if (!dragData->containsFiles())
463 Vector<String> filenames;
464 dragData->asFilenames(filenames);
465 if (filenames.isEmpty())
468 fileInput->receiveDroppedFiles(filenames);
472 VisibleSelection dragCaret = m_page->dragCaretController()->caretPosition();
473 m_page->dragCaretController()->clear();
474 RefPtr<Range> range = dragCaret.toNormalizedRange();
476 // For range to be null a WebKit client must have done something bad while
477 // manually controlling drag behaviour
480 CachedResourceLoader* cachedResourceLoader = range->ownerDocument()->cachedResourceLoader();
481 ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
482 if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
483 bool chosePlainText = false;
484 RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame, range, true, chosePlainText);
485 if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
489 m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
490 if (dragIsMove(innerFrame->selection(), dragData)) {
491 // NSTextView behavior is to always smart delete on moving a selection,
492 // but only to smart insert if the selection granularity is word granularity.
493 bool smartDelete = innerFrame->editor()->smartInsertDeleteEnabled();
494 bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
495 applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
497 if (setSelectionToDragCaret(innerFrame, dragCaret, range, point)) {
498 ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
499 if (dragData->canSmartReplace())
500 options |= ReplaceSelectionCommand::SmartReplace;
502 options |= ReplaceSelectionCommand::MatchStyle;
503 applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), fragment, options));
507 String text = dragData->asPlainText(innerFrame);
508 if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
512 m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
513 if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
514 applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
520 bool DragController::canProcessDrag(DragData* dragData)
524 if (!dragData->containsCompatibleContent())
527 IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
528 HitTestResult result = HitTestResult(point);
529 if (!m_page->mainFrame()->contentRenderer())
532 result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
534 if (!result.innerNonSharedNode())
537 if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
540 if (!result.innerNonSharedNode()->rendererIsEditable())
543 if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
549 static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
551 // This is designed to match IE's operation fallback for the case where
552 // the page calls preventDefault() in a drag event but doesn't set dropEffect.
553 if (srcOpMask == DragOperationEvery)
554 return DragOperationCopy;
555 if (srcOpMask == DragOperationNone)
556 return DragOperationNone;
557 if (srcOpMask & DragOperationMove || srcOpMask & DragOperationGeneric)
558 return DragOperationMove;
559 if (srcOpMask & DragOperationCopy)
560 return DragOperationCopy;
561 if (srcOpMask & DragOperationLink)
562 return DragOperationLink;
564 // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
565 return DragOperationGeneric;
568 bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
571 ASSERT(m_documentUnderMouse);
572 RefPtr<Frame> mainFrame = m_page->mainFrame();
573 RefPtr<FrameView> viewProtector = mainFrame->view();
577 ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
578 RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
579 DragOperation srcOpMask = dragData->draggingSourceOperationMask();
580 clipboard->setSourceOperation(srcOpMask);
582 PlatformMouseEvent event = createMouseEvent(dragData);
583 if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
584 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
588 operation = clipboard->destinationOperation();
589 if (clipboard->dropEffectIsUninitialized())
590 operation = defaultOperationForDrag(srcOpMask);
591 else if (!(srcOpMask & operation)) {
592 // The element picked an operation which is not supported by the source
593 operation = DragOperationNone;
596 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
600 Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
602 state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
604 for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
605 Node* node = renderer->node();
607 // Anonymous render blocks don't correspond to actual DOM nodes, so we skip over them
608 // for the purposes of finding a draggable node.
610 if (!(state.m_dragType & DragSourceActionSelection) && node->isTextNode() && node->canStartSelection())
611 // In this case we have a click in the unselected portion of text. If this text is
612 // selectable, we want to start the selection process instead of looking for a parent
615 if (node->isElementNode()) {
616 EUserDrag dragMode = renderer->style()->userDrag();
617 if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
618 state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
621 if (dragMode == DRAG_AUTO) {
622 if ((m_dragSourceAction & DragSourceActionImage)
623 && node->hasTagName(HTMLNames::imgTag)
624 && src->settings()->loadsImagesAutomatically()) {
625 state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionImage);
628 if ((m_dragSourceAction & DragSourceActionLink)
629 && node->hasTagName(HTMLNames::aTag)
630 && static_cast<HTMLAnchorElement*>(node)->isLiveLink()) {
631 state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionLink);
638 // We either have nothing to drag or we have a selection and we're not over a draggable element.
639 return (state.m_dragType & DragSourceActionSelection) ? startNode : 0;
642 static CachedImage* getCachedImage(Element* element)
645 RenderObject* renderer = element->renderer();
646 if (!renderer || !renderer->isImage())
648 RenderImage* image = toRenderImage(renderer);
649 return image->cachedImage();
652 static Image* getImage(Element* element)
655 CachedImage* cachedImage = getCachedImage(element);
656 // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
657 // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
658 // which would be empty when asking the cached BitmapImages.
659 return (cachedImage && !cachedImage->errorOccurred()) ?
660 cachedImage->image() : 0;
663 static void prepareClipboardForImageDrag(Frame* source, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
665 if (node->isContentRichlyEditable()) {
666 RefPtr<Range> range = source->document()->createRange();
667 ExceptionCode ec = 0;
668 range->selectNode(node, ec);
670 source->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
672 clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, source);
675 static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
677 // dragImageOffset is the cursor position relative to the lower-left corner of the image.
679 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
680 const int yOffset = dragImageOffset.y();
682 const int yOffset = -dragImageOffset.y();
686 return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
688 return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
691 static IntPoint dragLocForSelectionDrag(Frame* src)
693 IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
694 int xpos = draggingRect.maxX();
695 xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
696 int ypos = draggingRect.maxY();
698 // Deal with flipped coordinates on Mac
699 ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
701 ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
703 return IntPoint(xpos, ypos);
706 bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
710 if (!src->view() || !src->contentRenderer())
713 HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
714 if (!state.m_dragSrc->contains(hitTestResult.innerNode()))
715 // The original node being dragged isn't under the drag origin anymore... maybe it was
716 // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
717 // something that's not actually under the drag origin.
719 KURL linkURL = hitTestResult.absoluteLinkURL();
720 KURL imageURL = hitTestResult.absoluteImageURL();
722 IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
724 m_draggingImageURL = KURL();
725 m_sourceDragOperation = srcOp;
727 DragImageRef dragImage = 0;
728 IntPoint dragLoc(0, 0);
729 IntPoint dragImageOffset(0, 0);
731 Clipboard* clipboard = state.m_dragClipboard.get();
732 if (state.m_dragType == DragSourceActionDHTML)
733 dragImage = clipboard->createDragImage(dragImageOffset);
734 if (state.m_dragType == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty())
735 // Selection, image, and link drags receive a default set of allowed drag operations that
737 // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
738 m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
740 // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
741 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
743 dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
744 m_dragOffset = dragImageOffset;
747 bool startedDrag = true; // optimism - we almost always manage to start the drag
749 Node* node = state.m_dragSrc.get();
751 Image* image = getImage(static_cast<Element*>(node));
752 if (state.m_dragType == DragSourceActionSelection) {
753 if (!clipboard->hasData()) {
754 if (enclosingTextFormControl(src->selection()->start()))
755 clipboard->writePlainText(src->editor()->selectedText());
757 RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
758 ASSERT(selectionRange);
760 clipboard->writeRange(selectionRange.get(), src);
763 m_client->willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, clipboard);
765 dragImage = createDragImageForSelection(src);
766 dragLoc = dragLocForSelectionDrag(src);
767 m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
769 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
770 } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
771 && (m_dragSourceAction & DragSourceActionImage)) {
772 // We shouldn't be starting a drag for an image that can't provide an extension.
773 // This is an early detection for problems encountered later upon drop.
774 ASSERT(!image->filenameExtension().isEmpty());
775 Element* element = static_cast<Element*>(node);
776 if (!clipboard->hasData()) {
777 m_draggingImageURL = imageURL;
778 prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
781 m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
784 IntRect imageRect = hitTestResult.imageRect();
785 imageRect.setLocation(m_page->mainFrame()->view()->rootViewToContents(src->view()->contentsToRootView(imageRect.location())));
786 doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
788 // DHTML defined drag image
789 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
791 } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
792 if (!clipboard->hasData())
793 // Simplify whitespace so the title put on the clipboard resembles what the user sees
794 // on the web page. This includes replacing newlines with spaces.
795 clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
797 if (src->selection()->isCaret() && src->selection()->isContentEditable()) {
798 // a user can initiate a drag on a link without having any text
799 // selected. In this case, we should expand the selection to
800 // the enclosing anchor element
801 Position pos = src->selection()->base();
802 Node* node = enclosingAnchorElement(pos);
804 src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
807 m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
809 dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src);
810 IntSize size = dragImageSize(dragImage);
811 m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
812 dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
814 doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
815 } else if (state.m_dragType == DragSourceActionDHTML) {
816 ASSERT(m_dragSourceAction & DragSourceActionDHTML);
817 m_client->willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
818 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
820 // draggableNode() determined an image or link node was draggable, but it turns out the
821 // image or link had no URL, so there is nothing to drag.
826 deleteDragImage(dragImage);
830 void DragController::doImageDrag(Element* element, const IntPoint& dragOrigin, const IntRect& rect, Clipboard* clipboard, Frame* frame, IntPoint& dragImageOffset)
832 IntPoint mouseDownPoint = dragOrigin;
833 DragImageRef dragImage;
836 Image* image = getImage(element);
837 if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
838 && (dragImage = createDragImageFromImage(image))) {
839 IntSize originalSize = rect.size();
840 origin = rect.location();
842 dragImage = fitDragImageToMaxSize(dragImage, rect.size(), maxDragImageSize());
843 dragImage = dissolveDragImageToFraction(dragImage, DragImageAlpha);
844 IntSize newSize = dragImageSize(dragImage);
846 // Properly orient the drag image and orient it differently if it's smaller than the original
847 float scale = newSize.width() / (float)originalSize.width();
848 float dx = origin.x() - mouseDownPoint.x();
850 origin.setX((int)(dx + 0.5));
852 //Compensate for accursed flipped coordinates in cocoa
853 origin.setY(origin.y() + originalSize.height());
855 float dy = origin.y() - mouseDownPoint.y();
857 origin.setY((int)(dy + 0.5));
859 dragImage = createDragImageIconForCachedImage(getCachedImage(element));
861 origin = IntPoint(DragIconRightInset - dragImageSize(dragImage).width(), DragIconBottomInset);
864 dragImageOffset = mouseDownPoint + origin;
865 doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
867 deleteDragImage(dragImage);
870 void DragController::doSystemDrag(DragImageRef image, const IntPoint& dragLoc, const IntPoint& eventPos, Clipboard* clipboard, Frame* frame, bool forLink)
872 m_didInitiateDrag = true;
873 m_dragInitiator = frame->document();
874 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
875 RefPtr<Frame> frameProtector = m_page->mainFrame();
876 RefPtr<FrameView> viewProtector = frameProtector->view();
877 m_client->startDrag(image, viewProtector->rootViewToContents(frame->view()->contentsToRootView(dragLoc)),
878 viewProtector->rootViewToContents(frame->view()->contentsToRootView(eventPos)), clipboard, frameProtector.get(), forLink);
880 cleanupAfterSystemDrag();
883 // Manual drag caret manipulation
884 void DragController::placeDragCaret(const IntPoint& windowPoint)
886 mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(windowPoint));
887 if (!m_documentUnderMouse)
889 Frame* frame = m_documentUnderMouse->frame();
890 FrameView* frameView = frame->view();
893 IntPoint framePoint = frameView->windowToContents(windowPoint);
895 m_page->dragCaretController()->setCaretPosition(frame->visiblePositionForPoint(framePoint));
898 } // namespace WebCore
900 #endif // ENABLE(DRAG_SUPPORT)