DragController.cpp 38.7 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
#include "Frame.h"
45
#include "FrameLoadRequest.h"
46
#include "FrameLoader.h"
47
#include "FrameSelection.h"
48 49
#include "FrameView.h"
#include "HTMLAnchorElement.h"
50 51
#include "HTMLInputElement.h"
#include "HTMLNames.h"
52
#include "HTMLPlugInElement.h"
53
#include "HitTestRequest.h"
darin's avatar
darin committed
54
#include "HitTestResult.h"
55
#include "Image.h"
56
#include "ImageOrientation.h"
57 58 59
#include "MoveSelectionCommand.h"
#include "Node.h"
#include "Page.h"
60
#include "PlatformKeyboardEvent.h"
61
#include "RenderFileUploadControl.h"
62
#include "RenderImage.h"
63
#include "RenderView.h"
64 65
#include "ReplaceSelectionCommand.h"
#include "ResourceRequest.h"
66
#include "SecurityOrigin.h"
oliver's avatar
 
oliver committed
67
#include "Settings.h"
68
#include "ShadowRoot.h"
69
#include "StylePropertySet.h"
70
#include "Text.h"
71
#include "TextEvent.h"
72
#include "htmlediting.h"
darin's avatar
darin committed
73
#include "markup.h"
ap@webkit.org's avatar
ap@webkit.org committed
74
#include <wtf/CurrentTime.h>
75
#include <wtf/RefPtr.h>
76 77 78 79 80

namespace WebCore {

static PlatformMouseEvent createMouseEvent(DragData* dragData)
{
81 82
    bool shiftKey, ctrlKey, altKey, metaKey;
    shiftKey = ctrlKey = altKey = metaKey = false;
83 84 85 86 87 88
    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);

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

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

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

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

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

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

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

158 159 160
    return 0;
}

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

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

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

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

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

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

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

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

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

235
    m_documentUnderMouse = 0;
236

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

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

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;
}

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

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

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

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

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

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

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

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

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

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

    return static_cast<Element*>(n);
}

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

312
    if (!m_documentUnderMouse)
313
        return false;
314

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

318
    bool isHandlingDrag = false;
319
    if (actionMask & DragDestinationActionDHTML) {
320
        isHandlingDrag = tryDHTMLDrag(dragData, dragSession.operation);
321 322 323 324 325 326
        // 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)
327
            return false;
328
    }
329

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

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

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

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

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

        unsigned numberOfFiles = dragData->numberOfFiles();
368 369
        if (m_fileInputElementUnderMouse) {
            if (m_fileInputElementUnderMouse->disabled())
370
                dragSession.numberOfItemsToBeAccepted = 0;
371
            else if (m_fileInputElementUnderMouse->multiple())
372
                dragSession.numberOfItemsToBeAccepted = numberOfFiles;
373 374
            else if (numberOfFiles > 1)
                dragSession.numberOfItemsToBeAccepted = 0;
375 376 377 378 379
            else
                dragSession.numberOfItemsToBeAccepted = 1;
            
            if (!dragSession.numberOfItemsToBeAccepted)
                dragSession.operation = DragOperationNone;
380
            m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(dragSession.numberOfItemsToBeAccepted);
381 382 383 384 385 386
        } 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;
        }
        
387 388
        return true;
    }
389 390
    
    // We are not over an editable region. Make sure we're clearing any prior drag cursor.
391
    m_page->dragCaretController()->clear();
392 393 394
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = 0;
395
    return false;
396
}
397

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

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

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

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

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

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

443
    if (!m_documentUnderMouse)
444
        return false;
445

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

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

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

470 471 472 473
    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());
474
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
475
            return false;
476

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

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

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

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

503
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
504
        if (dragIsMove(innerFrame->selection(), dragData)) {
505 506 507
            // 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();
508
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
509
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
510
        } else {
511
            if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
512 513 514 515 516 517 518
                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));
            }
519
        }
520
    } else {
521
        String text = dragData->asPlainText(innerFrame.get());
522
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
523
            return false;
524
        }
525

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

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

536 537
    return true;
}
538 539

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

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

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

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

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

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

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

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

569 570 571
    return true;
}

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
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;
}

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

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

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

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

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

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

    for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
628
        Node* node = renderer->nonPseudoNode();
629 630 631 632 633 634 635 636 637 638
        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()) {
639
            EUserDrag dragMode = renderer->style()->userDrag();
640 641
            if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
642 643
                return node;
            }
644 645 646
            if (dragMode == DRAG_AUTO) {
                if ((m_dragSourceAction & DragSourceActionImage)
                    && node->hasTagName(HTMLNames::imgTag)
647
                    && src->settings()
648 649 650 651 652 653 654 655 656 657
                    && 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;
                }
658 659 660
            }
        }
    }
oliver's avatar
 
oliver committed
661

662 663
    // 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
664
}
665

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

676 677 678
static Image* getImage(Element* element)
{
    ASSERT(element);
679
    CachedImage* cachedImage = getCachedImage(element);
680 681 682
    // 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.
683
    return (cachedImage && !cachedImage->errorOccurred()) ?
684
        cachedImage->image() : 0;
685
}
686

687
static void prepareClipboardForImageDrag(Frame* source, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
688
{
689 690 691 692 693 694 695 696
    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);
697
}
698

699 700 701
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.
702 703
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
704 705 706 707
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
708

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

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

715 716
static IntPoint dragLocForSelectionDrag(Frame* src)
{
717
    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
718
    int xpos = draggingRect.maxX();
719
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
720
    int ypos = draggingRect.maxY();
721 722 723 724 725 726 727 728
#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);
}
729

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

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

737
    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
738 739 740 741 742 743 744
    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();
745

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

748
    m_draggingImageURL = KURL();
749
    m_sourceDragOperation = srcOp;
750

751 752 753
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
754

755 756
    Clipboard* clipboard = state.m_dragClipboard.get();
    if (state.m_dragType == DragSourceActionDHTML)
757
        dragImage = clipboard->createDragImage(dragImageOffset);
758 759 760
    if (state.m_dragType == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty())
        // Selection, image, and link drags receive a default set of allowed drag operations that
        // follows from:
761
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
762
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
763

764 765 766 767 768 769
    // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
    // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
    if (dragImage) {
        dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
        m_dragOffset = dragImageOffset;
    }
770

771
    bool startedDrag = true; // optimism - we almost always manage to start the drag
772

773
    Node* node = state.m_dragSrc.get();
774

alice.liu@apple.com's avatar
alice.liu@apple.com committed
775
    Image* image = getImage(static_cast<Element*>(node));
776 777
    if (state.m_dragType == DragSourceActionSelection) {
        if (!clipboard->hasData()) {
778
            if (enclosingTextFormControl(src->selection()->start()))
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
                clipboard->writePlainText(src->editor()->selectedText());
            else {
                RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
                ASSERT(selectionRange);

                clipboard->writeRange(selectionRange.get(), src);
            }
        }
        m_client->willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, clipboard);
        if (!dragImage) {
            dragImage = createDragImageForSelection(src);
            dragLoc = dragLocForSelectionDrag(src);
            m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
        }
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
794
    } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
795
               && (m_dragSourceAction & DragSourceActionImage)) {
796
        // We shouldn't be starting a drag for an image that can't provide an extension.
alice.liu@apple.com's avatar
alice.liu@apple.com committed
797 798
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
799 800
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
801
            m_draggingImageURL = imageURL;
802
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
803
        }
804

805
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
806

807
        if (!dragImage) {
808
            IntRect imageRect = hitTestResult.imageRect();
809
            imageRect.setLocation(m_page->mainFrame()->view()->rootViewToContents(src->view()->contentsToRootView(imageRect.location())));
810
            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
811
        } else
812 813 814 815
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {