DragController.cpp 39.6 KB
Newer Older
1
/*
2
 * Copyright (C) 2007, 2009, 2010, 2013 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 "CachedImage.h"
32 33
#include "Clipboard.h"
#include "ClipboardAccessPolicy.h"
34
#include "CachedResourceLoader.h"
35 36 37
#include "Document.h"
#include "DocumentFragment.h"
#include "DragActions.h"
darin's avatar
darin committed
38 39
#include "DragClient.h"
#include "DragData.h"
40
#include "DragSession.h"
41
#include "DragState.h"
42 43 44 45
#include "Editor.h"
#include "EditorClient.h"
#include "Element.h"
#include "EventHandler.h"
46
#include "ExceptionCodePlaceholder.h"
47
#include "FloatRect.h"
48
#include "Frame.h"
49
#include "FrameLoadRequest.h"
50
#include "FrameLoader.h"
51
#include "FrameSelection.h"
52 53
#include "FrameView.h"
#include "HTMLAnchorElement.h"
54 55
#include "HTMLInputElement.h"
#include "HTMLNames.h"
56
#include "HTMLPlugInElement.h"
57
#include "HitTestRequest.h"
darin's avatar
darin committed
58
#include "HitTestResult.h"
59
#include "Image.h"
60
#include "ImageOrientation.h"
61 62
#include "MoveSelectionCommand.h"
#include "Page.h"
63
#include "PlatformKeyboardEvent.h"
64 65
#include "PluginDocument.h"
#include "PluginViewBase.h"
66
#include "RenderFileUploadControl.h"
67
#include "RenderImage.h"
68
#include "RenderView.h"
69 70
#include "ReplaceSelectionCommand.h"
#include "ResourceRequest.h"
71
#include "SecurityOrigin.h"
oliver's avatar
 
oliver committed
72
#include "Settings.h"
73
#include "ShadowRoot.h"
74
#include "StylePropertySet.h"
75
#include "Text.h"
76
#include "TextEvent.h"
77
#include "htmlediting.h"
darin's avatar
darin committed
78
#include "markup.h"
ap@webkit.org's avatar
ap@webkit.org committed
79
#include <wtf/CurrentTime.h>
80
#include <wtf/RefPtr.h>
81 82 83 84 85

namespace WebCore {

static PlatformMouseEvent createMouseEvent(DragData* dragData)
{
86 87
    bool shiftKey, ctrlKey, altKey, metaKey;
    shiftKey = ctrlKey = altKey = metaKey = false;
88 89 90 91 92 93
    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);

94
    return PlatformMouseEvent(dragData->clientPosition(), dragData->globalPosition(),
95
                              LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
96
                              metaKey, currentTime());
97
}
98

99 100 101
DragController::DragController(Page* page, DragClient* client)
    : m_page(page)
    , m_client(client)
102
    , m_documentUnderMouse(0)
103
    , m_dragInitiator(0)
104
    , m_fileInputElementUnderMouse(0)
105
    , m_documentIsHandlingDrag(false)
106 107 108
    , m_dragDestinationAction(DragDestinationActionNone)
    , m_dragSourceAction(DragSourceActionNone)
    , m_didInitiateDrag(false)
109
    , m_sourceDragOperation(DragOperationNone)
110
{
111
    ASSERT(m_client);
112
}
113

114
DragController::~DragController()
115
{
116 117
    m_client->dragControllerDestroyed();
}
118

119 120 121 122 123
PassOwnPtr<DragController> DragController::create(Page* page, DragClient* client)
{
    return adoptPtr(new DragController(page, client));
}

124
static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, Frame* frame, RefPtr<Range> context,
oliver's avatar
oliver committed
125
                                          bool allowPlainText, bool& chosePlainText)
126 127 128 129
{
    ASSERT(dragData);
    chosePlainText = false;

130
    Document* document = context->ownerDocument();
131 132
    ASSERT(document);
    if (document && dragData->containsCompatibleContent()) {
133
        if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(frame, context, allowPlainText, chosePlainText))
134 135
            return fragment;

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

162 163 164
    return 0;
}

165
bool DragController::dragIsMove(FrameSelection* selection, DragData* dragData)
166
{
167
    return m_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && selection->isRange() && !isCopyKeyDown(dragData);
168 169
}

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

oliver's avatar
oliver committed
176 177 178
void DragController::dragEnded()
{
    m_dragInitiator = 0;
179 180
    m_didInitiateDrag = false;
    m_page->dragCaretController()->clear();
181 182
    
    m_client->dragEnded();
183
}
184

185
DragSession DragController::dragEntered(DragData* dragData)
186 187 188
{
    return dragEnteredOrUpdated(dragData);
}
189 190 191

void DragController::dragExited(DragData* dragData)
{
192 193
    ASSERT(dragData);
    Frame* mainFrame = m_page->mainFrame();
194

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

208
DragSession DragController::dragUpdated(DragData* dragData)
209 210 211
{
    return dragEnteredOrUpdated(dragData);
}
212

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

234
    if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
235
        m_documentUnderMouse = 0;
236 237
        return true;
    }
238

239
    m_documentUnderMouse = 0;
240

241
    if (operationForLoad(dragData) == DragOperationNone)
242
        return false;
243 244

    m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
245
    m_page->mainFrame()->loader()->load(FrameLoadRequest(m_page->mainFrame(), ResourceRequest(dragData->asURL(m_page->mainFrame()))));
246 247
    return true;
}
248 249 250 251 252 253 254 255 256 257 258 259

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

260
DragSession DragController::dragEnteredOrUpdated(DragData* dragData)
261 262
{
    ASSERT(dragData);
263
    ASSERT(m_page->mainFrame());
264 265
    mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(dragData->clientPosition()));

266
    m_dragDestinationAction = m_client->actionMaskForDrag(dragData);
267
    if (m_dragDestinationAction == DragDestinationActionNone) {
268
        cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
269
        return DragSession();
270
    }
271

272
    DragSession dragSession;
273 274
    m_documentIsHandlingDrag = tryDocumentDrag(dragData, m_dragDestinationAction, dragSession);
    if (!m_documentIsHandlingDrag && (m_dragDestinationAction & DragDestinationActionLoad))
275 276
        dragSession.operation = operationForLoad(dragData);
    return dragSession;
277
}
278 279 280 281

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

283
    HTMLInputElement* inputElement = node->toInputElement();
284

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

289
    return inputElement && inputElement->isFileUpload() ? inputElement : 0;
290
}
291

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

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

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

309
    return toElement(n);
310 311
}

312
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragSession& dragSession)
313 314
{
    ASSERT(dragData);
315

316
    if (!m_documentUnderMouse)
317
        return false;
318

319 320 321
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

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

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

340
    if (isHandlingDrag) {
341 342
        m_page->dragCaretController()->clear();
        return true;
343 344 345
    }

    if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
346
        if (dragData->containsColor()) {
347
            dragSession.operation = DragOperationGeneric;
348 349
            return true;
        }
350

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

        Frame* innerFrame = element->document()->frame();
367
        dragSession.operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
368
        dragSession.mouseIsOverFileInput = m_fileInputElementUnderMouse;
369 370 371
        dragSession.numberOfItemsToBeAccepted = 0;

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

402
DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
403
{
404
    m_dragSourceAction = m_client->dragSourceActionMaskForPoint(rootViewPoint);
405 406
    return m_dragSourceAction;
}
407

408 409 410
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
411
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
412 413 414 415

    bool pluginDocumentAcceptsDrags = false;

    if (doc && doc->isPluginDocument()) {
416
        const Widget* widget = toPluginDocument(doc)->pluginWidget();
417 418 419 420 421 422 423
        const PluginViewBase* pluginView = (widget && widget->isPluginViewBase()) ? static_cast<const PluginViewBase*>(widget) : 0;

        if (pluginView)
            pluginDocumentAcceptsDrags = pluginView->shouldAllowNavigationFromDrags();
    }

    if (doc && (m_didInitiateDrag || (doc->isPluginDocument() && !pluginDocumentAcceptsDrags) || doc->rendererIsEditable()))
424 425 426 427
        return DragOperationNone;
    return dragOperation(dragData);
}

428
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
429
{
darin@apple.com's avatar
darin@apple.com committed
430 431
    frame->selection()->setSelection(dragCaret);
    if (frame->selection()->isNone()) {
oliver's avatar
oliver committed
432
        dragCaret = frame->visiblePositionForPoint(point);
darin@apple.com's avatar
darin@apple.com committed
433
        frame->selection()->setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
434
        range = dragCaret.toNormalizedRange();
435
    }
darin@apple.com's avatar
darin@apple.com committed
436
    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
437 438
}

439 440
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
441 442
    ASSERT(m_page->dragCaretController()->hasCaret());
    String text = m_page->dragCaretController()->isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
443
    Node* target = innerFrame->editor().findEventTargetFrom(m_page->dragCaretController()->caretPosition());
444
    return target->dispatchEvent(TextEvent::createForDrop(innerFrame->document()->domWindow(), text), IGNORE_EXCEPTION);
445 446
}

447
bool DragController::concludeEditDrag(DragData* dragData)
448 449
{
    ASSERT(dragData);
450

451
    RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
452 453 454 455 456
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = 0;
    }

457
    if (!m_documentUnderMouse)
458
        return false;
459

460
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
461
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
462 463
    if (!element)
        return false;
464
    RefPtr<Frame> innerFrame = element->ownerDocument()->frame();
465
    ASSERT(innerFrame);
466

467
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
468 469
        return true;

470 471 472 473
    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
eric@webkit.org's avatar
eric@webkit.org committed
474
        RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
475
        RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
476
        style->setProperty(CSSPropertyColor, color.serialized(), false);
477
        if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
478 479
            return false;
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
480
        innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
481 482
        return true;
    }
483

484 485 486 487
    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());
488
        if (fileInput->isDisabledFormControl())
adele@apple.com's avatar
adele@apple.com committed
489
            return false;
490

491
        return fileInput->receiveDroppedFiles(dragData);
492
    }
493

494 495 496 497 498
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }

499
    VisibleSelection dragCaret = m_page->dragCaretController()->caretPosition();
justing's avatar
justing committed
500
    m_page->dragCaretController()->clear();
eric@webkit.org's avatar
eric@webkit.org committed
501
    RefPtr<Range> range = dragCaret.toNormalizedRange();
502
    RefPtr<Element> rootEditableElement = innerFrame->selection()->rootEditableElement();
503

oliver's avatar
oliver committed
504 505
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
506
    if (!range)
oliver's avatar
oliver committed
507
        return false;
508
    CachedResourceLoader* cachedResourceLoader = range->ownerDocument()->cachedResourceLoader();
509
    ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
510
    if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
511
        bool chosePlainText = false;
512
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame.get(), range, true, chosePlainText);
513
        if (!fragment || !innerFrame->editor().shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
514
            return false;
515
        }
516

517
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
518
        if (dragIsMove(innerFrame->selection(), dragData)) {
519 520
            // NSTextView behavior is to always smart delete on moving a selection,
            // but only to smart insert if the selection granularity is word granularity.
521
            bool smartDelete = innerFrame->editor().smartInsertDeleteEnabled();
522
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
523
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
524
        } else {
525
            if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
526 527 528 529 530 531 532
                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));
            }
533
        }
534
    } else {
535
        String text = dragData->asPlainText(innerFrame.get());
536
        if (text.isEmpty() || !innerFrame->editor().shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
537
            return false;
538
        }
539

540
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
541
        if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
542
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
543 544
    }

545 546 547 548 549
    if (rootEditableElement) {
        if (Frame* frame = rootEditableElement->document()->frame())
            frame->eventHandler()->updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
    }

550 551
    return true;
}
552 553

bool DragController::canProcessDrag(DragData* dragData)
554 555 556 557 558
{
    ASSERT(dragData);

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

560
    IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
561
    HitTestResult result = HitTestResult(point);
eric@webkit.org's avatar
eric@webkit.org committed
562
    if (!m_page->mainFrame()->contentRenderer())
563 564
        return false;

565
    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
566 567

    if (!result.innerNonSharedNode())
568
        return false;
569

570 571
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
572

573 574 575 576 577
    if (result.innerNonSharedNode()->isPluginElement()) {
        HTMLPlugInElement* plugin = static_cast<HTMLPlugInElement*>(result.innerNonSharedNode());
        if (!plugin->canProcessDrag() && !result.innerNonSharedNode()->rendererIsEditable())
            return false;
    } else if (!result.innerNonSharedNode()->rendererIsEditable())
578
        return false;
579

580
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
581
        return false;
582

583 584 585
    return true;
}

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
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;
}

605
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
606
{
607
    ASSERT(dragData);
608
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
609 610
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = mainFrame->view();
611
    if (!viewProtector)
612 613
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
614
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
615
    RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
616 617
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
618

619 620
    PlatformMouseEvent event = createMouseEvent(dragData);
    if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
621
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
622 623 624
        return false;
    }

625
    operation = clipboard->destinationOperation();
626 627 628
    if (clipboard->dropEffectIsUninitialized())
        operation = defaultOperationForDrag(srcOpMask);
    else if (!(srcOpMask & operation)) {
629 630
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
631
    }
632 633 634

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

637
Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
638
{
639 640 641
    state.type = (sourceFrame->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
    if (!startElement)
        return 0;
642

643
    for (const RenderObject* renderer = startElement->renderer(); renderer; renderer = renderer->parent()) {
644
        Node* node = renderer->nonPseudoNode();
645 646 647 648
        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;
649
        if (!(state.type & DragSourceActionSelection) && node->isTextNode() && node->canStartSelection())
650 651 652 653 654
            // 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()) {
655
            EUserDrag dragMode = renderer->style()->userDrag();
656
            if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
657 658
                state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
                return toElement(node);
659
            }
660 661 662
            if (dragMode == DRAG_AUTO) {
                if ((m_dragSourceAction & DragSourceActionImage)
                    && node->hasTagName(HTMLNames::imgTag)
663 664 665 666
                    && sourceFrame->settings()
                    && sourceFrame->settings()->loadsImagesAutomatically()) {
                    state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
                    return toElement(node);
667 668 669 670
                }
                if ((m_dragSourceAction & DragSourceActionLink)
                    && node->hasTagName(HTMLNames::aTag)
                    && static_cast<HTMLAnchorElement*>(node)->isLiveLink()) {
671 672
                    state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
                    return toElement(node);
673
                }
674 675 676
            }
        }
    }
oliver's avatar
 
oliver committed
677

678
    // We either have nothing to drag or we have a selection and we're not over a draggable element.
679
    return (state.type & DragSourceActionSelection) ? startElement : 0;
oliver's avatar
 
oliver committed
680
}
681

682 683 684 685
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
686
    if (!renderer || !renderer->isImage())
687
        return 0;
688
    RenderImage* image = toRenderImage(renderer);
689 690
    return image->cachedImage();
}
691

692 693 694
static Image* getImage(Element* element)
{
    ASSERT(element);
695
    CachedImage* cachedImage = getCachedImage(element);
696 697 698
    // 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.
699
    return (cachedImage && !cachedImage->errorOccurred()) ?
700
        cachedImage->image() : 0;
701
}
702

703
static void prepareClipboardForImageDrag(Frame* source, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
704
{
705 706
    if (node->isContentRichlyEditable()) {
        RefPtr<Range> range = source->document()->createRange();
707
        range->selectNode(node, ASSERT_NO_EXCEPTION);
708 709 710
        source->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
    }
    clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, source);
711
}
712

713 714 715
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.
716 717
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
718 719 720 721
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
722

723 724
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
725

726 727
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
728

729 730
static IntPoint dragLocForSelectionDrag(Frame* src)
{
731
    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
732
    int xpos = draggingRect.maxX();
733
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
734
    int ypos = draggingRect.maxY();
735 736 737 738 739 740 741 742
#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);
}
743

744
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
745
{
746
    ASSERT(src);
747

eric@webkit.org's avatar
eric@webkit.org committed
748
    if (!src->view() || !src->contentRenderer())
749
        return false;
750

751
    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
752
    if (!state.source->contains(hitTestResult.innerNode()))
753 754 755 756 757 758
        // 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();
759

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

762
    m_draggingImageURL = KURL();
763
    m_sourceDragOperation = srcOp;
764

765 766 767
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
768

769 770
    Clipboard* clipboard = state.clipboard.get();
    if (state.type == DragSourceActionDHTML)
771
        dragImage = clipboard->createDragImage(dragImageOffset);
772
    if (state.type == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty())
773 774
        // Selection, image, and link drags receive a default set of allowed drag operations that
        // follows from:
775
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
776
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
777

778 779 780 781 782 783
    // 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;
    }
784

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

787
    Element* element = state.source.get();
788