DragController.cpp 37.7 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
#include "CSSMutableStyleDeclaration.h"
31 32
#include "Clipboard.h"
#include "ClipboardAccessPolicy.h"
33
#include "CachedResourceLoader.h"
34 35 36
#include "Document.h"
#include "DocumentFragment.h"
#include "DragActions.h"
darin's avatar
darin committed
37 38
#include "DragClient.h"
#include "DragData.h"
39
#include "DragSession.h"
40 41 42 43
#include "Editor.h"
#include "EditorClient.h"
#include "Element.h"
#include "EventHandler.h"
44
#include "FloatRect.h"
45 46
#include "Frame.h"
#include "FrameLoader.h"
47
#include "FrameSelection.h"
48 49
#include "FrameView.h"
#include "HTMLAnchorElement.h"
50 51
#include "HTMLInputElement.h"
#include "HTMLNames.h"
52
#include "HitTestRequest.h"
darin's avatar
darin committed
53
#include "HitTestResult.h"
54
#include "Image.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 "Text.h"
68
#include "TextEvent.h"
69
#include "htmlediting.h"
darin's avatar
darin committed
70
#include "markup.h"
ap@webkit.org's avatar
ap@webkit.org committed
71
#include <wtf/CurrentTime.h>
72
#include <wtf/RefPtr.h>
73 74 75 76 77

namespace WebCore {

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

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

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

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

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

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

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

149 150 151
    return 0;
}

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

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

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

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

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

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

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

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

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

226
    m_documentUnderMouse = 0;
227

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

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

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

247
DragSession DragController::dragEnteredOrUpdated(DragData* dragData)
248 249
{
    ASSERT(dragData);
250 251 252
    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()));

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

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

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

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

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

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

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

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

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

303
    if (!m_documentUnderMouse)
304
        return false;
305

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

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

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

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

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

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

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

385
DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
386
{
387
    m_dragSourceAction = m_client->dragSourceActionMaskForPoint(rootViewPoint);
388 389
    return m_dragSourceAction;
}
390

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

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

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

420
bool DragController::concludeEditDrag(DragData* dragData)
421 422 423
{
    ASSERT(dragData);
    ASSERT(!m_isHandlingDrag);
424

425 426 427 428 429
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = 0;
    }

430
    if (!m_documentUnderMouse)
431
        return false;
432

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

440
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame, dragData))
441 442
        return true;

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

458 459 460 461
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }
462

463
    if (HTMLInputElement* fileInput = asFileInput(element)) {
464
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
465
            return false;
466

467 468
        if (!dragData->containsFiles())
            return false;
469

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

475
        fileInput->receiveDroppedFiles(filenames);
476 477
        return true;
    }
478

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

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

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

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

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

530 531
    return true;
}
532 533

bool DragController::canProcessDrag(DragData* dragData)
534 535 536 537 538
{
    ASSERT(dragData);

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

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

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
546 547

    if (!result.innerNonSharedNode())
548
        return false;
549

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

553
    if (!result.innerNonSharedNode()->rendererIsEditable())
554
        return false;
555

556
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
557
        return false;
558

559 560 561
    return true;
}

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

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

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

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

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

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

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

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

652 653
    // 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
654
}
655

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

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

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

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

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

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

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

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

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

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

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

738
    m_draggingImageURL = KURL();
739
    m_sourceDragOperation = srcOp;
740

741 742 743
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
744

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

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

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

763
    Node* node = state.m_dragSrc.get();
764

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

795
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
796

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

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
806 807 808
        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.
809
            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
810 811 812 813 814 815 816 817

        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)
818
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
819 820
        }

821 822
        m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
        if (!dragImage) {
823
            dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src);
824 825 826
            IntSize size = dragImageSize(dragImage);
            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
            dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
827
        }
828
        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
829
    } else if (state.m_dragType == DragSourceActionDHTML) {
830 831 832 833
        ASSERT(m_dragSourceAction & DragSourceActionDHTML);
        m_client->willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
    } else {
834 835
        // draggableNode() determined an image or link node was draggable, but it turns out the
        // image or link had no URL, so there is nothing to drag.
836 837
        startedDrag = false;
    }
838

839 840 841 842
    if (dragImage)
        deleteDragImage(dragImage);
    return startedDrag;
}