DragController.cpp 38.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 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
    ASSERT(m_client);
105
}
106

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

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

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

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

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

156 157 158
    return 0;
}

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

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

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

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

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

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

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

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

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

233
    m_documentUnderMouse = 0;
234

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

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

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

254
DragSession DragController::dragEnteredOrUpdated(DragData* dragData)
255 256
{
    ASSERT(dragData);
257 258 259
    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()));

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

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

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

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

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

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

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

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

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

    return static_cast<Element*>(n);
}

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

310
    if (!m_documentUnderMouse)
311
        return false;
312

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

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

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

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

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

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

        unsigned numberOfFiles = dragData->numberOfFiles();
364 365
        if (m_fileInputElementUnderMouse) {
            if (m_fileInputElementUnderMouse->disabled())
366
                dragSession.numberOfItemsToBeAccepted = 0;
367
            else if (m_fileInputElementUnderMouse->multiple())
368
                dragSession.numberOfItemsToBeAccepted = numberOfFiles;
369 370
            else if (numberOfFiles > 1)
                dragSession.numberOfItemsToBeAccepted = 0;
371 372 373 374 375
            else
                dragSession.numberOfItemsToBeAccepted = 1;
            
            if (!dragSession.numberOfItemsToBeAccepted)
                dragSession.operation = DragOperationNone;
376
            m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(dragSession.numberOfItemsToBeAccepted);
377 378 379 380 381 382
        } else {
            // We are not over a file input element. The dragged item(s) will only
            // be loaded into the view the number of dragged items is 1.
            dragSession.numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
        }
        
383 384
        return true;
    }
385 386
    
    // We are not over an editable region. Make sure we're clearing any prior drag cursor.
387
    m_page->dragCaretController()->clear();
388 389 390
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = 0;
391
    return false;
392
}
393

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

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

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

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

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

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

439
    if (!m_documentUnderMouse)
440
        return false;
441

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

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

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

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

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

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

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

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

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

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

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

532 533
    return true;
}
534 535

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

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

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

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

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

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

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

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

561 562 563
    return true;
}

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

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

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

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

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

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

615
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
616
{
617
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
618 619 620

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

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

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

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

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

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

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

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

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

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

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

729 730 731 732 733 734 735 736
    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();
737

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

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

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

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

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

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

765
    Node* node = state.m_dragSrc.get();
766

alice.liu@apple.com's avatar
alice.liu@apple.com committed
767
    Image* image = getImage(static_cast<Element*>(node));
768 769
    if (state.m_dragType == DragSourceActionSelection) {
        if (!clipboard->hasData()) {
770
            if (enclosingTextFormControl(src->selection()->start()))
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
                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);
786
    } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
787
               && (m_dragSourceAction & DragSourceActionImage)) {
788
        // 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
789 790
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
791 792
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
793
            m_draggingImageURL = imageURL;
794
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
795
        }
796

797
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
798

799
        if (!dragImage) {
800
            IntRect imageRect = hitTestResult.imageRect();
801
            imageRect.setLocation(m_page->mainFrame()->view()->rootViewToContents(src->view()->contentsToRootView(imageRect.location())));
802
            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
803
        } else
804 805 806 807
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
808 809 810
        if (!clipboard->hasData())
            // Simplify whitespace so the title put on the clipboard resembles what the user sees
            // on the web page. This includes replacing newlines with spaces.
811
            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
812 813 814 815 816 817 818 819

        if (src->selection()->isCaret() && src->selection()->isContentEditable()) {
            // a user can initiate a drag on a link without having any text
            // selected.  In this case, we should expand the selection to
            // the enclosing anchor element
            Position pos = src->selection()->base();
            Node* node = enclosingAnchorElement(pos);
            if (node)
820
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
821 822
        }

823 824
        m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
        if (!dragImage) {
825
            dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src);
826 827 828
            IntSize size = dragImageSize(dragImage);
            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
            dragLoc = IntPoint(mouseDraggedPoint.x