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

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

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

namespace WebCore {

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

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

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

111
DragController::~DragController()
112
{
113 114
    m_client->dragControllerDestroyed();
}
115

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

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

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

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

160 161 162
    return 0;
}

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

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

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

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

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

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

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

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

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

237
    m_documentUnderMouse = 0;
238

239
    if (operationForLoad(dragData) == DragOperationNone)
240
        return false;
241 242

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

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

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

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

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

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

281
    HTMLInputElement* inputElement = node->toInputElement();
282

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

287
    return inputElement && inputElement->isFileUpload() ? inputElement : 0;
288
}
289

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

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

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

    return static_cast<Element*>(n);
}

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

314
    if (!m_documentUnderMouse)
315
        return false;
316

317 318 319
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

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

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

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

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

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

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

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

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

406 407 408
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
409
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
410 411 412 413 414 415 416 417 418 419 420 421

    bool pluginDocumentAcceptsDrags = false;

    if (doc && doc->isPluginDocument()) {
        const Widget* widget = static_cast<PluginDocument*>(doc)->pluginWidget();
        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()))
422 423 424 425
        return DragOperationNone;
    return dragOperation(dragData);
}

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

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

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

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

456
    if (!m_documentUnderMouse)
457
        return false;
458

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

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

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

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

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

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

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

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

516
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
517
        if (dragIsMove(innerFrame->selection(), dragData)) {
518 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.
            bool smartDelete = innerFrame->editor()->smartInsertDeleteEnabled();
521
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
522
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
523
        } else {
524
            if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
525 526 527 528 529 530 531
                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));
            }
532
        }
533
    } else {
534
        String text = dragData->asPlainText(innerFrame.get());
535
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
536
            return false;
537
        }
538

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

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

549 550
    return true;
}
551 552

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

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

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

564
    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
565 566

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

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

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

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

582 583 584
    return true;
}

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

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

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

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

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

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

636
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
637
{
638
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
639 640

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

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

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

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

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

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

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

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

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

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

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

750
    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
751 752 753 754 755 756 757
    if (!state.m_dragSrc->contains(hitTestResult.innerNode()))
        // The original node being dragged isn't under the drag origin anymore... maybe it was
        // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
        // something that's not actually under the drag origin.
        return false;
    KURL linkURL = hitTestResult.absoluteLinkURL();
    KURL imageURL = hitTestResult.absoluteImageURL();
758

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

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

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

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

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

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

786
    Node* node = state.m_dragSrc.get();
787

alice.liu@apple.com's avatar
alice.liu@apple.com committed
788
    Image* image = getImage(static_cast<Element*>(node));
789 790
    if (state.m_dragType == DragSourceActionSelection) {
        if (!clipboard->hasData()) {
791
            if (enclosingTextFormControl(src->selection()->start()))
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
                clipboard->writePlainText(src->editor()->selectedText());
            else {
                RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
                ASSERT(selectionRange);

                clipboard->writeRange(selectionRange.get(), src);
            }
        }
        m_client->willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, clipboard);
        if (!dragImage) {
            dragImage = createDragImageForSelection(src);
            dragLoc = dragLocForSelectionDrag(src);
            m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
        }
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
807
    } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
808
               && (m_dragSourceAction & DragSourceActionImage)) {
809
        // We shouldn't be starting a drag for an image that can't provide an extension.
alice.liu@apple.com's avatar
alice.liu@apple.com committed
810 811
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
812 813
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
814
            m_draggingImageURL = imageURL;
815
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
816
        }
817

818
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
819

820
        if (!dragImage) {
821
            IntRect imageRect = hitTestResult.imageRect();
822
            imageRect.setLocation(m_page->mainFrame()->view()->rootViewToContents(src->view()->contentsToRootView(imageRect.location())));