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 "StylePropertySet.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
    bool shiftKey, ctrlKey, altKey, metaKey;
    shiftKey = ctrlKey = altKey = metaKey = false;
80 81 82 83 84 85
    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);

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

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

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

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

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

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

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

154 155 156
    return 0;
}

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

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

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

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

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

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

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

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

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

231
    m_documentUnderMouse = 0;
232

233
    if (operationForLoad(dragData) == DragOperationNone)
234
        return false;
235 236

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

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

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

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

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

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

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

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

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

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

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

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

    return static_cast<Element*>(n);
}

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

308
    if (!m_documentUnderMouse)
309
        return false;
310

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

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

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

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

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

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

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

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

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

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

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

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

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

437
    if (!m_documentUnderMouse)
438
        return false;
439

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

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

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

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

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

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

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

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

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

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

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

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

536 537
    return true;
}
538 539

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

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

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

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

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

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

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

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

565 566 567
    return true;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

760 761 762 763 764 765
    // 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;
    }
766

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

769
    Node* node = state.m_dragSrc.get();
770

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

801
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
802

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

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
812 813 814
        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.
815
            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
816 817 818 819 820 821 822 823

        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)
824
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
825 826
        }

827 828
        m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
        if (!dragImage) {
829
            dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src);
830 831 832
            IntSize size = dragImageSize(dragImage);
            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
            dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
833
        }
834
        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard