DragController.cpp 39 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 "FrameLoadRequest.h"
49
#include "FrameLoader.h"
50
#include "FrameSelection.h"
51 52
#include "FrameView.h"
#include "HTMLAnchorElement.h"
53
#include "HTMLImageElement.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"
darin@apple.com's avatar
darin@apple.com committed
61
#include "MainFrame.h"
62 63
#include "MoveSelectionCommand.h"
#include "Page.h"
64
#include "Pasteboard.h"
65
#include "PlatformKeyboardEvent.h"
66 67
#include "PluginDocument.h"
#include "PluginViewBase.h"
68
#include "RenderFileUploadControl.h"
69
#include "RenderImage.h"
70
#include "RenderView.h"
71 72
#include "ReplaceSelectionCommand.h"
#include "ResourceRequest.h"
73
#include "SecurityOrigin.h"
oliver's avatar
 
oliver committed
74
#include "Settings.h"
75
#include "ShadowRoot.h"
76
#include "StyleProperties.h"
77
#include "Text.h"
78
#include "TextEvent.h"
79
#include "htmlediting.h"
darin's avatar
darin committed
80
#include "markup.h"
ap@webkit.org's avatar
ap@webkit.org committed
81
#include <wtf/CurrentTime.h>
82
#include <wtf/RefPtr.h>
83 84 85

namespace WebCore {

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

96
    return PlatformMouseEvent(dragData.clientPosition(), dragData.globalPosition(),
97
                              LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
98
                              metaKey, currentTime());
99
}
100

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

115
DragController::~DragController()
116
{
117
    m_client.dragControllerDestroyed();
118 119
}

120
static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData& dragData, Frame* frame, Range& context, bool allowPlainText, bool& chosePlainText)
121 122 123
{
    chosePlainText = false;

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

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

155 156 157
    return 0;
}

158
bool DragController::dragIsMove(FrameSelection& selection, DragData& dragData)
159
{
160
    return m_documentUnderMouse == m_dragInitiator && selection.isContentEditable() && selection.isRange() && !isCopyKeyDown(dragData);
161 162
}

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

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

178
DragSession DragController::dragEntered(DragData& dragData)
179 180 181
{
    return dragEnteredOrUpdated(dragData);
}
182

183
void DragController::dragExited(DragData& dragData)
184
{
185
    if (RefPtr<FrameView> v = m_page.mainFrame().view()) {
186
        ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
187 188
        RefPtr<Clipboard> clipboard = Clipboard::createForDragAndDrop(policy, dragData);
        clipboard->setSourceOperation(dragData.draggingSourceOperationMask());
189
        m_page.mainFrame().eventHandler().cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
190 191
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
    }
192
    mouseMovedIntoDocument(0);
193 194 195
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = 0;
196
}
ggaren@apple.com's avatar
ggaren@apple.com committed
197

198
DragSession DragController::dragUpdated(DragData& dragData)
199 200 201
{
    return dragEnteredOrUpdated(dragData);
}
202

203
bool DragController::performDrag(DragData& dragData)
204
{
205
    m_documentUnderMouse = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
206
    if ((m_dragDestinationAction & DragDestinationActionDHTML) && m_documentIsHandlingDrag) {
207
        m_client.willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
akling@apple.com's avatar
akling@apple.com committed
208
        Ref<MainFrame> mainFrame(m_page.mainFrame());
209
        bool preventedDefault = false;
210 211
        if (mainFrame->view()) {
            // Sending an event can result in the destruction of the view and part.
212 213
            RefPtr<Clipboard> clipboard = Clipboard::createForDragAndDrop(ClipboardReadable, dragData);
            clipboard->setSourceOperation(dragData.draggingSourceOperationMask());
214
            preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), clipboard.get());
215 216
            clipboard->setAccessPolicy(ClipboardNumb); // Invalidate clipboard here for security
        }
217
        if (preventedDefault) {
218 219
            m_documentUnderMouse = 0;
            return true;
220
        }
221 222
    }

223
    if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
224
        m_documentUnderMouse = 0;
225 226
        return true;
    }
227

228
    m_documentUnderMouse = 0;
229

230
    if (operationForLoad(dragData) == DragOperationNone)
231
        return false;
232

233
    m_client.willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
234
    m_page.mainFrame().loader().load(FrameLoadRequest(&m_page.mainFrame(), ResourceRequest(dragData.asURL(&m_page.mainFrame()))));
235 236
    return true;
}
237 238 239 240 241 242 243 244 245 246 247 248

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

249
DragSession DragController::dragEnteredOrUpdated(DragData& dragData)
250
{
251
    mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(dragData.clientPosition()));
252

253
    m_dragDestinationAction = m_client.actionMaskForDrag(dragData);
254
    if (m_dragDestinationAction == DragDestinationActionNone) {
255
        cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
256
        return DragSession();
257
    }
258

259
    DragSession dragSession;
260 261
    m_documentIsHandlingDrag = tryDocumentDrag(dragData, m_dragDestinationAction, dragSession);
    if (!m_documentIsHandlingDrag && (m_dragDestinationAction & DragDestinationActionLoad))
262 263
        dragSession.operation = operationForLoad(dragData);
    return dragSession;
264
}
265 266 267 268

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

270
    HTMLInputElement* inputElement = node->toInputElement();
271

272
    // If this is a button inside of the a file input, move up to the file input.
273 274
    if (inputElement && inputElement->isTextButton() && inputElement->treeScope().rootNode()->isShadowRoot())
        inputElement = toShadowRoot(inputElement->treeScope().rootNode())->hostElement()->toInputElement();
275

276
    return inputElement && inputElement->isFileUpload() ? inputElement : 0;
277
}
278

279
// This can return null if an empty document is loaded.
280 281
static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
{
282 283
    Frame* frame = documentUnderMouse->frame();
    float zoomFactor = frame ? frame->pageZoomFactor() : 1;
284
    LayoutPoint point = roundedLayoutPoint(FloatPoint(p.x() * zoomFactor, p.y() * zoomFactor));
285

286
    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
287
    HitTestResult result(point);
288
    documentUnderMouse->renderView()->hitTest(request, result);
289 290 291 292 293

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

296
    return toElement(n);
297 298
}

299
bool DragController::tryDocumentDrag(DragData& dragData, DragDestinationAction actionMask, DragSession& dragSession)
300
{
301
    if (!m_documentUnderMouse)
302
        return false;
303

304 305 306
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

307
    bool isHandlingDrag = false;
308
    if (actionMask & DragDestinationActionDHTML) {
309
        isHandlingDrag = tryDHTMLDrag(dragData, dragSession.operation);
310 311 312 313 314 315
        // 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)
316
            return false;
317
    }
318

319 320
    // It's unclear why this check is after tryDHTMLDrag.
    // We send drag events in tryDHTMLDrag and that may be the reason.
321
    RefPtr<FrameView> frameView = m_documentUnderMouse->view();
322
    if (!frameView)
323 324
        return false;

325
    if (isHandlingDrag) {
326
        m_page.dragCaretController().clear();
327
        return true;
328 329 330
    }

    if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
331
        if (dragData.containsColor()) {
332
            dragSession.operation = DragOperationGeneric;
333 334
            return true;
        }
335

336
        IntPoint point = frameView->windowToContents(dragData.clientPosition());
337
        Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
338 339
        if (!element)
            return false;
340 341
        
        HTMLInputElement* elementAsFileInput = asFileInput(element);
342 343 344 345 346 347 348
        if (m_fileInputElementUnderMouse != elementAsFileInput) {
            if (m_fileInputElementUnderMouse)
                m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
            m_fileInputElementUnderMouse = elementAsFileInput;
        }
        
        if (!m_fileInputElementUnderMouse)
349
            m_page.dragCaretController().setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
350

351
        Frame* innerFrame = element->document().frame();
352
        dragSession.operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
353
        dragSession.mouseIsOverFileInput = m_fileInputElementUnderMouse;
354 355
        dragSession.numberOfItemsToBeAccepted = 0;

356
        unsigned numberOfFiles = dragData.numberOfFiles();
357
        if (m_fileInputElementUnderMouse) {
358
            if (m_fileInputElementUnderMouse->isDisabledFormControl())
359
                dragSession.numberOfItemsToBeAccepted = 0;
360
            else if (m_fileInputElementUnderMouse->multiple())
361
                dragSession.numberOfItemsToBeAccepted = numberOfFiles;
362 363
            else if (numberOfFiles > 1)
                dragSession.numberOfItemsToBeAccepted = 0;
364 365 366 367 368
            else
                dragSession.numberOfItemsToBeAccepted = 1;
            
            if (!dragSession.numberOfItemsToBeAccepted)
                dragSession.operation = DragOperationNone;
369
            m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(dragSession.numberOfItemsToBeAccepted);
370 371 372 373 374 375
        } 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;
        }
        
376 377
        return true;
    }
378 379
    
    // We are not over an editable region. Make sure we're clearing any prior drag cursor.
380
    m_page.dragCaretController().clear();
381 382 383
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = 0;
384
    return false;
385
}
386

387
DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
388
{
389
    m_dragSourceAction = m_client.dragSourceActionMaskForPoint(rootViewPoint);
390 391
    return m_dragSourceAction;
}
392

393
DragOperation DragController::operationForLoad(DragData& dragData)
394
{
395
    Document* doc = m_page.mainFrame().documentAtPoint(dragData.clientPosition());
396 397 398 399

    bool pluginDocumentAcceptsDrags = false;

    if (doc && doc->isPluginDocument()) {
400
        const Widget* widget = toPluginDocument(doc)->pluginWidget();
401
        const PluginViewBase* pluginView = (widget && widget->isPluginViewBase()) ? toPluginViewBase(widget) : nullptr;
402 403 404 405 406 407

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

    if (doc && (m_didInitiateDrag || (doc->isPluginDocument() && !pluginDocumentAcceptsDrags) || 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
{
414 415
    frame->selection().setSelection(dragCaret);
    if (frame->selection().isNone()) {
oliver's avatar
oliver committed
416
        dragCaret = frame->visiblePositionForPoint(point);
417
        frame->selection().setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
418
        range = dragCaret.toNormalizedRange();
419
    }
420
    return !frame->selection().isNone() && frame->selection().isContentEditable();
421 422
}

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

431
bool DragController::concludeEditDrag(DragData& dragData)
432
{
433
    RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
434 435 436 437 438
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = 0;
    }

439
    if (!m_documentUnderMouse)
440
        return false;
441

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

449
    if (m_page.dragCaretController().hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
450 451
        return true;

452 453
    if (dragData.containsColor()) {
        Color color = dragData.asColor();
454 455
        if (!color.isValid())
            return false;
456
        RefPtr<Range> innerRange = innerFrame->selection().toNormalizedRange();
457
        RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
458
        style->setProperty(CSSPropertyColor, color.serialized(), false);
459
        if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
460
            return false;
461
        m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
462
        innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
463 464
        return true;
    }
465

466
    if (dragData.containsFiles() && fileInput) {
467 468 469
        // 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());
470
        if (fileInput->isDisabledFormControl())
adele@apple.com's avatar
adele@apple.com committed
471
            return false;
472

473
        return fileInput->receiveDroppedFiles(dragData);
474
    }
475

476 477
    if (!m_page.dragController().canProcessDrag(dragData)) {
        m_page.dragCaretController().clear();
478 479 480
        return false;
    }

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

oliver's avatar
oliver committed
486 487
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
488
    if (!range)
oliver's avatar
oliver committed
489
        return false;
490

491
    CachedResourceLoader* cachedResourceLoader = range->ownerDocument().cachedResourceLoader();
492
    ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
493
    if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
494
        bool chosePlainText = false;
495
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame.get(), *range, true, chosePlainText);
496
        if (!fragment || !innerFrame->editor().shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
497
            return false;
498
        }
499

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

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

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

533 534
    return true;
}
535

536
bool DragController::canProcessDrag(DragData& dragData)
537
{
538
    if (!dragData.containsCompatibleContent())
539
        return false;
540

541
    IntPoint point = m_page.mainFrame().view()->windowToContents(dragData.clientPosition());
542
    HitTestResult result = HitTestResult(point);
543
    if (!m_page.mainFrame().contentRenderer())
544 545
        return false;

546
    result = m_page.mainFrame().eventHandler().hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
547 548

    if (!result.innerNonSharedNode())
549
        return false;
550

551
    if (dragData.containsFiles() && asFileInput(result.innerNonSharedNode()))
552
        return true;
553

554
    if (result.innerNonSharedNode()->isPluginElement()) {
555
        if (!toHTMLPlugInElement(result.innerNonSharedNode())->canProcessDrag() && !result.innerNonSharedNode()->rendererIsEditable())
556 557
            return false;
    } else if (!result.innerNonSharedNode()->rendererIsEditable())
558
        return false;
559

560
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
561
        return false;
562

563 564 565
    return true;
}

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
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;
}

585
bool DragController::tryDHTMLDrag(DragData& dragData, DragOperation& operation)
586
{
587
    ASSERT(m_documentUnderMouse);
akling@apple.com's avatar
akling@apple.com committed
588
    Ref<MainFrame> mainFrame(m_page.mainFrame());
ggaren@apple.com's avatar
ggaren@apple.com committed
589
    RefPtr<FrameView> viewProtector = mainFrame->view();
590
    if (!viewProtector)
591 592
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
593
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
594 595
    RefPtr<Clipboard> clipboard = Clipboard::createForDragAndDrop(policy, dragData);
    DragOperation srcOpMask = dragData.draggingSourceOperationMask();
596
    clipboard->setSourceOperation(srcOpMask);
597

598
    PlatformMouseEvent event = createMouseEvent(dragData);
599
    if (!mainFrame->eventHandler().updateDragAndDrop(event, clipboard.get())) {
600
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
601 602 603
        return false;
    }

604
    operation = clipboard->destinationOperation();
605 606 607
    if (clipboard->dropEffectIsUninitialized())
        operation = defaultOperationForDrag(srcOpMask);
    else if (!(srcOpMask & operation)) {
608 609
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
610
    }
611 612 613

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

616
Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
617
{
618
    state.type = (sourceFrame->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
619 620
    if (!startElement)
        return 0;
621

622 623 624 625 626
    for (auto renderer = startElement->renderer(); renderer; renderer = renderer->parent()) {
        Element* element = renderer->nonPseudoElement();
        if (!element) {
            // Anonymous render blocks don't correspond to actual DOM elements, so we skip over them
            // for the purposes of finding a draggable element.
627
            continue;
628
        }
629
        EUserDrag dragMode = renderer->style().userDrag();
630 631 632 633 634 635 636 637 638 639
        if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
            state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
            return element;
        }
        if (dragMode == DRAG_AUTO) {
            if ((m_dragSourceAction & DragSourceActionImage)
                && isHTMLImageElement(element)
                && sourceFrame->settings().loadsImagesAutomatically()) {
                state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
                return element;
640
            }
641 642 643 644 645
            if ((m_dragSourceAction & DragSourceActionLink)
                && isHTMLAnchorElement(element)
                && toHTMLAnchorElement(element)->isLiveLink()) {
                state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
                return element;
646 647 648
            }
        }
    }
oliver's avatar
 
oliver committed
649

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

654
static CachedImage* getCachedImage(Element& element)
655
{
656
    RenderObject* renderer = element.renderer();
657
    if (!renderer || !renderer->isImage())
658
        return 0;
659
    RenderImage* image = toRenderImage(renderer);
660 661
    return image->cachedImage();
}
662

663
static Image* getImage(Element& element)
664
{
665
    CachedImage* cachedImage = getCachedImage(element);
666 667 668
    // 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.
669
    return (cachedImage && !cachedImage->errorOccurred()) ?
670
        cachedImage->image() : 0;
671
}
672

673
static void selectElement(Element& element)
674