DragController.cpp 34.9 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)
darin's avatar
darin committed
30
#include "CSSStyleDeclaration.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 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 55 56
#include "MoveSelectionCommand.h"
#include "Node.h"
#include "Page.h"
57
#include "PlatformKeyboardEvent.h"
58
#include "RenderFileUploadControl.h"
59
#include "RenderImage.h"
60
#include "RenderLayer.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 "Text.h"
67
#include "TextEvent.h"
68
#include "htmlediting.h"
darin's avatar
darin committed
69
#include "markup.h"
ap@webkit.org's avatar
ap@webkit.org committed
70
#include <wtf/CurrentTime.h>
71
#include <wtf/RefPtr.h>
72 73 74 75 76

namespace WebCore {

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

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

98
DragController::~DragController()
99
{
100 101
    m_client->dragControllerDestroyed();
}
102

103
static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, Frame* frame, RefPtr<Range> context,
oliver's avatar
oliver committed
104
                                          bool allowPlainText, bool& chosePlainText)
105 106 107 108
{
    ASSERT(dragData);
    chosePlainText = false;

109
    Document* document = context->ownerDocument();
110 111
    ASSERT(document);
    if (document && dragData->containsCompatibleContent()) {
112
        if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(frame, context, allowPlainText, chosePlainText))
113 114
            return fragment;

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

142 143 144
    return 0;
}

145
bool DragController::dragIsMove(FrameSelection* selection, DragData* dragData)
146
{
147
    return m_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && !isCopyKeyDown(dragData);
148 149
}

150
// FIXME: This method is poorly named.  We're just clearing the selection from the document this drag is exiting.
151 152 153 154 155
void DragController::cancelDrag()
{
    m_page->dragCaretController()->clear();
}

oliver's avatar
oliver committed
156 157 158
void DragController::dragEnded()
{
    m_dragInitiator = 0;
159 160
    m_didInitiateDrag = false;
    m_page->dragCaretController()->clear();
161 162
    
    m_client->dragEnded();
163
}
164

165
DragOperation DragController::dragEntered(DragData* dragData)
166 167 168
{
    return dragEnteredOrUpdated(dragData);
}
169 170 171

void DragController::dragExited(DragData* dragData)
{
172 173
    ASSERT(dragData);
    Frame* mainFrame = m_page->mainFrame();
174

175
    if (RefPtr<FrameView> v = mainFrame->view()) {
176
        ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
177
        RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame);
178 179 180 181
        clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
        mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
    }
182
    mouseMovedIntoDocument(0);
183
}
ggaren@apple.com's avatar
ggaren@apple.com committed
184

185
DragOperation DragController::dragUpdated(DragData* dragData)
186 187 188
{
    return dragEnteredOrUpdated(dragData);
}
189

190
bool DragController::performDrag(DragData* dragData)
191
{
192
    ASSERT(dragData);
193
    m_documentUnderMouse = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
194 195 196
    if (m_isHandlingDrag) {
        ASSERT(m_dragDestinationAction & DragDestinationActionDHTML);
        m_client->willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
197
        RefPtr<Frame> mainFrame = m_page->mainFrame();
198 199
        if (mainFrame->view()) {
            // Sending an event can result in the destruction of the view and part.
200
            RefPtr<Clipboard> clipboard = Clipboard::create(ClipboardReadable, dragData, mainFrame.get());
201 202 203 204
            clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
            mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
            clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
        }
205
        m_documentUnderMouse = 0;
206
        return true;
207 208
    }

209
    if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
210
        m_documentUnderMouse = 0;
211 212
        return true;
    }
213

214
    m_documentUnderMouse = 0;
215

216
    if (operationForLoad(dragData) == DragOperationNone)
217
        return false;
218 219

    m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
220
    m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL(m_page->mainFrame())), false);
221 222
    return true;
}
223 224 225 226 227 228 229 230 231 232 233 234

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

235 236 237
DragOperation DragController::dragEnteredOrUpdated(DragData* dragData)
{
    ASSERT(dragData);
238 239 240
    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()));

241
    m_dragDestinationAction = m_client->actionMaskForDrag(dragData);
242
    if (m_dragDestinationAction == DragDestinationActionNone) {
243
        cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
244
        return DragOperationNone;
245
    }
246 247 248 249

    DragOperation operation = DragOperationNone;
    bool handledByDocument = tryDocumentDrag(dragData, m_dragDestinationAction, operation);
    if (!handledByDocument && (m_dragDestinationAction & DragDestinationActionLoad))
250
        return operationForLoad(dragData);
251 252
    return operation;
}
253 254 255 256

static HTMLInputElement* asFileInput(Node* node)
{
    ASSERT(node);
rniwa@webkit.org's avatar
rniwa@webkit.org committed
257 258 259
    
    if (!node->hasTagName(HTMLNames::inputTag))
        return 0;
260

rniwa@webkit.org's avatar
rniwa@webkit.org committed
261
    HTMLInputElement* inputElement = toHTMLInputElement(node);
262

263
    // If this is a button inside of the a file input, move up to the file input.
rniwa@webkit.org's avatar
rniwa@webkit.org committed
264 265 266 267 268 269
    if (inputElement->isTextButton() && inputElement->treeScope()->isShadowRoot()) {
        node = inputElement->treeScope()->shadowHost();
        if (!node->hasTagName(HTMLNames::inputTag))
            return 0;
        inputElement = toHTMLInputElement(node);
    }
270

rniwa@webkit.org's avatar
rniwa@webkit.org committed
271
    return inputElement->isFileUpload() ? inputElement : 0;
272
}
273

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

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

294
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragOperation& operation)
295 296
{
    ASSERT(dragData);
297

298
    if (!m_documentUnderMouse)
299
        return false;
300

301 302 303
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

304
    m_isHandlingDrag = false;
305
    if (actionMask & DragDestinationActionDHTML) {
306
        m_isHandlingDrag = tryDHTMLDrag(dragData, operation);
307 308 309 310 311 312
        // 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)
313
            return false;
314
    }
315

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

    if (m_isHandlingDrag) {
        m_page->dragCaretController()->clear();
        return true;
325
    } else if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
326 327 328 329
        if (dragData->containsColor()) {
            operation = DragOperationGeneric;
            return true;
        }
330

331
        IntPoint point = frameView->windowToContents(dragData->clientPosition());
332
        Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
333 334
        if (!element)
            return false;
335 336
        if (!asFileInput(element))
            m_page->dragCaretController()->setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
337 338

        Frame* innerFrame = element->document()->frame();
339
        operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
340 341
        return true;
    }
342 343
    // If we're not over an editable region, make sure we're clearing any prior drag cursor.
    m_page->dragCaretController()->clear();
344
    return false;
345
}
346 347

DragSourceAction DragController::delegateDragSourceAction(const IntPoint& windowPoint)
348
{
349 350 351
    m_dragSourceAction = m_client->dragSourceActionMaskForPoint(windowPoint);
    return m_dragSourceAction;
}
352

353 354 355
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
356
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
357
    if (doc && (m_didInitiateDrag || doc->isPluginDocument() || doc->rendererIsEditable()))
358 359 360 361
        return DragOperationNone;
    return dragOperation(dragData);
}

362
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
363
{
darin@apple.com's avatar
darin@apple.com committed
364 365
    frame->selection()->setSelection(dragCaret);
    if (frame->selection()->isNone()) {
oliver's avatar
oliver committed
366
        dragCaret = frame->visiblePositionForPoint(point);
darin@apple.com's avatar
darin@apple.com committed
367
        frame->selection()->setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
368
        range = dragCaret.toNormalizedRange();
369
    }
darin@apple.com's avatar
darin@apple.com committed
370
    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
371 372
}

373 374
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
375 376 377
    ASSERT(m_page->dragCaretController()->hasCaret());
    String text = m_page->dragCaretController()->isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
    Node* target = innerFrame->editor()->findEventTargetFrom(m_page->dragCaretController()->caretPosition());
378 379 380 381
    ExceptionCode ec = 0;
    return target->dispatchEvent(TextEvent::createForDrop(innerFrame->domWindow(), text), ec);
}

382
bool DragController::concludeEditDrag(DragData* dragData)
383 384 385
{
    ASSERT(dragData);
    ASSERT(!m_isHandlingDrag);
386

387
    if (!m_documentUnderMouse)
388
        return false;
389

390
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
391
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
392 393
    if (!element)
        return false;
394
    Frame* innerFrame = element->ownerDocument()->frame();
395
    ASSERT(innerFrame);
396

397
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame, dragData))
398 399
        return true;

400 401 402 403
    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
eric@webkit.org's avatar
eric@webkit.org committed
404
        RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
405
        RefPtr<CSSStyleDeclaration> style = m_documentUnderMouse->createCSSStyleDeclaration();
406
        ExceptionCode ec;
407
        style->setProperty("color", color.serialized(), ec);
408 409 410 411 412 413
        if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
            return false;
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
        innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
        return true;
    }
414

415 416 417 418
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }
419

420
    if (HTMLInputElement* fileInput = asFileInput(element)) {
421
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
422
            return false;
423

424 425
        if (!dragData->containsFiles())
            return false;
426

427 428 429 430
        Vector<String> filenames;
        dragData->asFilenames(filenames);
        if (filenames.isEmpty())
            return false;
431

432
        fileInput->receiveDroppedFiles(filenames);
433 434
        return true;
    }
435

436
    VisibleSelection dragCaret = m_page->dragCaretController()->caretPosition();
justing's avatar
justing committed
437
    m_page->dragCaretController()->clear();
eric@webkit.org's avatar
eric@webkit.org committed
438
    RefPtr<Range> range = dragCaret.toNormalizedRange();
439

oliver's avatar
oliver committed
440 441
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
442
    if (!range)
oliver's avatar
oliver committed
443
        return false;
444
    CachedResourceLoader* cachedResourceLoader = range->ownerDocument()->cachedResourceLoader();
445
    ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
446
    if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
447
        bool chosePlainText = false;
448
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame, range, true, chosePlainText);
449
        if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
450
            return false;
451
        }
452

453
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
454
        if (dragIsMove(innerFrame->selection(), dragData)) {
455 456 457
            // 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();
458
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
459
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
460
        } else {
461 462 463 464 465 466 467 468
            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));
            }
469
        }
470
    } else {
471
        String text = dragData->asPlainText(innerFrame);
472
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
473
            return false;
474
        }
475

476
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
477
        if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
478
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
479 480 481 482
    }

    return true;
}
483 484

bool DragController::canProcessDrag(DragData* dragData)
485 486 487 488 489
{
    ASSERT(dragData);

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

491
    IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
492
    HitTestResult result = HitTestResult(point);
eric@webkit.org's avatar
eric@webkit.org committed
493
    if (!m_page->mainFrame()->contentRenderer())
494 495 496
        return false;

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
497 498

    if (!result.innerNonSharedNode())
499
        return false;
500

501 502
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
503

504
    if (!result.innerNonSharedNode()->rendererIsEditable())
505
        return false;
506

507
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
508
        return false;
509

510 511 512
    return true;
}

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
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;
}

532
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
533
{
534
    ASSERT(dragData);
535
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
536 537
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = mainFrame->view();
538
    if (!viewProtector)
539 540
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
541
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
542
    RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
543 544
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
545

546 547
    PlatformMouseEvent event = createMouseEvent(dragData);
    if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
548
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
549 550 551
        return false;
    }

552
    operation = clipboard->destinationOperation();
553 554 555
    if (clipboard->dropEffectIsUninitialized())
        operation = defaultOperationForDrag(srcOpMask);
    else if (!(srcOpMask & operation)) {
556 557
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
558
    }
559 560 561

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

564
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
565
{
566
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
567 568 569

    for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
        Node* node = renderer->node();
570 571 572 573 574 575 576 577 578 579
        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()) {
580
            EUserDrag dragMode = renderer->style()->userDrag();
581 582
            if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
583 584
                return node;
            }
585 586 587 588 589 590 591 592 593 594 595 596 597
            if (dragMode == DRAG_AUTO) {
                if ((m_dragSourceAction & DragSourceActionImage)
                    && node->hasTagName(HTMLNames::imgTag)
                    && 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;
                }
598 599 600
            }
        }
    }
oliver's avatar
 
oliver committed
601

602 603
    // 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
604
}
605

606 607 608 609
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
610
    if (!renderer || !renderer->isImage())
611
        return 0;
612
    RenderImage* image = toRenderImage(renderer);
613 614
    return image->cachedImage();
}
615

616 617 618
static Image* getImage(Element* element)
{
    ASSERT(element);
619 620 621
    CachedImage* cachedImage = getCachedImage(element);
    return (cachedImage && !cachedImage->errorOccurred()) ?
        cachedImage->image() : 0;
622
}
623

624 625 626 627 628
static void prepareClipboardForImageDrag(Frame* src, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
{
    RefPtr<Range> range = src->document()->createRange();
    ExceptionCode ec = 0;
    range->selectNode(node, ec);
629 630
    ASSERT(!ec);
    src->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
631 632
    clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, src);
}
633

634 635 636
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.
637 638
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
639 640 641 642
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
643

644 645
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
646

647 648
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
649

650 651
static IntPoint dragLocForSelectionDrag(Frame* src)
{
652
    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
653
    int xpos = draggingRect.maxX();
654
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
655
    int ypos = draggingRect.maxY();
656 657 658 659 660 661 662 663
#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);
}
664

665
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
666
{
667
    ASSERT(src);
668

eric@webkit.org's avatar
eric@webkit.org committed
669
    if (!src->view() || !src->contentRenderer())
670
        return false;
671

672 673 674 675 676 677 678 679
    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();
680

681
    IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
682

683
    m_draggingImageURL = KURL();
684
    m_sourceDragOperation = srcOp;
685

686 687 688
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
689

690 691
    Clipboard* clipboard = state.m_dragClipboard.get();
    if (state.m_dragType == DragSourceActionDHTML)
692
        dragImage = clipboard->createDragImage(dragImageOffset);
693 694 695
    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:
696
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
697
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
698

699 700 701 702 703 704
    // 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;
    }
705

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

708
    Node* node = state.m_dragSrc.get();
709

alice.liu@apple.com's avatar
alice.liu@apple.com committed
710
    Image* image = getImage(static_cast<Element*>(node));
711 712
    if (state.m_dragType == DragSourceActionSelection) {
        if (!clipboard->hasData()) {
713
            if (enclosingTextFormControl(src->selection()->start()))
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
                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);
729
    } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
730
               && (m_dragSourceAction & DragSourceActionImage)) {
731
        // 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
732 733
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
734 735
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
736
            m_draggingImageURL = imageURL;
737
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
738
        }
739

740
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
741

742
        if (!dragImage) {
743
            IntRect imageRect = hitTestResult.imageRect();
744
            imageRect.setLocation(m_page->mainFrame()->view()->windowToContents(src->view()->contentsToWindow(imageRect.location())));
745
            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
746
        } else
747 748 749 750
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
751 752 753
        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.
754
            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
755 756 757 758 759 760 761 762

        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)
763
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
764 765
        }

766 767
        m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
        if (!dragImage) {
768
            dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src);
769 770 771
            IntSize size = dragImageSize(dragImage);
            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
            dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
772
        }
773
        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
774
    } else if (state.m_dragType == DragSourceActionDHTML) {
775 776 777 778
        ASSERT(m_dragSourceAction & DragSourceActionDHTML);
        m_client->willPerformDragSourceAction