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