DragController.cpp 38.6 KB
Newer Older
1
/*
2
 * Copyright (C) 2007, 2009, 2010 Apple Inc. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include "config.h"
#include "DragController.h"

bolsinga@apple.com's avatar
bolsinga@apple.com committed
29
#if ENABLE(DRAG_SUPPORT)
30 31
#include "Clipboard.h"
#include "ClipboardAccessPolicy.h"
32
#include "CachedResourceLoader.h"
33 34 35
#include "Document.h"
#include "DocumentFragment.h"
#include "DragActions.h"
darin's avatar
darin committed
36 37
#include "DragClient.h"
#include "DragData.h"
38
#include "DragSession.h"
39 40 41 42
#include "Editor.h"
#include "EditorClient.h"
#include "Element.h"
#include "EventHandler.h"
43
#include "FloatRect.h"
44 45
#include "Frame.h"
#include "FrameLoader.h"
46
#include "FrameSelection.h"
47 48
#include "FrameView.h"
#include "HTMLAnchorElement.h"
49 50
#include "HTMLInputElement.h"
#include "HTMLNames.h"
51
#include "HTMLPlugInElement.h"
52
#include "HitTestRequest.h"
darin's avatar
darin committed
53
#include "HitTestResult.h"
54
#include "Image.h"
55
#include "ImageOrientation.h"
56 57 58
#include "MoveSelectionCommand.h"
#include "Node.h"
#include "Page.h"
59
#include "PlatformKeyboardEvent.h"
60
#include "RenderFileUploadControl.h"
61
#include "RenderImage.h"
62
#include "RenderView.h"
63 64
#include "ReplaceSelectionCommand.h"
#include "ResourceRequest.h"
65
#include "SecurityOrigin.h"
oliver's avatar
 
oliver committed
66
#include "Settings.h"
67
#include "ShadowRoot.h"
68
#include "StylePropertySet.h"
69
#include "Text.h"
70
#include "TextEvent.h"
71
#include "htmlediting.h"
darin's avatar
darin committed
72
#include "markup.h"
ap@webkit.org's avatar
ap@webkit.org committed
73
#include <wtf/CurrentTime.h>
74
#include <wtf/RefPtr.h>
75 76 77 78 79

namespace WebCore {

static PlatformMouseEvent createMouseEvent(DragData* dragData)
{
80 81
    bool shiftKey, ctrlKey, altKey, metaKey;
    shiftKey = ctrlKey = altKey = metaKey = false;
82 83 84 85 86 87
    int keyState = dragData->modifierKeyState();
    shiftKey = static_cast<bool>(keyState & PlatformEvent::ShiftKey);
    ctrlKey = static_cast<bool>(keyState & PlatformEvent::CtrlKey);
    altKey = static_cast<bool>(keyState & PlatformEvent::AltKey);
    metaKey = static_cast<bool>(keyState & PlatformEvent::MetaKey);

88
    return PlatformMouseEvent(dragData->clientPosition(), dragData->globalPosition(),
89
                              LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
90
                              metaKey, currentTime());
91
}
92

93 94 95
DragController::DragController(Page* page, DragClient* client)
    : m_page(page)
    , m_client(client)
96
    , m_documentUnderMouse(0)
97
    , m_dragInitiator(0)
98
    , m_fileInputElementUnderMouse(0)
99
    , m_documentIsHandlingDrag(false)
100 101 102
    , m_dragDestinationAction(DragDestinationActionNone)
    , m_dragSourceAction(DragSourceActionNone)
    , m_didInitiateDrag(false)
103
    , m_sourceDragOperation(DragOperationNone)
104
{
105
    ASSERT(m_client);
106
}
107

108
DragController::~DragController()
109
{
110 111
    m_client->dragControllerDestroyed();
}
112

113 114 115 116 117
PassOwnPtr<DragController> DragController::create(Page* page, DragClient* client)
{
    return adoptPtr(new DragController(page, client));
}

118
static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, Frame* frame, RefPtr<Range> context,
oliver's avatar
oliver committed
119
                                          bool allowPlainText, bool& chosePlainText)
120 121 122 123
{
    ASSERT(dragData);
    chosePlainText = false;

124
    Document* document = context->ownerDocument();
125 126
    ASSERT(document);
    if (document && dragData->containsCompatibleContent()) {
127
        if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(frame, context, allowPlainText, chosePlainText))
128 129
            return fragment;

130
        if (dragData->containsURL(frame, DragData::DoNotConvertFilenames)) {
131
            String title;
132
            String url = dragData->asURL(frame, DragData::DoNotConvertFilenames, &title);
ggaren's avatar
ggaren committed
133
            if (!url.isEmpty()) {
134
                RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(document);
135
                anchor->setHref(url);
136 137 138
                if (title.isEmpty()) {
                    // Try the plain text first because the url might be normalized or escaped.
                    if (dragData->containsPlainText())
139
                        title = dragData->asPlainText(frame);
140 141 142
                    if (title.isEmpty())
                        title = url;
                }
143
                RefPtr<Node> anchorText = document->createTextNode(title);
144
                ExceptionCode ec;
145 146 147 148 149 150 151 152 153
                anchor->appendChild(anchorText, ec);
                RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
                fragment->appendChild(anchor, ec);
                return fragment.get();
            }
        }
    }
    if (allowPlainText && dragData->containsPlainText()) {
        chosePlainText = true;
154
        return createFragmentFromText(context.get(), dragData->asPlainText(frame)).get();
155
    }
156

157 158 159
    return 0;
}

160
bool DragController::dragIsMove(FrameSelection* selection, DragData* dragData)
161
{
162
    return m_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && selection->isRange() && !isCopyKeyDown(dragData);
163 164
}

165
// FIXME: This method is poorly named.  We're just clearing the selection from the document this drag is exiting.
166 167 168 169 170
void DragController::cancelDrag()
{
    m_page->dragCaretController()->clear();
}

oliver's avatar
oliver committed
171 172 173
void DragController::dragEnded()
{
    m_dragInitiator = 0;
174 175
    m_didInitiateDrag = false;
    m_page->dragCaretController()->clear();
176 177
    
    m_client->dragEnded();
178
}
179

180
DragSession DragController::dragEntered(DragData* dragData)
181 182 183
{
    return dragEnteredOrUpdated(dragData);
}
184 185 186

void DragController::dragExited(DragData* dragData)
{
187 188
    ASSERT(dragData);
    Frame* mainFrame = m_page->mainFrame();
189

190
    if (RefPtr<FrameView> v = mainFrame->view()) {
191
        ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
192
        RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame);
193 194 195 196
        clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
        mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
    }
197
    mouseMovedIntoDocument(0);
198 199 200
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = 0;
201
}
ggaren@apple.com's avatar
ggaren@apple.com committed
202

203
DragSession DragController::dragUpdated(DragData* dragData)
204 205 206
{
    return dragEnteredOrUpdated(dragData);
}
207

208
bool DragController::performDrag(DragData* dragData)
209
{
210
    ASSERT(dragData);
211
    m_documentUnderMouse = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
212
    if ((m_dragDestinationAction & DragDestinationActionDHTML) && m_documentIsHandlingDrag) {
213
        m_client->willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
214
        RefPtr<Frame> mainFrame = m_page->mainFrame();
215
        bool preventedDefault = false;
216 217
        if (mainFrame->view()) {
            // Sending an event can result in the destruction of the view and part.
218
            RefPtr<Clipboard> clipboard = Clipboard::create(ClipboardReadable, dragData, mainFrame.get());
219
            clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
220 221 222
            preventedDefault = mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
            clipboard->setAccessPolicy(ClipboardNumb); // Invalidate clipboard here for security
        }
223
        if (preventedDefault) {
224 225
            m_documentUnderMouse = 0;
            return true;
226
        }
227 228
    }

229
    if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
230
        m_documentUnderMouse = 0;
231 232
        return true;
    }
233

234
    m_documentUnderMouse = 0;
235

236
    if (operationForLoad(dragData) == DragOperationNone)
237
        return false;
238 239

    m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
240
    m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL(m_page->mainFrame())), false);
241 242
    return true;
}
243 244 245 246 247 248 249 250 251 252 253 254

void DragController::mouseMovedIntoDocument(Document* newDocument)
{
    if (m_documentUnderMouse == newDocument)
        return;

    // If we were over another document clear the selection
    if (m_documentUnderMouse)
        cancelDrag();
    m_documentUnderMouse = newDocument;
}

255
DragSession DragController::dragEnteredOrUpdated(DragData* dragData)
256 257
{
    ASSERT(dragData);
258
    ASSERT(m_page->mainFrame());
259 260
    mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(dragData->clientPosition()));

261
    m_dragDestinationAction = m_client->actionMaskForDrag(dragData);
262
    if (m_dragDestinationAction == DragDestinationActionNone) {
263
        cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
264
        return DragSession();
265
    }
266

267
    DragSession dragSession;
268 269
    m_documentIsHandlingDrag = tryDocumentDrag(dragData, m_dragDestinationAction, dragSession);
    if (!m_documentIsHandlingDrag && (m_dragDestinationAction & DragDestinationActionLoad))
270 271
        dragSession.operation = operationForLoad(dragData);
    return dragSession;
272
}
273 274 275 276

static HTMLInputElement* asFileInput(Node* node)
{
    ASSERT(node);
277

278
    HTMLInputElement* inputElement = node->toInputElement();
279

280
    // If this is a button inside of the a file input, move up to the file input.
281
    if (inputElement && inputElement->isTextButton() && inputElement->treeScope()->rootNode()->isShadowRoot())
282
        inputElement = toShadowRoot(inputElement->treeScope()->rootNode())->host()->toInputElement();
283

284
    return inputElement && inputElement->isFileUpload() ? inputElement : 0;
285
}
286

287
// This can return null if an empty document is loaded.
288 289
static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
{
290 291
    Frame* frame = documentUnderMouse->frame();
    float zoomFactor = frame ? frame->pageZoomFactor() : 1;
292
    LayoutPoint point = roundedLayoutPoint(FloatPoint(p.x() * zoomFactor, p.y() * zoomFactor));
293 294 295

    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
    HitTestResult result(point);
296
    documentUnderMouse->renderView()->hitTest(request, result);
297 298 299 300 301 302 303 304 305 306

    Node* n = result.innerNode();
    while (n && !n->isElementNode())
        n = n->parentNode();
    if (n)
        n = n->shadowAncestorNode();

    return static_cast<Element*>(n);
}

307
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragSession& dragSession)
308 309
{
    ASSERT(dragData);
310

311
    if (!m_documentUnderMouse)
312
        return false;
313

314 315 316
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

317
    bool isHandlingDrag = false;
318
    if (actionMask & DragDestinationActionDHTML) {
319
        isHandlingDrag = tryDHTMLDrag(dragData, dragSession.operation);
320 321 322 323 324 325
        // Do not continue if m_documentUnderMouse has been reset by tryDHTMLDrag.
        // tryDHTMLDrag fires dragenter event. The event listener that listens
        // to this event may create a nested message loop (open a modal dialog),
        // which could process dragleave event and reset m_documentUnderMouse in
        // dragExited.
        if (!m_documentUnderMouse)
326
            return false;
327
    }
328

329 330
    // It's unclear why this check is after tryDHTMLDrag.
    // We send drag events in tryDHTMLDrag and that may be the reason.
331
    RefPtr<FrameView> frameView = m_documentUnderMouse->view();
332
    if (!frameView)
333 334
        return false;

335
    if (isHandlingDrag) {
336 337
        m_page->dragCaretController()->clear();
        return true;
338 339 340
    }

    if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
341
        if (dragData->containsColor()) {
342
            dragSession.operation = DragOperationGeneric;
343 344
            return true;
        }
345

346
        IntPoint point = frameView->windowToContents(dragData->clientPosition());
347
        Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
348 349
        if (!element)
            return false;
350 351
        
        HTMLInputElement* elementAsFileInput = asFileInput(element);
352 353 354 355 356 357 358
        if (m_fileInputElementUnderMouse != elementAsFileInput) {
            if (m_fileInputElementUnderMouse)
                m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
            m_fileInputElementUnderMouse = elementAsFileInput;
        }
        
        if (!m_fileInputElementUnderMouse)
359
            m_page->dragCaretController()->setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
360 361

        Frame* innerFrame = element->document()->frame();
362
        dragSession.operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
363
        dragSession.mouseIsOverFileInput = m_fileInputElementUnderMouse;
364 365 366
        dragSession.numberOfItemsToBeAccepted = 0;

        unsigned numberOfFiles = dragData->numberOfFiles();
367 368
        if (m_fileInputElementUnderMouse) {
            if (m_fileInputElementUnderMouse->disabled())
369
                dragSession.numberOfItemsToBeAccepted = 0;
370
            else if (m_fileInputElementUnderMouse->multiple())
371
                dragSession.numberOfItemsToBeAccepted = numberOfFiles;
372 373
            else if (numberOfFiles > 1)
                dragSession.numberOfItemsToBeAccepted = 0;
374 375 376 377 378
            else
                dragSession.numberOfItemsToBeAccepted = 1;
            
            if (!dragSession.numberOfItemsToBeAccepted)
                dragSession.operation = DragOperationNone;
379
            m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(dragSession.numberOfItemsToBeAccepted);
380 381 382 383 384 385
        } else {
            // We are not over a file input element. The dragged item(s) will only
            // be loaded into the view the number of dragged items is 1.
            dragSession.numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
        }
        
386 387
        return true;
    }
388 389
    
    // We are not over an editable region. Make sure we're clearing any prior drag cursor.
390
    m_page->dragCaretController()->clear();
391 392 393
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = 0;
394
    return false;
395
}
396

397
DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
398
{
399
    m_dragSourceAction = m_client->dragSourceActionMaskForPoint(rootViewPoint);
400 401
    return m_dragSourceAction;
}
402

403 404 405
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
406
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
407
    if (doc && (m_didInitiateDrag || doc->isPluginDocument() || doc->rendererIsEditable()))
408 409 410 411
        return DragOperationNone;
    return dragOperation(dragData);
}

412
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
413
{
darin@apple.com's avatar
darin@apple.com committed
414 415
    frame->selection()->setSelection(dragCaret);
    if (frame->selection()->isNone()) {
oliver's avatar
oliver committed
416
        dragCaret = frame->visiblePositionForPoint(point);
darin@apple.com's avatar
darin@apple.com committed
417
        frame->selection()->setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
418
        range = dragCaret.toNormalizedRange();
419
    }
darin@apple.com's avatar
darin@apple.com committed
420
    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
421 422
}

423 424
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
425 426 427
    ASSERT(m_page->dragCaretController()->hasCaret());
    String text = m_page->dragCaretController()->isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
    Node* target = innerFrame->editor()->findEventTargetFrom(m_page->dragCaretController()->caretPosition());
428
    ExceptionCode ec = 0;
429
    return target->dispatchEvent(TextEvent::createForDrop(innerFrame->document()->domWindow(), text), ec);
430 431
}

432
bool DragController::concludeEditDrag(DragData* dragData)
433 434
{
    ASSERT(dragData);
435

436
    RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
437 438 439 440 441
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = 0;
    }

442
    if (!m_documentUnderMouse)
443
        return false;
444

445
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
446
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
447 448
    if (!element)
        return false;
449
    RefPtr<Frame> innerFrame = element->ownerDocument()->frame();
450
    ASSERT(innerFrame);
451

452
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
453 454
        return true;

455 456 457 458
    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
eric@webkit.org's avatar
eric@webkit.org committed
459
        RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
460
        RefPtr<StylePropertySet> style = StylePropertySet::create();
461
        style->setProperty(CSSPropertyColor, color.serialized(), false);
462
        if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
463 464
            return false;
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
465
        innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
466 467
        return true;
    }
468

469 470 471 472
    if (dragData->containsFiles() && fileInput) {
        // fileInput should be the element we hit tested for, unless it was made
        // display:none in a drop event handler.
        ASSERT(fileInput == element || !fileInput->renderer());
473
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
474
            return false;
475

476
        return fileInput->receiveDroppedFiles(dragData);
477
    }
478

479 480 481 482 483
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }

484
    VisibleSelection dragCaret = m_page->dragCaretController()->caretPosition();
justing's avatar
justing committed
485
    m_page->dragCaretController()->clear();
eric@webkit.org's avatar
eric@webkit.org committed
486
    RefPtr<Range> range = dragCaret.toNormalizedRange();
487
    RefPtr<Element> rootEditableElement = innerFrame->selection()->rootEditableElement();
488

oliver's avatar
oliver committed
489 490
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
491
    if (!range)
oliver's avatar
oliver committed
492
        return false;
493
    CachedResourceLoader* cachedResourceLoader = range->ownerDocument()->cachedResourceLoader();
494
    ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
495
    if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
496
        bool chosePlainText = false;
497
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame.get(), range, true, chosePlainText);
498
        if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
499
            return false;
500
        }
501

502
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
503
        if (dragIsMove(innerFrame->selection(), dragData)) {
504 505 506
            // NSTextView behavior is to always smart delete on moving a selection,
            // but only to smart insert if the selection granularity is word granularity.
            bool smartDelete = innerFrame->editor()->smartInsertDeleteEnabled();
507
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
508
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
509
        } else {
510
            if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
511 512 513 514 515 516 517
                ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
                if (dragData->canSmartReplace())
                    options |= ReplaceSelectionCommand::SmartReplace;
                if (chosePlainText)
                    options |= ReplaceSelectionCommand::MatchStyle;
                applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), fragment, options));
            }
518
        }
519
    } else {
520
        String text = dragData->asPlainText(innerFrame.get());
521
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
522
            return false;
523
        }
524

525
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
526
        if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
527
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
528 529
    }

530 531 532 533 534
    if (rootEditableElement) {
        if (Frame* frame = rootEditableElement->document()->frame())
            frame->eventHandler()->updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
    }

535 536
    return true;
}
537 538

bool DragController::canProcessDrag(DragData* dragData)
539 540 541 542 543
{
    ASSERT(dragData);

    if (!dragData->containsCompatibleContent())
        return false;
544

545
    IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
546
    HitTestResult result = HitTestResult(point);
eric@webkit.org's avatar
eric@webkit.org committed
547
    if (!m_page->mainFrame()->contentRenderer())
548 549
        return false;

550
    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
551 552

    if (!result.innerNonSharedNode())
553
        return false;
554

555 556
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
557

558 559 560 561 562
    if (result.innerNonSharedNode()->isPluginElement()) {
        HTMLPlugInElement* plugin = static_cast<HTMLPlugInElement*>(result.innerNonSharedNode());
        if (!plugin->canProcessDrag() && !result.innerNonSharedNode()->rendererIsEditable())
            return false;
    } else if (!result.innerNonSharedNode()->rendererIsEditable())
563
        return false;
564

565
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
566
        return false;
567

568 569 570
    return true;
}

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
static DragOperation defaultOperationForDrag(DragOperation srcOpMask)
{
    // This is designed to match IE's operation fallback for the case where
    // the page calls preventDefault() in a drag event but doesn't set dropEffect.
    if (srcOpMask == DragOperationEvery)
        return DragOperationCopy;
    if (srcOpMask == DragOperationNone)
        return DragOperationNone;
    if (srcOpMask & DragOperationMove || srcOpMask & DragOperationGeneric)
        return DragOperationMove;
    if (srcOpMask & DragOperationCopy)
        return DragOperationCopy;
    if (srcOpMask & DragOperationLink)
        return DragOperationLink;
    
    // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
    return DragOperationGeneric;
}

590
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
591
{
592
    ASSERT(dragData);
593
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
594 595
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = mainFrame->view();
596
    if (!viewProtector)
597 598
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
599
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
600
    RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
601 602
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
603

604 605
    PlatformMouseEvent event = createMouseEvent(dragData);
    if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
606
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
607 608 609
        return false;
    }

610
    operation = clipboard->destinationOperation();
611 612 613
    if (clipboard->dropEffectIsUninitialized())
        operation = defaultOperationForDrag(srcOpMask);
    else if (!(srcOpMask & operation)) {
614 615
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
616
    }
617 618 619

    clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
    return true;
620 621
}

622
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
623
{
624
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
625 626 627

    for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
        Node* node = renderer->node();
628 629 630 631 632 633 634 635 636 637
        if (!node)
            // Anonymous render blocks don't correspond to actual DOM nodes, so we skip over them
            // for the purposes of finding a draggable node.
            continue;
        if (!(state.m_dragType & DragSourceActionSelection) && node->isTextNode() && node->canStartSelection())
            // In this case we have a click in the unselected portion of text. If this text is
            // selectable, we want to start the selection process instead of looking for a parent
            // to try to drag.
            return 0;
        if (node->isElementNode()) {
638
            EUserDrag dragMode = renderer->style()->userDrag();
639 640
            if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
641 642
                return node;
            }
643 644 645
            if (dragMode == DRAG_AUTO) {
                if ((m_dragSourceAction & DragSourceActionImage)
                    && node->hasTagName(HTMLNames::imgTag)
646
                    && src->settings()
647 648 649 650 651 652 653 654 655 656
                    && src->settings()->loadsImagesAutomatically()) {
                    state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionImage);
                    return node;
                }
                if ((m_dragSourceAction & DragSourceActionLink)
                    && node->hasTagName(HTMLNames::aTag)
                    && static_cast<HTMLAnchorElement*>(node)->isLiveLink()) {
                    state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionLink);
                    return node;
                }
657 658 659
            }
        }
    }
oliver's avatar
 
oliver committed
660

661 662
    // We either have nothing to drag or we have a selection and we're not over a draggable element.
    return (state.m_dragType & DragSourceActionSelection) ? startNode : 0;
oliver's avatar
 
oliver committed
663
}
664

665 666 667 668
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
669
    if (!renderer || !renderer->isImage())
670
        return 0;
671
    RenderImage* image = toRenderImage(renderer);
672 673
    return image->cachedImage();
}
674

675 676 677
static Image* getImage(Element* element)
{
    ASSERT(element);
678
    CachedImage* cachedImage = getCachedImage(element);
679 680 681
    // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
    // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
    // which would be empty when asking the cached BitmapImages.
682
    return (cachedImage && !cachedImage->errorOccurred()) ?
683
        cachedImage->image() : 0;
684
}
685

686
static void prepareClipboardForImageDrag(Frame* source, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
687
{
688 689 690 691 692 693 694 695
    if (node->isContentRichlyEditable()) {
        RefPtr<Range> range = source->document()->createRange();
        ExceptionCode ec = 0;
        range->selectNode(node, ec);
        ASSERT(!ec);
        source->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
    }
    clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, source);
696
}
697

698 699 700
static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
{
    // dragImageOffset is the cursor position relative to the lower-left corner of the image.
701 702
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
703 704 705 706
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
707

708 709
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
710

711 712
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
713

714 715
static IntPoint dragLocForSelectionDrag(Frame* src)
{
716
    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
717
    int xpos = draggingRect.maxX();
718
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
719
    int ypos = draggingRect.maxY();
720 721 722 723 724 725 726 727
#if PLATFORM(MAC)
    // Deal with flipped coordinates on Mac
    ypos = draggingRect.y() > ypos ? draggingRect.y() : ypos;
#else
    ypos = draggingRect.y() < ypos ? draggingRect.y() : ypos;
#endif
    return IntPoint(xpos, ypos);
}
728

729
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
730
{
731
    ASSERT(src);
732

eric@webkit.org's avatar
eric@webkit.org committed
733
    if (!src->view() || !src->contentRenderer())
734
        return false;
735

736
    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
737 738 739 740 741 742 743
    if (!state.m_dragSrc->contains(hitTestResult.innerNode()))
        // The original node being dragged isn't under the drag origin anymore... maybe it was
        // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
        // something that's not actually under the drag origin.
        return false;
    KURL linkURL = hitTestResult.absoluteLinkURL();
    KURL imageURL = hitTestResult.absoluteImageURL();
744

weinig@apple.com's avatar
weinig@apple.com committed
745
    IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.position());
746

747
    m_draggingImageURL = KURL();
748
    m_sourceDragOperation = srcOp;