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

namespace WebCore {

static PlatformMouseEvent createMouseEvent(DragData* dragData)
{
79 80 81
    bool shiftKey, ctrlKey, altKey, metaKey;
    shiftKey = ctrlKey = altKey = metaKey = false;
    PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
82
    return PlatformMouseEvent(dragData->clientPosition(), dragData->globalPosition(),
83
                              LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
84
                              metaKey, currentTime());
85
}
86

87 88 89
DragController::DragController(Page* page, DragClient* client)
    : m_page(page)
    , m_client(client)
90
    , m_documentUnderMouse(0)
91
    , m_dragInitiator(0)
92
    , m_fileInputElementUnderMouse(0)
93 94 95
    , m_dragDestinationAction(DragDestinationActionNone)
    , m_dragSourceAction(DragSourceActionNone)
    , m_didInitiateDrag(false)
96
    , m_isHandlingDrag(false)
97
    , m_sourceDragOperation(DragOperationNone)
98 99
{
}
100

101
DragController::~DragController()
102
{
103 104
    m_client->dragControllerDestroyed();
}
105

106 107 108 109 110
PassOwnPtr<DragController> DragController::create(Page* page, DragClient* client)
{
    return adoptPtr(new DragController(page, client));
}

111
static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, Frame* frame, RefPtr<Range> context,
oliver's avatar
oliver committed
112
                                          bool allowPlainText, bool& chosePlainText)
113 114 115 116
{
    ASSERT(dragData);
    chosePlainText = false;

117
    Document* document = context->ownerDocument();
118 119
    ASSERT(document);
    if (document && dragData->containsCompatibleContent()) {
120
        if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(frame, context, allowPlainText, chosePlainText))
121 122
            return fragment;

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

150 151 152
    return 0;
}

153
bool DragController::dragIsMove(FrameSelection* selection, DragData* dragData)
154
{
155
    return m_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && selection->isRange() && !isCopyKeyDown(dragData);
156 157
}

158
// FIXME: This method is poorly named.  We're just clearing the selection from the document this drag is exiting.
159 160 161 162 163
void DragController::cancelDrag()
{
    m_page->dragCaretController()->clear();
}

oliver's avatar
oliver committed
164 165 166
void DragController::dragEnded()
{
    m_dragInitiator = 0;
167 168
    m_didInitiateDrag = false;
    m_page->dragCaretController()->clear();
169 170
    
    m_client->dragEnded();
171
}
172

173
DragSession DragController::dragEntered(DragData* dragData)
174 175 176
{
    return dragEnteredOrUpdated(dragData);
}
177 178 179

void DragController::dragExited(DragData* dragData)
{
180 181
    ASSERT(dragData);
    Frame* mainFrame = m_page->mainFrame();
182

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

196
DragSession DragController::dragUpdated(DragData* dragData)
197 198 199
{
    return dragEnteredOrUpdated(dragData);
}
200

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

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

227
    m_documentUnderMouse = 0;
228

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

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

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

248
DragSession DragController::dragEnteredOrUpdated(DragData* dragData)
249 250
{
    ASSERT(dragData);
251 252 253
    ASSERT(m_page->mainFrame()); // It is not possible in Mac WebKit to have a Page without a mainFrame()
    mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(dragData->clientPosition()));

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

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

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

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

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

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

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

    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
    HitTestResult result(point);
    documentUnderMouse->renderView()->layer()->hitTest(request, result);

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

    return static_cast<Element*>(n);
}

300
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragSession& dragSession)
301 302
{
    ASSERT(dragData);
303

304
    if (!m_documentUnderMouse)
305
        return false;
306

307 308 309
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

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

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

    if (m_isHandlingDrag) {
        m_page->dragCaretController()->clear();
        return true;
331
    } else if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
332
        if (dragData->containsColor()) {
333
            dragSession.operation = DragOperationGeneric;
334 335
            return true;
        }
336

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

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

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

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

394 395 396
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
397
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
398
    if (doc && (m_didInitiateDrag || doc->isPluginDocument() || doc->rendererIsEditable()))
399 400 401 402
        return DragOperationNone;
    return dragOperation(dragData);
}

403
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
404
{
darin@apple.com's avatar
darin@apple.com committed
405 406
    frame->selection()->setSelection(dragCaret);
    if (frame->selection()->isNone()) {
oliver's avatar
oliver committed
407
        dragCaret = frame->visiblePositionForPoint(point);
darin@apple.com's avatar
darin@apple.com committed
408
        frame->selection()->setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
409
        range = dragCaret.toNormalizedRange();
410
    }
darin@apple.com's avatar
darin@apple.com committed
411
    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
412 413
}

414 415
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
416 417 418
    ASSERT(m_page->dragCaretController()->hasCaret());
    String text = m_page->dragCaretController()->isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
    Node* target = innerFrame->editor()->findEventTargetFrom(m_page->dragCaretController()->caretPosition());
419 420 421 422
    ExceptionCode ec = 0;
    return target->dispatchEvent(TextEvent::createForDrop(innerFrame->domWindow(), text), ec);
}

423
bool DragController::concludeEditDrag(DragData* dragData)
424 425
{
    ASSERT(dragData);
426

427
    RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
428 429 430 431 432
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = 0;
    }

433
    if (!m_documentUnderMouse)
434
        return false;
435

436
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
437
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
438 439
    if (!element)
        return false;
440
    Frame* innerFrame = element->ownerDocument()->frame();
441
    ASSERT(innerFrame);
442

443
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame, dragData))
444 445
        return true;

446 447 448 449
    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
eric@webkit.org's avatar
eric@webkit.org committed
450
        RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
451
        RefPtr<StylePropertySet> style = StylePropertySet::create();
452
        style->setProperty(CSSPropertyColor, color.serialized(), false);
453
        if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
454 455
            return false;
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
456
        innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
457 458
        return true;
    }
459

460 461 462 463
    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());
464
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
465
            return false;
466

467 468 469 470
        Vector<String> filenames;
        dragData->asFilenames(filenames);
        if (filenames.isEmpty())
            return false;
471

472
        fileInput->receiveDroppedFiles(filenames);
473
        m_client->willPerformDragDestinationAction(DragDestinationActionUpload, dragData);
474 475
        return true;
    }
476

477 478 479 480 481
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }

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

oliver's avatar
oliver committed
487 488
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
489
    if (!range)
oliver's avatar
oliver committed
490
        return false;
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, 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 504
            // 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();
505
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
506
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
507
        } else {
508 509 510 511 512 513 514 515
            if (setSelectionToDragCaret(innerFrame, dragCaret, range, point)) {
                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));
            }
516
        }
517
    } else {
518
        String text = dragData->asPlainText(innerFrame);
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, dragCaret, range, point))
525
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
526 527
    }

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

533 534
    return true;
}
535 536

bool DragController::canProcessDrag(DragData* dragData)
537 538 539 540 541
{
    ASSERT(dragData);

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

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

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
549 550

    if (!result.innerNonSharedNode())
551
        return false;
552

553 554
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
555

556
    if (!result.innerNonSharedNode()->rendererIsEditable())
557
        return false;
558

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

562 563 564
    return true;
}

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

584
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
585
{
586
    ASSERT(dragData);
587
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
588 589
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    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
    RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
595 596
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
597

598 599
    PlatformMouseEvent event = createMouseEvent(dragData);
    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
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
617
{
618
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
619 620 621

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

655 656
    // 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
657
}
658

659 660 661 662
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
663
    if (!renderer || !renderer->isImage())
664
        return 0;
665
    RenderImage* image = toRenderImage(renderer);
666 667
    return image->cachedImage();
}
668

669 670 671
static Image* getImage(Element* element)
{
    ASSERT(element);
672
    CachedImage* cachedImage = getCachedImage(element);
673 674 675
    // 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.
676
    return (cachedImage && !cachedImage->errorOccurred()) ?
677
        cachedImage->image() : 0;
678
}
679

680
static void prepareClipboardForImageDrag(Frame* source, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
681
{
682 683 684 685 686 687 688 689
    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);
690
}
691

692 693 694
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.
695 696
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
697 698 699 700
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
701

702 703
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
704

705 706
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
707

708 709
static IntPoint dragLocForSelectionDrag(Frame* src)
{
710
    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
711
    int xpos = draggingRect.maxX();
712
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
713
    int ypos = draggingRect.maxY();
714 715 716 717 718 719 720 721
#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);
}
722

723
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
724
{
725
    ASSERT(src);
726

eric@webkit.org's avatar
eric@webkit.org committed
727
    if (!src->view() || !src->contentRenderer())
728
        return false;
729

730 731 732 733 734 735 736 737
    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
    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();
738

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

741
    m_draggingImageURL = KURL();
742
    m_sourceDragOperation = srcOp;
743

744 745 746
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
747

748 749
    Clipboard* clipboard = state.m_dragClipboard.get();
    if (state.m_dragType == DragSourceActionDHTML)
750
        dragImage = clipboard->createDragImage(dragImageOffset);
751 752 753
    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:
754
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
755
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
756

757 758 759 760 761 762
    // 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