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_documentUnderMouse(0)
80 , m_dragInitiator(0)
81 , m_dragDestinationAction(DragDestinationActionNone)
82 , m_dragSourceAction(DragSourceActionNone)
83 , m_didInitiateDrag(false)
84 , m_isHandlingDrag(false)
85 , m_sourceDragOperation(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 RefPtr<HTMLAnchorElement> anchor = new HTMLAnchorElement(document);
111 anchor->setHref(url);
112 ExceptionCode ec;
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_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && !isCopyKeyDown();
132 }
133
134 // FIXME: This method is poorly named. We're just clearing the selection from the document this drag is exiting.
cancelDrag()135 void DragController::cancelDrag()
136 {
137 m_page->dragCaretController()->clear();
138 }
139
dragEnded()140 void DragController::dragEnded()
141 {
142 m_dragInitiator = 0;
143 m_didInitiateDrag = false;
144 m_page->dragCaretController()->clear();
145 }
146
dragEntered(DragData * dragData)147 DragOperation DragController::dragEntered(DragData* dragData)
148 {
149 return dragEnteredOrUpdated(dragData);
150 }
151
dragExited(DragData * dragData)152 void DragController::dragExited(DragData* dragData)
153 {
154 ASSERT(dragData);
155 Frame* mainFrame = m_page->mainFrame();
156
157 if (RefPtr<FrameView> v = mainFrame->view()) {
158 ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
159 RefPtr<Clipboard> clipboard = dragData->createClipboard(policy);
160 clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
161 mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
162 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
163 }
164 mouseMovedIntoDocument(0);
165 }
166
dragUpdated(DragData * dragData)167 DragOperation DragController::dragUpdated(DragData* dragData)
168 {
169 return dragEnteredOrUpdated(dragData);
170 }
171
performDrag(DragData * dragData)172 bool DragController::performDrag(DragData* dragData)
173 {
174 ASSERT(dragData);
175 m_documentUnderMouse = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
176 if (m_isHandlingDrag) {
177 ASSERT(m_dragDestinationAction & DragDestinationActionDHTML);
178 m_client->willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
179 RefPtr<Frame> mainFrame = m_page->mainFrame();
180 if (mainFrame->view()) {
181 // Sending an event can result in the destruction of the view and part.
182 RefPtr<Clipboard> clipboard = dragData->createClipboard(ClipboardReadable);
183 clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
184 mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
185 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
186 }
187 m_documentUnderMouse = 0;
188 return true;
189 }
190
191 if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
192 m_documentUnderMouse = 0;
193 return true;
194 }
195
196 m_documentUnderMouse = 0;
197
198 if (operationForLoad(dragData) == DragOperationNone)
199 return false;
200
201 m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
202 m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL()), false);
203 return true;
204 }
205
mouseMovedIntoDocument(Document * newDocument)206 void DragController::mouseMovedIntoDocument(Document* newDocument)
207 {
208 if (m_documentUnderMouse == newDocument)
209 return;
210
211 // If we were over another document clear the selection
212 if (m_documentUnderMouse)
213 cancelDrag();
214 m_documentUnderMouse = newDocument;
215 }
216
dragEnteredOrUpdated(DragData * dragData)217 DragOperation DragController::dragEnteredOrUpdated(DragData* dragData)
218 {
219 ASSERT(dragData);
220 ASSERT(m_page->mainFrame()); // It is not possible in Mac WebKit to have a Page without a mainFrame()
221 mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(dragData->clientPosition()));
222
223 m_dragDestinationAction = m_client->actionMaskForDrag(dragData);
224 if (m_dragDestinationAction == DragDestinationActionNone) {
225 cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
226 return DragOperationNone;
227 }
228
229 DragOperation operation = DragOperationNone;
230 bool handledByDocument = tryDocumentDrag(dragData, m_dragDestinationAction, operation);
231 if (!handledByDocument && (m_dragDestinationAction & DragDestinationActionLoad))
232 return operationForLoad(dragData);
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,DragOperation & operation)256 bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragOperation& operation)
257 {
258 ASSERT(dragData);
259
260 if (!m_documentUnderMouse)
261 return false;
262
263 m_isHandlingDrag = false;
264 if (actionMask & DragDestinationActionDHTML) {
265 m_isHandlingDrag = tryDHTMLDrag(dragData, operation);
266 // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
267 // tryDHTMLDrag fires dragenter event. The event listener that listens
268 // to this event may create a nested message loop (open a modal dialog),
269 // which could process dragleave event and reset m_documentUnderMouse in
270 // dragExited.
271 if (!m_documentUnderMouse)
272 return false;
273 }
274
275 // It's unclear why this check is after tryDHTMLDrag.
276 // We send drag events in tryDHTMLDrag and that may be the reason.
277 RefPtr<FrameView> frameView = m_documentUnderMouse->view();
278 if (!frameView)
279 return false;
280
281 if (m_isHandlingDrag) {
282 m_page->dragCaretController()->clear();
283 return true;
284 } else if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
285 if (dragData->containsColor()) {
286 operation = DragOperationGeneric;
287 return true;
288 }
289
290 IntPoint dragPos = dragData->clientPosition();
291 IntPoint point = frameView->windowToContents(dragPos);
292 Element* element = m_documentUnderMouse->elementFromPoint(point.x(), point.y());
293 ASSERT(element);
294 if (!asFileInput(element)) {
295 VisibleSelection dragCaret = m_documentUnderMouse->frame()->visiblePositionForPoint(point);
296 m_page->dragCaretController()->setSelection(dragCaret);
297 }
298
299 Frame* innerFrame = element->document()->frame();
300 operation = dragIsMove(innerFrame->selection()) ? DragOperationMove : DragOperationCopy;
301 return true;
302 }
303 // If we're not over an editable region, make sure we're clearing any prior drag cursor.
304 m_page->dragCaretController()->clear();
305 return false;
306 }
307
delegateDragSourceAction(const IntPoint & windowPoint)308 DragSourceAction DragController::delegateDragSourceAction(const IntPoint& windowPoint)
309 {
310 m_dragSourceAction = m_client->dragSourceActionMaskForPoint(windowPoint);
311 return m_dragSourceAction;
312 }
313
operationForLoad(DragData * dragData)314 DragOperation DragController::operationForLoad(DragData* dragData)
315 {
316 ASSERT(dragData);
317 Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
318 if (doc && (m_didInitiateDrag || doc->isPluginDocument() || (doc->frame() && doc->frame()->editor()->clientIsEditable())))
319 return DragOperationNone;
320 return dragOperation(dragData);
321 }
322
setSelectionToDragCaret(Frame * frame,VisibleSelection & dragCaret,RefPtr<Range> & range,const IntPoint & point)323 static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
324 {
325 frame->selection()->setSelection(dragCaret);
326 if (frame->selection()->isNone()) {
327 dragCaret = frame->visiblePositionForPoint(point);
328 frame->selection()->setSelection(dragCaret);
329 range = dragCaret.toNormalizedRange();
330 }
331 return !frame->selection()->isNone() && frame->selection()->isContentEditable();
332 }
333
concludeEditDrag(DragData * dragData)334 bool DragController::concludeEditDrag(DragData* dragData)
335 {
336 ASSERT(dragData);
337 ASSERT(!m_isHandlingDrag);
338
339 if (!m_documentUnderMouse)
340 return false;
341
342 IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
343 Element* element = m_documentUnderMouse->elementFromPoint(point.x(), point.y());
344 ASSERT(element);
345 Frame* innerFrame = element->ownerDocument()->frame();
346 ASSERT(innerFrame);
347
348 if (dragData->containsColor()) {
349 Color color = dragData->asColor();
350 if (!color.isValid())
351 return false;
352 if (!innerFrame)
353 return false;
354 RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
355 RefPtr<CSSStyleDeclaration> style = m_documentUnderMouse->createCSSStyleDeclaration();
356 ExceptionCode ec;
357 style->setProperty("color", color.name(), ec);
358 if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
359 return false;
360 m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
361 innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
362 return true;
363 }
364
365 if (!m_page->dragController()->canProcessDrag(dragData)) {
366 m_page->dragCaretController()->clear();
367 return false;
368 }
369
370 if (HTMLInputElement* fileInput = asFileInput(element)) {
371 if (!fileInput->isEnabledFormControl())
372 return false;
373
374 if (!dragData->containsFiles())
375 return false;
376
377 Vector<String> filenames;
378 dragData->asFilenames(filenames);
379 if (filenames.isEmpty())
380 return false;
381
382 // Ugly. For security none of the APIs available to us can set the input value
383 // on file inputs. Even forcing a change in HTMLInputElement doesn't work as
384 // RenderFileUploadControl clears the file when doing updateFromElement().
385 RenderFileUploadControl* renderer = toRenderFileUploadControl(fileInput->renderer());
386 if (!renderer)
387 return false;
388
389 renderer->receiveDroppedFiles(filenames);
390 return true;
391 }
392
393 VisibleSelection dragCaret(m_page->dragCaretController()->selection());
394 m_page->dragCaretController()->clear();
395 RefPtr<Range> range = dragCaret.toNormalizedRange();
396
397 // For range to be null a WebKit client must have done something bad while
398 // manually controlling drag behaviour
399 if (!range)
400 return false;
401 DocLoader* loader = range->ownerDocument()->docLoader();
402 loader->setAllowStaleResources(true);
403 if (dragIsMove(innerFrame->selection()) || dragCaret.isContentRichlyEditable()) {
404 bool chosePlainText = false;
405 RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, range, true, chosePlainText);
406 if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
407 loader->setAllowStaleResources(false);
408 return false;
409 }
410
411 m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
412 if (dragIsMove(innerFrame->selection())) {
413 bool smartMove = innerFrame->selectionGranularity() == WordGranularity
414 && innerFrame->editor()->smartInsertDeleteEnabled()
415 && dragData->canSmartReplace();
416 applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartMove));
417 } else {
418 if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
419 applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse, fragment, true, dragData->canSmartReplace(), chosePlainText));
420 }
421 } else {
422 String text = dragData->asPlainText();
423 if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
424 loader->setAllowStaleResources(false);
425 return false;
426 }
427
428 m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
429 if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
430 applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse, createFragmentFromText(range.get(), text), true, false, true));
431 }
432 loader->setAllowStaleResources(false);
433
434 return true;
435 }
436
canProcessDrag(DragData * dragData)437 bool DragController::canProcessDrag(DragData* dragData)
438 {
439 ASSERT(dragData);
440
441 if (!dragData->containsCompatibleContent())
442 return false;
443
444 IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
445 HitTestResult result = HitTestResult(point);
446 if (!m_page->mainFrame()->contentRenderer())
447 return false;
448
449 result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
450
451 if (!result.innerNonSharedNode())
452 return false;
453
454 if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
455 return true;
456
457 if (!result.innerNonSharedNode()->isContentEditable())
458 return false;
459
460 if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
461 return false;
462
463 return true;
464 }
465
defaultOperationForDrag(DragOperation srcOpMask)466 static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
467 {
468 // This is designed to match IE's operation fallback for the case where
469 // the page calls preventDefault() in a drag event but doesn't set dropEffect.
470 if (srcOpMask & DragOperationCopy)
471 return DragOperationCopy;
472 if (srcOpMask & DragOperationMove || srcOpMask & DragOperationGeneric)
473 return DragOperationMove;
474 if (srcOpMask & DragOperationLink)
475 return DragOperationLink;
476
477 // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
478 return DragOperationGeneric;
479 }
480
tryDHTMLDrag(DragData * dragData,DragOperation & operation)481 bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
482 {
483 ASSERT(dragData);
484 ASSERT(m_documentUnderMouse);
485 RefPtr<Frame> mainFrame = m_page->mainFrame();
486 RefPtr<FrameView> viewProtector = mainFrame->view();
487 if (!viewProtector)
488 return false;
489
490 ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
491 RefPtr<Clipboard> clipboard = dragData->createClipboard(policy);
492 DragOperation srcOpMask = dragData->draggingSourceOperationMask();
493 clipboard->setSourceOperation(srcOpMask);
494
495 PlatformMouseEvent event = createMouseEvent(dragData);
496 if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
497 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
498 return false;
499 }
500
501 if (!clipboard->destinationOperation(operation)) {
502 // The element accepted but they didn't pick an operation, so we pick one (to match IE).
503 operation = defaultOperationForDrag(srcOpMask);
504 } else if (!(srcOpMask & operation)) {
505 // The element picked an operation which is not supported by the source
506 operation = DragOperationNone;
507 }
508
509 clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
510 return true;
511 }
512
mayStartDragAtEventLocation(const Frame * frame,const IntPoint & framePos)513 bool DragController::mayStartDragAtEventLocation(const Frame* frame, const IntPoint& framePos)
514 {
515 ASSERT(frame);
516 ASSERT(frame->settings());
517
518 if (!frame->view() || !frame->contentRenderer())
519 return false;
520
521 HitTestResult mouseDownTarget = HitTestResult(framePos);
522
523 mouseDownTarget = frame->eventHandler()->hitTestResultAtPoint(framePos, true);
524
525 if (mouseDownTarget.image()
526 && !mouseDownTarget.absoluteImageURL().isEmpty()
527 && frame->settings()->loadsImagesAutomatically()
528 && m_dragSourceAction & DragSourceActionImage)
529 return true;
530
531 if (!mouseDownTarget.absoluteLinkURL().isEmpty()
532 && m_dragSourceAction & DragSourceActionLink
533 && mouseDownTarget.isLiveLink())
534 return true;
535
536 if (mouseDownTarget.isSelected()
537 && m_dragSourceAction & DragSourceActionSelection)
538 return true;
539
540 return false;
541
542 }
543
getCachedImage(Element * element)544 static CachedImage* getCachedImage(Element* element)
545 {
546 ASSERT(element);
547 RenderObject* renderer = element->renderer();
548 if (!renderer || !renderer->isImage())
549 return 0;
550 RenderImage* image = toRenderImage(renderer);
551 return image->cachedImage();
552 }
553
getImage(Element * element)554 static Image* getImage(Element* element)
555 {
556 ASSERT(element);
557 RenderObject* renderer = element->renderer();
558 if (!renderer || !renderer->isImage())
559 return 0;
560
561 RenderImage* image = toRenderImage(renderer);
562 if (image->cachedImage() && !image->cachedImage()->errorOccurred())
563 return image->cachedImage()->image();
564 return 0;
565 }
566
prepareClipboardForImageDrag(Frame * src,Clipboard * clipboard,Element * node,const KURL & linkURL,const KURL & imageURL,const String & label)567 static void prepareClipboardForImageDrag(Frame* src, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
568 {
569 RefPtr<Range> range = src->document()->createRange();
570 ExceptionCode ec = 0;
571 range->selectNode(node, ec);
572 ASSERT(!ec);
573 src->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
574 clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, src);
575 }
576
dragLocForDHTMLDrag(const IntPoint & mouseDraggedPoint,const IntPoint & dragOrigin,const IntPoint & dragImageOffset,bool isLinkImage)577 static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
578 {
579 // dragImageOffset is the cursor position relative to the lower-left corner of the image.
580 #if PLATFORM(MAC)
581 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
582 const int yOffset = dragImageOffset.y();
583 #else
584 const int yOffset = -dragImageOffset.y();
585 #endif
586
587 if (isLinkImage)
588 return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
589
590 return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
591 }
592
dragLocForSelectionDrag(Frame * src)593 static IntPoint dragLocForSelectionDrag(Frame* src)
594 {
595 IntRect draggingRect = enclosingIntRect(src->selectionBounds());
596 int xpos = draggingRect.right();
597 xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
598 int ypos = draggingRect.bottom();
599 #if PLATFORM(MAC)
600 // Deal with flipped coordinates on Mac
601 ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
602 #else
603 ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
604 #endif
605 return IntPoint(xpos, ypos);
606 }
607
startDrag(Frame * src,Clipboard * clipboard,DragOperation srcOp,const PlatformMouseEvent & dragEvent,const IntPoint & dragOrigin,bool isDHTMLDrag)608 bool DragController::startDrag(Frame* src, Clipboard* clipboard, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin, bool isDHTMLDrag)
609 {
610 ASSERT(src);
611 ASSERT(clipboard);
612
613 if (!src->view() || !src->contentRenderer())
614 return false;
615
616 HitTestResult dragSource = HitTestResult(dragOrigin);
617 dragSource = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
618 KURL linkURL = dragSource.absoluteLinkURL();
619 KURL imageURL = dragSource.absoluteImageURL();
620 bool isSelected = dragSource.isSelected();
621
622 IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
623
624 m_draggingImageURL = KURL();
625 m_sourceDragOperation = srcOp;
626
627 DragImageRef dragImage = 0;
628 IntPoint dragLoc(0, 0);
629 IntPoint dragImageOffset(0, 0);
630
631 if (isDHTMLDrag)
632 dragImage = clipboard->createDragImage(dragImageOffset);
633
634 // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
635 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
636 if (dragImage) {
637 dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
638 m_dragOffset = dragImageOffset;
639 }
640
641 bool startedDrag = true; // optimism - we almost always manage to start the drag
642
643 Node* node = dragSource.innerNonSharedNode();
644
645 Image* image = getImage(static_cast<Element*>(node));
646 if (!imageURL.isEmpty() && node && node->isElementNode() && image
647 && (m_dragSourceAction & DragSourceActionImage)) {
648 // We shouldn't be starting a drag for an image that can't provide an extension.
649 // This is an early detection for problems encountered later upon drop.
650 ASSERT(!image->filenameExtension().isEmpty());
651 Element* element = static_cast<Element*>(node);
652 if (!clipboard->hasData()) {
653 m_draggingImageURL = imageURL;
654 prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, dragSource.altDisplayString());
655 }
656
657 m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
658
659 if (!dragImage) {
660 IntRect imageRect = dragSource.imageRect();
661 imageRect.setLocation(m_page->mainFrame()->view()->windowToContents(src->view()->contentsToWindow(imageRect.location())));
662 doImageDrag(element, dragOrigin, dragSource.imageRect(), clipboard, src, m_dragOffset);
663 } else
664 // DHTML defined drag image
665 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
666
667 } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
668 if (!clipboard->hasData())
669 // Simplify whitespace so the title put on the clipboard resembles what the user sees
670 // on the web page. This includes replacing newlines with spaces.
671 clipboard->writeURL(linkURL, dragSource.textContent().simplifyWhiteSpace(), src);
672
673 if (src->selection()->isCaret() && src->selection()->isContentEditable()) {
674 // a user can initiate a drag on a link without having any text
675 // selected. In this case, we should expand the selection to
676 // the enclosing anchor element
677 Position pos = src->selection()->base();
678 Node* node = enclosingAnchorElement(pos);
679 if (node)
680 src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
681 }
682
683 m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
684 if (!dragImage) {
685 dragImage = m_client->createDragImageForLink(linkURL, dragSource.textContent(), src);
686 IntSize size = dragImageSize(dragImage);
687 m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
688 dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
689 }
690 doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
691 } else if (isSelected && (m_dragSourceAction & DragSourceActionSelection)) {
692 RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
693 ASSERT(selectionRange);
694 if (!clipboard->hasData())
695 clipboard->writeRange(selectionRange.get(), src);
696 m_client->willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, clipboard);
697 if (!dragImage) {
698 dragImage = createDragImageForSelection(src);
699 dragLoc = dragLocForSelectionDrag(src);
700 m_dragOffset = IntPoint((int)(dragOrigin.x() - dragLoc.x()), (int)(dragOrigin.y() - dragLoc.y()));
701 }
702 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
703 } else if (isDHTMLDrag) {
704 ASSERT(m_dragSourceAction & DragSourceActionDHTML);
705 m_client->willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
706 doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
707 } else {
708 // 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
709 // under the mousedown point, so linkURL, imageURL and isSelected are all false/empty.
710 startedDrag = false;
711 }
712
713 if (dragImage)
714 deleteDragImage(dragImage);
715 return startedDrag;
716 }
717
doImageDrag(Element * element,const IntPoint & dragOrigin,const IntRect & rect,Clipboard * clipboard,Frame * frame,IntPoint & dragImageOffset)718 void DragController::doImageDrag(Element* element, const IntPoint& dragOrigin, const IntRect& rect, Clipboard* clipboard, Frame* frame, IntPoint& dragImageOffset)
719 {
720 IntPoint mouseDownPoint = dragOrigin;
721 DragImageRef dragImage;
722 IntPoint origin;
723
724 Image* image = getImage(element);
725 if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
726 && (dragImage = createDragImageFromImage(image))) {
727 IntSize originalSize = rect.size();
728 origin = rect.location();
729
730 dragImage = fitDragImageToMaxSize(dragImage, rect.size(), maxDragImageSize());
731 dragImage = dissolveDragImageToFraction(dragImage, DragImageAlpha);
732 IntSize newSize = dragImageSize(dragImage);
733
734 // Properly orient the drag image and orient it differently if it's smaller than the original
735 float scale = newSize.width() / (float)originalSize.width();
736 float dx = origin.x() - mouseDownPoint.x();
737 dx *= scale;
738 origin.setX((int)(dx + 0.5));
739 #if PLATFORM(MAC)
740 //Compensate for accursed flipped coordinates in cocoa
741 origin.setY(origin.y() + originalSize.height());
742 #endif
743 float dy = origin.y() - mouseDownPoint.y();
744 dy *= scale;
745 origin.setY((int)(dy + 0.5));
746 } else {
747 dragImage = createDragImageIconForCachedImage(getCachedImage(element));
748 if (dragImage)
749 origin = IntPoint(DragIconRightInset - dragImageSize(dragImage).width(), DragIconBottomInset);
750 }
751
752 dragImageOffset.setX(mouseDownPoint.x() + origin.x());
753 dragImageOffset.setY(mouseDownPoint.y() + origin.y());
754 doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
755
756 deleteDragImage(dragImage);
757 }
758
doSystemDrag(DragImageRef image,const IntPoint & dragLoc,const IntPoint & eventPos,Clipboard * clipboard,Frame * frame,bool forLink)759 void DragController::doSystemDrag(DragImageRef image, const IntPoint& dragLoc, const IntPoint& eventPos, Clipboard* clipboard, Frame* frame, bool forLink)
760 {
761 m_didInitiateDrag = true;
762 m_dragInitiator = frame->document();
763 // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
764 RefPtr<Frame> frameProtector = m_page->mainFrame();
765 RefPtr<FrameView> viewProtector = frameProtector->view();
766 m_client->startDrag(image, viewProtector->windowToContents(frame->view()->contentsToWindow(dragLoc)),
767 viewProtector->windowToContents(frame->view()->contentsToWindow(eventPos)), clipboard, frameProtector.get(), forLink);
768
769 cleanupAfterSystemDrag();
770 }
771
772 // Manual drag caret manipulation
placeDragCaret(const IntPoint & windowPoint)773 void DragController::placeDragCaret(const IntPoint& windowPoint)
774 {
775 mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(windowPoint));
776 if (!m_documentUnderMouse)
777 return;
778 Frame* frame = m_documentUnderMouse->frame();
779 FrameView* frameView = frame->view();
780 if (!frameView)
781 return;
782 IntPoint framePoint = frameView->windowToContents(windowPoint);
783 VisibleSelection dragCaret(frame->visiblePositionForPoint(framePoint));
784 m_page->dragCaretController()->setSelection(dragCaret);
785 }
786
787 } // namespace WebCore
788