• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007, 2009 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 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.
24  */
25 
26 #include "config.h"
27 #include "DragController.h"
28 
29 #include "CSSStyleDeclaration.h"
30 #include "Clipboard.h"
31 #include "ClipboardAccessPolicy.h"
32 #include "DocLoader.h"
33 #include "Document.h"
34 #include "DocumentFragment.h"
35 #include "DragActions.h"
36 #include "DragClient.h"
37 #include "DragData.h"
38 #include "Editor.h"
39 #include "EditorClient.h"
40 #include "Element.h"
41 #include "EventHandler.h"
42 #include "FloatRect.h"
43 #include "Frame.h"
44 #include "FrameLoader.h"
45 #include "FrameView.h"
46 #include "HTMLAnchorElement.h"
47 #include "HTMLInputElement.h"
48 #include "HTMLNames.h"
49 #include "HitTestResult.h"
50 #include "Image.h"
51 #include "MoveSelectionCommand.h"
52 #include "Node.h"
53 #include "Page.h"
54 #include "RenderFileUploadControl.h"
55 #include "RenderImage.h"
56 #include "ReplaceSelectionCommand.h"
57 #include "ResourceRequest.h"
58 #include "SelectionController.h"
59 #include "Settings.h"
60 #include "Text.h"
61 #include "htmlediting.h"
62 #include "markup.h"
63 #include <wtf/CurrentTime.h>
64 #include <wtf/RefPtr.h>
65 
66 namespace WebCore {
67 
createMouseEvent(DragData * dragData)68 static PlatformMouseEvent createMouseEvent(DragData* dragData)
69 {
70     // FIXME: We should fake modifier keys here.
71     return PlatformMouseEvent(dragData->clientPosition(), dragData->globalPosition(),
72                               LeftButton, MouseEventMoved, 0, false, false, false, false, currentTime());
73 
74 }
75 
DragController(Page * page,DragClient * client)76 DragController::DragController(Page* page, DragClient* client)
77     : m_page(page)
78     , m_client(client)
79     , m_document(0)
80     , m_dragInitiator(0)
81     , m_dragDestinationAction(DragDestinationActionNone)
82     , m_dragSourceAction(DragSourceActionNone)
83     , m_didInitiateDrag(false)
84     , m_isHandlingDrag(false)
85     , m_dragOperation(DragOperationNone)
86 {
87 }
88 
~DragController()89 DragController::~DragController()
90 {
91     m_client->dragControllerDestroyed();
92 }
93 
documentFragmentFromDragData(DragData * dragData,RefPtr<Range> context,bool allowPlainText,bool & chosePlainText)94 static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, RefPtr<Range> context,
95                                           bool allowPlainText, bool& chosePlainText)
96 {
97     ASSERT(dragData);
98     chosePlainText = false;
99 
100     Document* document = context->ownerDocument();
101     ASSERT(document);
102     if (document && dragData->containsCompatibleContent()) {
103         if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(document))
104             return fragment;
105 
106         if (dragData->containsURL()) {
107             String title;
108             String url = dragData->asURL(&title);
109             if (!url.isEmpty()) {
110                 ExceptionCode ec;
111                 RefPtr<HTMLAnchorElement> anchor = static_cast<HTMLAnchorElement*>(document->createElement("a", ec).get());
112                 anchor->setHref(url);
113                 RefPtr<Node> anchorText = document->createTextNode(title);
114                 anchor->appendChild(anchorText, ec);
115                 RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
116                 fragment->appendChild(anchor, ec);
117                 return fragment.get();
118             }
119         }
120     }
121     if (allowPlainText && dragData->containsPlainText()) {
122         chosePlainText = true;
123         return createFragmentFromText(context.get(), dragData->asPlainText()).get();
124     }
125 
126     return 0;
127 }
128 
dragIsMove(SelectionController * selection)129 bool DragController::dragIsMove(SelectionController* selection)
130 {
131     return m_document == m_dragInitiator && selection->isContentEditable() && !isCopyKeyDown();
132 }
133 
cancelDrag()134 void DragController::cancelDrag()
135 {
136     m_page->dragCaretController()->clear();
137 }
138 
dragEnded()139 void DragController::dragEnded()
140 {
141     m_dragInitiator = 0;
142     m_didInitiateDrag = false;
143     m_page->dragCaretController()->clear();
144 }
145 
dragEntered(DragData * dragData)146 DragOperation DragController::dragEntered(DragData* dragData)
147 {
148     return dragEnteredOrUpdated(dragData);
149 }
150 
dragExited(DragData * dragData)151 void DragController::dragExited(DragData* dragData)
152 {
153     ASSERT(dragData);
154     Frame* mainFrame = m_page->mainFrame();
155 
156     if (RefPtr<FrameView> v = mainFrame->view()) {
157         ClipboardAccessPolicy policy = mainFrame->loader()->baseURL().isLocalFile() ? ClipboardReadable : ClipboardTypesReadable;
158         RefPtr<Clipboard> clipboard = dragData->createClipboard(policy);
159         clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
160         mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
161         clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
162     }
163 
164     cancelDrag();
165     m_document = 0;
166 }
167 
dragUpdated(DragData * dragData)168 DragOperation DragController::dragUpdated(DragData* dragData)
169 {
170     return dragEnteredOrUpdated(dragData);
171 }
172 
performDrag(DragData * dragData)173 bool DragController::performDrag(DragData* dragData)
174 {
175     ASSERT(dragData);
176     m_document = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
177     if (m_isHandlingDrag) {
178         ASSERT(m_dragDestinationAction & DragDestinationActionDHTML);
179         m_client->willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
180         RefPtr<Frame> mainFrame = m_page->mainFrame();
181         if (mainFrame->view()) {
182             // Sending an event can result in the destruction of the view and part.
183             RefPtr<Clipboard> clipboard = dragData->createClipboard(ClipboardReadable);
184             clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
185             mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
186             clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
187         }
188         m_document = 0;
189         return true;
190     }
191 
192     if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
193         m_document = 0;
194         return true;
195     }
196 
197     m_document = 0;
198 
199     if (operationForLoad(dragData) == DragOperationNone)
200         return false;
201 
202     m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
203     m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL()), false);
204     return true;
205 }
206 
dragEnteredOrUpdated(DragData * dragData)207 DragOperation DragController::dragEnteredOrUpdated(DragData* dragData)
208 {
209     ASSERT(dragData);
210     IntPoint windowPoint = dragData->clientPosition();
211 
212     Document* newDraggingDoc = 0;
213     if (Frame* frame = m_page->mainFrame())
214         newDraggingDoc = frame->documentAtPoint(windowPoint);
215     if (m_document != newDraggingDoc) {
216         if (m_document)
217             cancelDrag();
218         m_document = newDraggingDoc;
219     }
220 
221     m_dragDestinationAction = m_client->actionMaskForDrag(dragData);
222 
223     DragOperation operation = DragOperationNone;
224 
225     if (m_dragDestinationAction == DragDestinationActionNone)
226         cancelDrag();
227     else {
228         operation = tryDocumentDrag(dragData, m_dragDestinationAction);
229         if (operation == DragOperationNone && (m_dragDestinationAction & DragDestinationActionLoad))
230             return operationForLoad(dragData);
231     }
232 
233     return operation;
234 }
235 
asFileInput(Node * node)236 static HTMLInputElement* asFileInput(Node* node)
237 {
238     ASSERT(node);
239 
240     // The button for a FILE input is a sub element with no set input type
241     // In order to get around this problem we assume any non-FILE input element
242     // is this internal button, and try querying the shadow parent node.
243     if (node->hasTagName(HTMLNames::inputTag) && node->isShadowNode() && static_cast<HTMLInputElement*>(node)->inputType() != HTMLInputElement::FILE)
244       node = node->shadowParentNode();
245 
246     if (!node || !node->hasTagName(HTMLNames::inputTag))
247         return 0;
248 
249     HTMLInputElement* inputElem = static_cast<HTMLInputElement*>(node);
250     if (inputElem->inputType() == HTMLInputElement::FILE)
251         return inputElem;
252 
253     return 0;
254 }
255 
tryDocumentDrag(DragData * dragData,DragDestinationAction actionMask)256 DragOperation DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask)
257 {
258     ASSERT(dragData);
259 
260     if (!m_document)
261         return DragOperationNone;
262 
263     DragOperation operation = DragOperationNone;
264     if (actionMask & DragDestinationActionDHTML)
265         operation = tryDHTMLDrag(dragData);
266     m_isHandlingDrag = operation != DragOperationNone;
267 
268     RefPtr<FrameView> frameView = m_document->view();
269     if (!frameView)
270         return operation;
271 
272     if ((actionMask & DragDestinationActionEdit) && !m_isHandlingDrag && canProcessDrag(dragData)) {
273         if (dragData->containsColor())
274             return DragOperationGeneric;
275 
276         IntPoint dragPos = dragData->clientPosition();
277         IntPoint point = frameView->windowToContents(dragPos);
278         Element* element = m_document->elementFromPoint(point.x(), point.y());
279         ASSERT(element);
280         Frame* innerFrame = element->document()->frame();
281         ASSERT(innerFrame);
282         if (!asFileInput(element)) {
283             Selection dragCaret;
284             if (Frame* frame = m_document->frame())
285                 dragCaret = frame->visiblePositionForPoint(point);
286             m_page->dragCaretController()->setSelection(dragCaret);
287         }
288 
289         return dragIsMove(innerFrame->selection()) ? DragOperationMove : DragOperationCopy;
290     }
291 
292     m_page->dragCaretController()->clear();
293     return operation;
294 }
295 
delegateDragSourceAction(const IntPoint & windowPoint)296 DragSourceAction DragController::delegateDragSourceAction(const IntPoint& windowPoint)
297 {
298     m_dragSourceAction = m_client->dragSourceActionMaskForPoint(windowPoint);
299     return m_dragSourceAction;
300 }
301 
operationForLoad(DragData * dragData)302 DragOperation DragController::operationForLoad(DragData* dragData)
303 {
304     ASSERT(dragData);
305     Document* doc = 0;
306     doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
307     if (doc && (m_didInitiateDrag || doc->isPluginDocument() || (doc->frame() && doc->frame()->editor()->clientIsEditable())))
308         return DragOperationNone;
309     return dragOperation(dragData);
310 }
311 
setSelectionToDragCaret(Frame * frame,Selection & dragCaret,RefPtr<Range> & range,const IntPoint & point)312 static bool setSelectionToDragCaret(Frame* frame, Selection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
313 {
314     frame->selection()->setSelection(dragCaret);
315     if (frame->selection()->isNone()) {
316         dragCaret = frame->visiblePositionForPoint(point);
317         frame->selection()->setSelection(dragCaret);
318         range = dragCaret.toRange();
319     }
320     return !frame->selection()->isNone() && frame->selection()->isContentEditable();
321 }
322 
concludeEditDrag(DragData * dragData)323 bool DragController::concludeEditDrag(DragData* dragData)
324 {
325     ASSERT(dragData);
326     ASSERT(!m_isHandlingDrag);
327 
328     if (!m_document)
329         return false;
330 
331     IntPoint point = m_document->view()->windowToContents(dragData->clientPosition());
332     Element* element =  m_document->elementFromPoint(point.x(), point.y());
333     ASSERT(element);
334     Frame* innerFrame = element->ownerDocument()->frame();
335     ASSERT(innerFrame);
336 
337     if (dragData->containsColor()) {
338         Color color = dragData->asColor();
339         if (!color.isValid())
340             return false;
341         if (!innerFrame)
342             return false;
343         RefPtr<Range> innerRange = innerFrame->selection()->toRange();
344         RefPtr<CSSStyleDeclaration> style = m_document->createCSSStyleDeclaration();
345         ExceptionCode ec;
346         style->setProperty("color", color.name(), ec);
347         if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
348             return false;
349         m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
350         innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
351         return true;
352     }
353 
354     if (!m_page->dragController()->canProcessDrag(dragData)) {
355         m_page->dragCaretController()->clear();
356         return false;
357     }
358 
359     if (HTMLInputElement* fileInput = asFileInput(element)) {
360 
361         if (!fileInput->isEnabled())
362             return false;
363 
364         if (!dragData->containsFiles())
365             return false;
366 
367         Vector<String> filenames;
368         dragData->asFilenames(filenames);
369         if (filenames.isEmpty())
370             return false;
371 
372         // Ugly.  For security none of the API's available to us to set the input value
373         // on file inputs.  Even forcing a change in HTMLInputElement doesn't work as
374         // RenderFileUploadControl clears the file when doing updateFromElement()
375         RenderFileUploadControl* renderer = static_cast<RenderFileUploadControl*>(fileInput->renderer());
376 
377         if (!renderer)
378             return false;
379 
380         renderer->receiveDroppedFiles(filenames);
381         return true;
382     }
383 
384     Selection dragCaret(m_page->dragCaretController()->selection());
385     m_page->dragCaretController()->clear();
386     RefPtr<Range> range = dragCaret.toRange();
387 
388     // For range to be null a WebKit client must have done something bad while
389     // manually controlling drag behaviour
390     if (!range)
391         return false;
392     DocLoader* loader = range->ownerDocument()->docLoader();
393     loader->setAllowStaleResources(true);
394     if (dragIsMove(innerFrame->selection()) || dragCaret.isContentRichlyEditable()) {
395         bool chosePlainText = false;
396         RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, range, true, chosePlainText);
397         if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
398             loader->setAllowStaleResources(false);
399             return false;
400         }
401 
402         m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
403         if (dragIsMove(innerFrame->selection())) {
404             bool smartMove = innerFrame->selectionGranularity() == WordGranularity
405                           && innerFrame->editor()->smartInsertDeleteEnabled()
406                           && dragData->canSmartReplace();
407             applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartMove));
408         } else {
409             if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
410                 applyCommand(ReplaceSelectionCommand::create(m_document, fragment, true, dragData->canSmartReplace(), chosePlainText));
411         }
412     } else {
413         String text = dragData->asPlainText();
414         if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
415             loader->setAllowStaleResources(false);
416             return false;
417         }
418 
419         m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
420         if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
421             applyCommand(ReplaceSelectionCommand::create(m_document, createFragmentFromText(range.get(), text), true, false, true));
422     }
423     loader->setAllowStaleResources(false);
424 
425     return true;
426 }
427 
428 
canProcessDrag(DragData * dragData)429 bool DragController::canProcessDrag(DragData* dragData)
430 {
431     ASSERT(dragData);
432 
433     if (!dragData->containsCompatibleContent())
434         return false;
435 
436     IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
437     HitTestResult result = HitTestResult(point);
438     if (!m_page->mainFrame()->contentRenderer())
439         return false;
440 
441     result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
442 
443     if (!result.innerNonSharedNode())
444         return false;
445 
446     if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
447         return true;
448 
449     if (!result.innerNonSharedNode()->isContentEditable())
450         return false;
451 
452     if (m_didInitiateDrag && m_document == m_dragInitiator && result.isSelected())
453         return false;
454 
455     return true;
456 }
457 
tryDHTMLDrag(DragData * dragData)458 DragOperation DragController::tryDHTMLDrag(DragData* dragData)
459 {
460     ASSERT(dragData);
461     ASSERT(m_document);
462     DragOperation op = DragOperationNone;
463     RefPtr<Frame> frame = m_page->mainFrame();
464     RefPtr<FrameView> viewProtector = frame->view();
465     if (!viewProtector)
466         return DragOperationNone;
467 
468     ClipboardAccessPolicy policy = frame->loader()->baseURL().isLocalFile() ? ClipboardReadable : ClipboardTypesReadable;
469     RefPtr<Clipboard> clipboard = dragData->createClipboard(policy);
470     DragOperation srcOp = dragData->draggingSourceOperationMask();
471     clipboard->setSourceOperation(srcOp);
472 
473     PlatformMouseEvent event = createMouseEvent(dragData);
474     if (frame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
475         // *op unchanged if no source op was set
476         if (!clipboard->destinationOperation(op)) {
477             // The element accepted but they didn't pick an operation, so we pick one for them
478             // (as does WinIE).
479             if (srcOp & DragOperationCopy)
480                 op = DragOperationCopy;
481             else if (srcOp & DragOperationMove || srcOp & DragOperationGeneric)
482                 op = DragOperationMove;
483             else if (srcOp & DragOperationLink)
484                 op = DragOperationLink;
485             else
486                 op = DragOperationGeneric;
487         } else if (!(op & srcOp)) {
488             op = DragOperationNone;
489         }
490 
491         clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
492         return op;
493     }
494     return op;
495 }
496 
mayStartDragAtEventLocation(const Frame * frame,const IntPoint & framePos)497 bool DragController::mayStartDragAtEventLocation(const Frame* frame, const IntPoint& framePos)
498 {
499     ASSERT(frame);
500     ASSERT(frame->settings());
501 
502     if (!frame->view() || !frame->contentRenderer())
503         return false;
504 
505     HitTestResult mouseDownTarget = HitTestResult(framePos);
506 
507     mouseDownTarget = frame->eventHandler()->hitTestResultAtPoint(framePos, true);
508 
509     if (mouseDownTarget.image()
510         && !mouseDownTarget.absoluteImageURL().isEmpty()
511         && frame->settings()->loadsImagesAutomatically()
512         && m_dragSourceAction & DragSourceActionImage)
513         return true;
514 
515     if (!mouseDownTarget.absoluteLinkURL().isEmpty()
516         && m_dragSourceAction & DragSourceActionLink
517         && mouseDownTarget.isLiveLink())
518         return true;
519 
520     if (mouseDownTarget.isSelected()
521         && m_dragSourceAction & DragSourceActionSelection)
522         return true;
523 
524     return false;
525 
526 }
527 
getCachedImage(Element * element)528 static CachedImage* getCachedImage(Element* element)
529 {
530     ASSERT(element);
531     RenderObject* renderer = element->renderer();
532     if (!renderer || !renderer->isImage())
533         return 0;
534     RenderImage* image = static_cast<RenderImage*>(renderer);
535     return image->cachedImage();
536 }
537 
getImage(Element * element)538 static Image* getImage(Element* element)
539 {
540     ASSERT(element);
541     RenderObject* renderer = element->renderer();
542     if (!renderer || !renderer->isImage())
543         return 0;
544 
545     RenderImage* image = static_cast<RenderImage*>(renderer);
546     if (image->cachedImage() && !image->cachedImage()->errorOccurred())
547         return image->cachedImage()->image();
548     return 0;
549 }
550 
prepareClipboardForImageDrag(Frame * src,Clipboard * clipboard,Element * node,const KURL & linkURL,const KURL & imageURL,const String & label)551 static void prepareClipboardForImageDrag(Frame* src, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
552 {
553     RefPtr<Range> range = src->document()->createRange();
554     ExceptionCode ec = 0;
555     range->selectNode(node, ec);
556     ASSERT(ec == 0);
557     src->selection()->setSelection(Selection(range.get(), DOWNSTREAM));
558     clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, src);
559 }
560 
dragLocForDHTMLDrag(const IntPoint & mouseDraggedPoint,const IntPoint & dragOrigin,const IntPoint & dragImageOffset,bool isLinkImage)561 static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
562 {
563     // dragImageOffset is the cursor position relative to the lower-left corner of the image.
564 #if PLATFORM(MAC)
565     // We add in the Y dimension because we are a flipped view, so adding moves the image down.
566     const int yOffset = dragImageOffset.y();
567 #else
568     const int yOffset = -dragImageOffset.y();
569 #endif
570 
571     if (isLinkImage)
572         return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
573 
574     return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
575 }
576 
dragLocForSelectionDrag(Frame * src)577 static IntPoint dragLocForSelectionDrag(Frame* src)
578 {
579     IntRect draggingRect = enclosingIntRect(src->selectionBounds());
580     int xpos = draggingRect.right();
581     xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
582     int ypos = draggingRect.bottom();
583 #if PLATFORM(MAC)
584     // Deal with flipped coordinates on Mac
585     ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
586 #else
587     ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
588 #endif
589     return IntPoint(xpos, ypos);
590 }
591 
startDrag(Frame * src,Clipboard * clipboard,DragOperation srcOp,const PlatformMouseEvent & dragEvent,const IntPoint & dragOrigin,bool isDHTMLDrag)592 bool DragController::startDrag(Frame* src, Clipboard* clipboard, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin, bool isDHTMLDrag)
593 {
594     ASSERT(src);
595     ASSERT(clipboard);
596 
597     if (!src->view() || !src->contentRenderer())
598         return false;
599 
600     HitTestResult dragSource = HitTestResult(dragOrigin);
601     dragSource = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
602     KURL linkURL = dragSource.absoluteLinkURL();
603     KURL imageURL = dragSource.absoluteImageURL();
604     bool isSelected = dragSource.isSelected();
605 
606     IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
607 
608     m_draggingImageURL = KURL();
609     m_dragOperation = srcOp;
610 
611     DragImageRef dragImage = 0;
612     IntPoint dragLoc(0, 0);
613     IntPoint dragImageOffset(0, 0);
614 
615     if (isDHTMLDrag)
616         dragImage = clipboard->createDragImage(dragImageOffset);
617 
618     // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
619     // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
620     if (dragImage) {
621         dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
622         m_dragOffset = dragImageOffset;
623     }
624 
625     bool startedDrag = true; // optimism - we almost always manage to start the drag
626 
627     Node* node = dragSource.innerNonSharedNode();
628 
629     Image* image = getImage(static_cast<Element*>(node));
630     if (!imageURL.isEmpty() && node && node->isElementNode() && image
631             && (m_dragSourceAction & DragSourceActionImage)) {
632         // We shouldn't be starting a drag for an image that can't provide an extension.
633         // This is an early detection for problems encountered later upon drop.
634         ASSERT(!image->filenameExtension().isEmpty());
635         Element* element = static_cast<Element*>(node);
636         if (!clipboard->hasData()) {
637             m_draggingImageURL = imageURL;
638             prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, dragSource.altDisplayString());
639         }
640 
641         m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
642 
643         if (!dragImage) {
644             IntRect imageRect = dragSource.imageRect();
645             imageRect.setLocation(m_page->mainFrame()->view()->windowToContents(src->view()->contentsToWindow(imageRect.location())));
646             doImageDrag(element, dragOrigin, dragSource.imageRect(), clipboard, src, m_dragOffset);
647         } else
648             // DHTML defined drag image
649             doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
650 
651     } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
652         if (!clipboard->hasData())
653             // Simplify whitespace so the title put on the clipboard resembles what the user sees
654             // on the web page. This includes replacing newlines with spaces.
655             clipboard->writeURL(linkURL, dragSource.textContent().simplifyWhiteSpace(), src);
656 
657         if (src->selection()->isCaret() && src->selection()->isContentEditable()) {
658             // a user can initiate a drag on a link without having any text
659             // selected.  In this case, we should expand the selection to
660             // the enclosing anchor element
661             Position pos = src->selection()->base();
662             Node* node = enclosingAnchorElement(pos);
663             if (node)
664                 src->selection()->setSelection(Selection::selectionFromContentsOfNode(node));
665         }
666 
667         m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
668         if (!dragImage) {
669             dragImage = m_client->createDragImageForLink(linkURL, dragSource.textContent(), src);
670             IntSize size = dragImageSize(dragImage);
671             m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
672             dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
673         }
674         doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
675     } else if (isSelected && (m_dragSourceAction & DragSourceActionSelection)) {
676         RefPtr<Range> selectionRange = src->selection()->toRange();
677         ASSERT(selectionRange);
678         if (!clipboard->hasData())
679             clipboard->writeRange(selectionRange.get(), src);
680         m_client->willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, clipboard);
681         if (!dragImage) {
682             dragImage = createDragImageForSelection(src);
683             dragLoc = dragLocForSelectionDrag(src);
684             m_dragOffset = IntPoint((int)(dragOrigin.x() - dragLoc.x()), (int)(dragOrigin.y() - dragLoc.y()));
685         }
686         doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
687     } else if (isDHTMLDrag) {
688         ASSERT(m_dragSourceAction & DragSourceActionDHTML);
689         m_client->willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
690         doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
691     } else {
692         // Only way I know to get here is if to get here is if the original element clicked on in the mousedown is no longer
693         // under the mousedown point, so linkURL, imageURL and isSelected are all false/empty.
694         startedDrag = false;
695     }
696 
697     if (dragImage)
698         deleteDragImage(dragImage);
699     return startedDrag;
700 }
701 
doImageDrag(Element * element,const IntPoint & dragOrigin,const IntRect & rect,Clipboard * clipboard,Frame * frame,IntPoint & dragImageOffset)702 void DragController::doImageDrag(Element* element, const IntPoint& dragOrigin, const IntRect& rect, Clipboard* clipboard, Frame* frame, IntPoint& dragImageOffset)
703 {
704     IntPoint mouseDownPoint = dragOrigin;
705     DragImageRef dragImage;
706     IntPoint origin;
707 
708     Image* image = getImage(element);
709     if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
710         && (dragImage = createDragImageFromImage(image))) {
711         IntSize originalSize = rect.size();
712         origin = rect.location();
713 
714         dragImage = fitDragImageToMaxSize(dragImage, rect.size(), maxDragImageSize());
715         dragImage = dissolveDragImageToFraction(dragImage, DragImageAlpha);
716         IntSize newSize = dragImageSize(dragImage);
717 
718         // Properly orient the drag image and orient it differently if it's smaller than the original
719         float scale = newSize.width() / (float)originalSize.width();
720         float dx = origin.x() - mouseDownPoint.x();
721         dx *= scale;
722         origin.setX((int)(dx + 0.5));
723 #if PLATFORM(MAC)
724         //Compensate for accursed flipped coordinates in cocoa
725         origin.setY(origin.y() + originalSize.height());
726 #endif
727         float dy = origin.y() - mouseDownPoint.y();
728         dy *= scale;
729         origin.setY((int)(dy + 0.5));
730     } else {
731         dragImage = createDragImageIconForCachedImage(getCachedImage(element));
732         if (dragImage)
733             origin = IntPoint(DragIconRightInset - dragImageSize(dragImage).width(), DragIconBottomInset);
734     }
735 
736     dragImageOffset.setX(mouseDownPoint.x() + origin.x());
737     dragImageOffset.setY(mouseDownPoint.y() + origin.y());
738     doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
739 
740     deleteDragImage(dragImage);
741 }
742 
doSystemDrag(DragImageRef image,const IntPoint & dragLoc,const IntPoint & eventPos,Clipboard * clipboard,Frame * frame,bool forLink)743 void DragController::doSystemDrag(DragImageRef image, const IntPoint& dragLoc, const IntPoint& eventPos, Clipboard* clipboard, Frame* frame, bool forLink)
744 {
745     m_didInitiateDrag = true;
746     m_dragInitiator = frame->document();
747     // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
748     RefPtr<Frame> frameProtector = m_page->mainFrame();
749     RefPtr<FrameView> viewProtector = frameProtector->view();
750     m_client->startDrag(image, viewProtector->windowToContents(frame->view()->contentsToWindow(dragLoc)),
751         viewProtector->windowToContents(frame->view()->contentsToWindow(eventPos)), clipboard, frameProtector.get(), forLink);
752 
753     cleanupAfterSystemDrag();
754 }
755 
756 // Manual drag caret manipulation
placeDragCaret(const IntPoint & windowPoint)757 void DragController::placeDragCaret(const IntPoint& windowPoint)
758 {
759     Frame* mainFrame = m_page->mainFrame();
760     Document* newDraggingDoc = mainFrame->documentAtPoint(windowPoint);
761     if (m_document != newDraggingDoc) {
762         if (m_document)
763             cancelDrag();
764         m_document = newDraggingDoc;
765     }
766     if (!m_document)
767         return;
768     Frame* frame = m_document->frame();
769     ASSERT(frame);
770     FrameView* frameView = frame->view();
771     if (!frameView)
772         return;
773     IntPoint framePoint = frameView->windowToContents(windowPoint);
774     Selection dragCaret(frame->visiblePositionForPoint(framePoint));
775     m_page->dragCaretController()->setSelection(dragCaret);
776 }
777 
778 }
779