DragController.cpp 38.3 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 "RenderView.h"
62 63
#include "ReplaceSelectionCommand.h"
#include "ResourceRequest.h"
64
#include "SecurityOrigin.h"
oliver's avatar
 
oliver committed
65
#include "Settings.h"
66
#include "ShadowRoot.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
    bool shiftKey, ctrlKey, altKey, metaKey;
    shiftKey = ctrlKey = altKey = metaKey = false;
81 82 83 84 85 86
    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);

87
    return PlatformMouseEvent(dragData->clientPosition(), dragData->globalPosition(),
88
                              LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
89
                              metaKey, currentTime());
90
}
91

92 93 94
DragController::DragController(Page* page, DragClient* client)
    : m_page(page)
    , m_client(client)
95
    , m_documentUnderMouse(0)
96
    , m_dragInitiator(0)
97
    , m_fileInputElementUnderMouse(0)
98 99 100
    , m_dragDestinationAction(DragDestinationActionNone)
    , m_dragSourceAction(DragSourceActionNone)
    , m_didInitiateDrag(false)
101
    , m_isHandlingDrag(false)
102
    , m_sourceDragOperation(DragOperationNone)
103 104
{
}
105

106
DragController::~DragController()
107
{
108 109
    m_client->dragControllerDestroyed();
}
110

111 112 113 114 115
PassOwnPtr<DragController> DragController::create(Page* page, DragClient* client)
{
    return adoptPtr(new DragController(page, client));
}

116
static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, Frame* frame, RefPtr<Range> context,
oliver's avatar
oliver committed
117
                                          bool allowPlainText, bool& chosePlainText)
118 119 120 121
{
    ASSERT(dragData);
    chosePlainText = false;

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

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

155 156 157
    return 0;
}

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

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

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

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

void DragController::dragExited(DragData* dragData)
{
185 186
    ASSERT(dragData);
    Frame* mainFrame = m_page->mainFrame();
187

188
    if (RefPtr<FrameView> v = mainFrame->view()) {
189
        ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
190
        RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame);
191 192 193 194
        clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
        mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
        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) {
211
        m_client->willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
212
        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::create(ClipboardReadable, dragData, mainFrame.get());
217
            clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
218 219 220
            preventedDefault = mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
            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

    m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
238
    m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL(m_page->mainFrame())), false);
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 257 258
    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()));

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

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

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

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

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

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

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

    HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
    HitTestResult result(point);
294
    documentUnderMouse->renderView()->hitTest(request, result);
295 296 297 298 299 300 301 302 303 304

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

    return static_cast<Element*>(n);
}

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

309
    if (!m_documentUnderMouse)
310
        return false;
311

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

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

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

    if (m_isHandlingDrag) {
        m_page->dragCaretController()->clear();
        return true;
336
    } else if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
337
        if (dragData->containsColor()) {
338
            dragSession.operation = DragOperationGeneric;
339 340
            return true;
        }
341

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

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

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

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

399 400 401
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
402
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
403
    if (doc && (m_didInitiateDrag || doc->isPluginDocument() || doc->rendererIsEditable()))
404 405 406 407
        return DragOperationNone;
    return dragOperation(dragData);
}

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

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

428
bool DragController::concludeEditDrag(DragData* dragData)
429 430
{
    ASSERT(dragData);
431

432
    RefPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
433 434 435 436 437
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = 0;
    }

438
    if (!m_documentUnderMouse)
439
        return false;
440

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

448
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame, dragData))
449 450
        return true;

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

465 466 467 468
    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());
469
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
470
            return false;
471

472 473 474 475
        Vector<String> filenames;
        dragData->asFilenames(filenames);
        if (filenames.isEmpty())
            return false;
476

477
        fileInput->receiveDroppedFiles(filenames);
478 479
        return true;
    }
480

481 482 483 484 485
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }

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

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

504
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
505
        if (dragIsMove(innerFrame->selection(), dragData)) {
506 507 508
            // 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();
509
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
510
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
511
        } else {
512 513 514 515 516 517 518 519
            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));
            }
520
        }
521
    } else {
522
        String text = dragData->asPlainText(innerFrame);
523
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
524
            return false;
525
        }
526

527
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
528
        if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
529
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
530 531
    }

532 533 534 535 536
    if (rootEditableElement) {
        if (Frame* frame = rootEditableElement->document()->frame())
            frame->eventHandler()->updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
    }

537 538
    return true;
}
539 540

bool DragController::canProcessDrag(DragData* dragData)
541 542 543 544 545
{
    ASSERT(dragData);

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

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

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
553 554

    if (!result.innerNonSharedNode())
555
        return false;
556

557 558
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
559

560
    if (!result.innerNonSharedNode()->rendererIsEditable())
561
        return false;
562

563
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
564
        return false;
565

566 567 568
    return true;
}

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

588
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
589
{
590
    ASSERT(dragData);
591
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
592 593
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = mainFrame->view();
594
    if (!viewProtector)
595 596
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
597
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
598
    RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
599 600
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
601

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

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

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

620
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
621
{
622
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
623 624 625

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

659 660
    // 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
661
}
662

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

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

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

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

706 707
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
708

709 710
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
711

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

727
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
728
{
729
    ASSERT(src);
730

eric@webkit.org's avatar
eric@webkit.org committed
731
    if (!src->view() || !src->contentRenderer())
732
        return false;
733

734 735 736 737 738 739 740 741
    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();
742

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

745
    m_draggingImageURL = KURL();
746
    m_sourceDragOperation = srcOp;
747

748 749 750
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
751

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