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