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
#include "HTMLImageElement.h"
55 56
#include "HTMLInputElement.h"
#include "HTMLNames.h"
57
#include "HTMLPlugInElement.h"
58
#include "HitTestRequest.h"
darin's avatar
darin committed
59
#include "HitTestResult.h"
60
#include "Image.h"
61
#include "ImageOrientation.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 "StylePropertySet.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 86 87

namespace WebCore {

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

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, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText)
121 122 123 124
{
    ASSERT(dragData);
    chosePlainText = false;

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

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

156 157 158
    return 0;
}

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

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

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

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

void DragController::dragExited(DragData* dragData)
{
186
    ASSERT(dragData);
187

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

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

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

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

232
    m_documentUnderMouse = 0;
233

234
    if (operationForLoad(dragData) == DragOperationNone)
235
        return false;
236

237 238
    m_client.willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
    m_page.mainFrame().loader().load(FrameLoadRequest(&m_page.mainFrame(), ResourceRequest(dragData->asURL(&m_page.mainFrame()))));
239 240
    return true;
}
241 242 243 244 245 246 247 248 249 250 251 252

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

253
DragSession DragController::dragEnteredOrUpdated(DragData* dragData)
254 255
{
    ASSERT(dragData);
256
    mouseMovedIntoDocument(m_page.mainFrame().documentAtPoint(dragData->clientPosition()));
257

258
    m_dragDestinationAction = m_client.actionMaskForDrag(dragData);
259
    if (m_dragDestinationAction == DragDestinationActionNone) {
260
        cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
261
        return DragSession();
262
    }
263

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

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

275
    HTMLInputElement* inputElement = node->toInputElement();
276

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

281
    return inputElement && inputElement->isFileUpload() ? inputElement : 0;
282
}
283

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

291
    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
292
    HitTestResult result(point);
293
    documentUnderMouse->renderView()->hitTest(request, result);
294 295 296 297 298

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

301
    return toElement(n);
302 303
}

304
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragSession& dragSession)
305 306
{
    ASSERT(dragData);
307

308
    if (!m_documentUnderMouse)
309
        return false;
310

311 312 313
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

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

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

332
    if (isHandlingDrag) {
333
        m_page.dragCaretController().clear();
334
        return true;
335 336 337
    }

    if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
338
        if (dragData->containsColor()) {
339
            dragSession.operation = DragOperationGeneric;
340 341
            return true;
        }
342

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

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

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

394
DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
395
{
396
    m_dragSourceAction = m_client.dragSourceActionMaskForPoint(rootViewPoint);
397 398
    return m_dragSourceAction;
}
399

400 401 402
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
403
    Document* doc = m_page.mainFrame().documentAtPoint(dragData->clientPosition());
404 405 406 407

    bool pluginDocumentAcceptsDrags = false;

    if (doc && doc->isPluginDocument()) {
408
        const Widget* widget = toPluginDocument(doc)->pluginWidget();
409 410 411 412 413 414 415
        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()))
416 417 418 419
        return DragOperationNone;
    return dragOperation(dragData);
}

420
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
421
{
422 423
    frame->selection().setSelection(dragCaret);
    if (frame->selection().isNone()) {
oliver's avatar
oliver committed
424
        dragCaret = frame->visiblePositionForPoint(point);
425
        frame->selection().setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
426
        range = dragCaret.toNormalizedRange();
427
    }
428
    return !frame->selection().isNone() && frame->selection().isContentEditable();
429 430
}

431 432
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
433 434 435
    ASSERT(m_page.dragCaretController().hasCaret());
    String text = m_page.dragCaretController().isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
    Node* target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
436
    return target->dispatchEvent(TextEvent::createForDrop(innerFrame->document()->domWindow(), text), IGNORE_EXCEPTION);
437 438
}

439
bool DragController::concludeEditDrag(DragData* dragData)
440 441
{
    ASSERT(dragData);
442

443
    RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
444 445 446 447 448
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = 0;
    }

449
    if (!m_documentUnderMouse)
450
        return false;
451

452
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
453
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
454 455
    if (!element)
        return false;
456
    RefPtr<Frame> innerFrame = element->document().frame();
457
    ASSERT(innerFrame);
458

459
    if (m_page.dragCaretController().hasCaret() && !dispatchTextInputEventFor(innerFrame.get(), dragData))
460 461
        return true;

462 463 464 465
    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
466
        RefPtr<Range> innerRange = innerFrame->selection().toNormalizedRange();
467
        RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
468
        style->setProperty(CSSPropertyColor, color.serialized(), false);
469
        if (!innerFrame->editor().shouldApplyStyle(style.get(), innerRange.get()))
470
            return false;
471
        m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
472
        innerFrame->editor().applyStyle(style.get(), EditActionSetColor);
473 474
        return true;
    }
475

476 477 478 479
    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());
480
        if (fileInput->isDisabledFormControl())
adele@apple.com's avatar
adele@apple.com committed
481
            return false;
482

483
        return fileInput->receiveDroppedFiles(dragData);
484
    }
485

486 487
    if (!m_page.dragController().canProcessDrag(dragData)) {
        m_page.dragCaretController().clear();
488 489 490
        return false;
    }

491 492
    VisibleSelection dragCaret = m_page.dragCaretController().caretPosition();
    m_page.dragCaretController().clear();
eric@webkit.org's avatar
eric@webkit.org committed
493
    RefPtr<Range> range = dragCaret.toNormalizedRange();
494
    RefPtr<Element> rootEditableElement = innerFrame->selection().rootEditableElement();
495

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

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

532
        m_client.willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
533
        if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
534
            applyCommand(ReplaceSelectionCommand::create(*m_documentUnderMouse, createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
535 536
    }

537
    if (rootEditableElement) {
538
        if (Frame* frame = rootEditableElement->document().frame())
539
            frame->eventHandler().updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
540 541
    }

542 543
    return true;
}
544 545

bool DragController::canProcessDrag(DragData* dragData)
546 547 548 549 550
{
    ASSERT(dragData);

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

552
    IntPoint point = m_page.mainFrame().view()->windowToContents(dragData->clientPosition());
553
    HitTestResult result = HitTestResult(point);
554
    if (!m_page.mainFrame().contentRenderer())
555 556
        return false;

557
    result = m_page.mainFrame().eventHandler().hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
558 559

    if (!result.innerNonSharedNode())
560
        return false;
561

562 563
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
564

565 566 567 568 569
    if (result.innerNonSharedNode()->isPluginElement()) {
        HTMLPlugInElement* plugin = static_cast<HTMLPlugInElement*>(result.innerNonSharedNode());
        if (!plugin->canProcessDrag() && !result.innerNonSharedNode()->rendererIsEditable())
            return false;
    } else if (!result.innerNonSharedNode()->rendererIsEditable())
570
        return false;
571

572
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
573
        return false;
574

575 576 577
    return true;
}

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
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;
}

597
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
598
{
599
    ASSERT(dragData);
600
    ASSERT(m_documentUnderMouse);
601
    RefPtr<Frame> mainFrame = &m_page.mainFrame();
ggaren@apple.com's avatar
ggaren@apple.com committed
602
    RefPtr<FrameView> viewProtector = mainFrame->view();
603
    if (!viewProtector)
604 605
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
606
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
607
    RefPtr<Clipboard> clipboard = Clipboard::createForDragAndDrop(policy, *dragData);
608 609
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
610

611
    PlatformMouseEvent event = createMouseEvent(dragData);
612
    if (!mainFrame->eventHandler().updateDragAndDrop(event, clipboard.get())) {
613
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
614 615 616
        return false;
    }

617
    operation = clipboard->destinationOperation();
618 619 620
    if (clipboard->dropEffectIsUninitialized())
        operation = defaultOperationForDrag(srcOpMask);
    else if (!(srcOpMask & operation)) {
621 622
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
623
    }
624 625 626

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

629
Element* DragController::draggableElement(const Frame* sourceFrame, Element* startElement, const IntPoint& dragOrigin, DragState& state) const
630
{
631
    state.type = (sourceFrame->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
632 633
    if (!startElement)
        return 0;
634

635
    for (const RenderObject* renderer = startElement->renderer(); renderer; renderer = renderer->parent()) {
636
        Node* node = renderer->nonPseudoNode();
637 638 639 640
        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;
641
        if (!(state.type & DragSourceActionSelection) && node->isTextNode() && node->canStartSelection())
642 643 644 645 646
            // 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()) {
647
            EUserDrag dragMode = renderer->style()->userDrag();
648
            if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
649 650
                state.type = static_cast<DragSourceAction>(state.type | DragSourceActionDHTML);
                return toElement(node);
651
            }
652 653
            if (dragMode == DRAG_AUTO) {
                if ((m_dragSourceAction & DragSourceActionImage)
654
                    && isHTMLImageElement(node)
655
                    && sourceFrame->settings().loadsImagesAutomatically()) {
656 657
                    state.type = static_cast<DragSourceAction>(state.type | DragSourceActionImage);
                    return toElement(node);
658 659
                }
                if ((m_dragSourceAction & DragSourceActionLink)
660 661
                    && isHTMLAnchorElement(node)
                    && toHTMLAnchorElement(node)->isLiveLink()) {
662 663
                    state.type = static_cast<DragSourceAction>(state.type | DragSourceActionLink);
                    return toElement(node);
664
                }
665 666 667
            }
        }
    }
oliver's avatar
 
oliver committed
668

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

673 674 675 676
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
677
    if (!renderer || !renderer->isImage())
678
        return 0;
679
    RenderImage* image = toRenderImage(renderer);
680 681
    return image->cachedImage();
}
682

683 684 685
static Image* getImage(Element* element)
{
    ASSERT(element);
686
    CachedImage* cachedImage = getCachedImage(element);
687 688 689
    // 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.
690
    return (cachedImage && !cachedImage->errorOccurred()) ?
691
        cachedImage->image() : 0;
692
}
693

694
static void selectElement(Element* element)
695
{
696
    RefPtr<Range> range = element->document().createRange();
697
    range->selectNode(element);
698
    element->document().frame()->selection().setSelection(VisibleSelection(range.get(), DOWNSTREAM));
699
}
700

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

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

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

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

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

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

739
    HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
740
    if (!state.source->contains(hitTestResult.innerNode()))
741 742 743 744 745 746
        // 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();
747

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

750
    m_draggingImageURL = KURL();
751
    m_sourceDragOperation = srcOp;
752

753 754 755
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
756

757 758
    Clipboard* clipboard = state.clipboard.get();
    if (state.type == DragSourceActionDHTML)
759
        dragImage = clipboard->createDragImage(dragImageOffset);