DragController.cpp 34.8 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 161
    m_didInitiateDrag = false;
    m_page->dragCaretController()->clear();
}
162

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

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

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

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

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

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

212
    m_documentUnderMouse = 0;
213

214
    if (operationForLoad(dragData) == DragOperationNone)
215
        return false;
216 217

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

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

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

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

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

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

256
    HTMLInputElement* inputElement = node->toInputElement();
257

258
    // If this is a button inside of the a file input, move up to the file input.
259
    if (inputElement && inputElement->isTextButton() && inputElement->treeScope()->isShadowRoot())
260
        inputElement = inputElement->treeScope()->shadowHost()->toInputElement();
261

262
    return inputElement && inputElement->isFileUpload() ? inputElement : 0;
263
}
264

265
// This can return null if an empty document is loaded.
266 267
static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
{
268 269
    Frame* frame = documentUnderMouse->frame();
    float zoomFactor = frame ? frame->pageZoomFactor() : 1;
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    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);
}

285
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragOperation& operation)
286 287
{
    ASSERT(dragData);
288

289
    if (!m_documentUnderMouse)
290
        return false;
291

292 293 294
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

295
    m_isHandlingDrag = false;
296
    if (actionMask & DragDestinationActionDHTML) {
297
        m_isHandlingDrag = tryDHTMLDrag(dragData, operation);
298 299 300 301 302 303
        // 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)
304
            return false;
305
    }
306

307 308
    // It's unclear why this check is after tryDHTMLDrag.
    // We send drag events in tryDHTMLDrag and that may be the reason.
309
    RefPtr<FrameView> frameView = m_documentUnderMouse->view();
310
    if (!frameView)
311 312 313 314 315
        return false;

    if (m_isHandlingDrag) {
        m_page->dragCaretController()->clear();
        return true;
316
    } else if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
317 318 319 320
        if (dragData->containsColor()) {
            operation = DragOperationGeneric;
            return true;
        }
321

322
        IntPoint point = frameView->windowToContents(dragData->clientPosition());
323
        Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
324 325
        if (!element)
            return false;
326 327
        if (!asFileInput(element))
            m_page->dragCaretController()->setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
328 329

        Frame* innerFrame = element->document()->frame();
330
        operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
331 332
        return true;
    }
333 334
    // If we're not over an editable region, make sure we're clearing any prior drag cursor.
    m_page->dragCaretController()->clear();
335
    return false;
336
}
337 338

DragSourceAction DragController::delegateDragSourceAction(const IntPoint& windowPoint)
339
{
340 341 342
    m_dragSourceAction = m_client->dragSourceActionMaskForPoint(windowPoint);
    return m_dragSourceAction;
}
343

344 345 346
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
347
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
348
    if (doc && (m_didInitiateDrag || doc->isPluginDocument() || doc->rendererIsEditable()))
349 350 351 352
        return DragOperationNone;
    return dragOperation(dragData);
}

353
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
354
{
darin@apple.com's avatar
darin@apple.com committed
355 356
    frame->selection()->setSelection(dragCaret);
    if (frame->selection()->isNone()) {
oliver's avatar
oliver committed
357
        dragCaret = frame->visiblePositionForPoint(point);
darin@apple.com's avatar
darin@apple.com committed
358
        frame->selection()->setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
359
        range = dragCaret.toNormalizedRange();
360
    }
darin@apple.com's avatar
darin@apple.com committed
361
    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
362 363
}

364 365
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
366 367 368
    ASSERT(m_page->dragCaretController()->hasCaret());
    String text = m_page->dragCaretController()->isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
    Node* target = innerFrame->editor()->findEventTargetFrom(m_page->dragCaretController()->caretPosition());
369 370 371 372
    ExceptionCode ec = 0;
    return target->dispatchEvent(TextEvent::createForDrop(innerFrame->domWindow(), text), ec);
}

373
bool DragController::concludeEditDrag(DragData* dragData)
374 375 376
{
    ASSERT(dragData);
    ASSERT(!m_isHandlingDrag);
377

378
    if (!m_documentUnderMouse)
379
        return false;
380

381
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
382
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
383 384
    if (!element)
        return false;
385
    Frame* innerFrame = element->ownerDocument()->frame();
386
    ASSERT(innerFrame);
387

388
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame, dragData))
389 390
        return true;

391 392 393 394
    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
eric@webkit.org's avatar
eric@webkit.org committed
395
        RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
396
        RefPtr<CSSStyleDeclaration> style = m_documentUnderMouse->createCSSStyleDeclaration();
397
        ExceptionCode ec;
398
        style->setProperty("color", color.serialized(), ec);
399 400 401 402 403 404
        if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
            return false;
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
        innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
        return true;
    }
405

406 407 408 409
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }
410

411
    if (HTMLInputElement* fileInput = asFileInput(element)) {
412
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
413
            return false;
414

415 416
        if (!dragData->containsFiles())
            return false;
417

418 419 420 421
        Vector<String> filenames;
        dragData->asFilenames(filenames);
        if (filenames.isEmpty())
            return false;
422

423
        fileInput->receiveDroppedFiles(filenames);
424 425
        return true;
    }
426

427
    VisibleSelection dragCaret = m_page->dragCaretController()->caretPosition();
justing's avatar
justing committed
428
    m_page->dragCaretController()->clear();
eric@webkit.org's avatar
eric@webkit.org committed
429
    RefPtr<Range> range = dragCaret.toNormalizedRange();
430

oliver's avatar
oliver committed
431 432
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
433
    if (!range)
oliver's avatar
oliver committed
434
        return false;
435
    CachedResourceLoader* cachedResourceLoader = range->ownerDocument()->cachedResourceLoader();
436
    ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
437
    if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
438
        bool chosePlainText = false;
439
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame, range, true, chosePlainText);
440
        if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
441
            return false;
442
        }
443

444
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
445
        if (dragIsMove(innerFrame->selection(), dragData)) {
446 447 448
            // 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();
449
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
450
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
451
        } else {
452 453 454 455 456 457 458 459
            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));
            }
460
        }
461
    } else {
462
        String text = dragData->asPlainText(innerFrame);
463
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
464
            return false;
465
        }
466

467
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
468
        if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
469
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
470 471 472 473
    }

    return true;
}
474 475

bool DragController::canProcessDrag(DragData* dragData)
476 477 478 479 480
{
    ASSERT(dragData);

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

482
    IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
483
    HitTestResult result = HitTestResult(point);
eric@webkit.org's avatar
eric@webkit.org committed
484
    if (!m_page->mainFrame()->contentRenderer())
485 486 487
        return false;

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
488 489

    if (!result.innerNonSharedNode())
490
        return false;
491

492 493
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
494

495
    if (!result.innerNonSharedNode()->rendererIsEditable())
496
        return false;
497

498
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
499
        return false;
500

501 502 503
    return true;
}

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
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;
}

523
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
524
{
525
    ASSERT(dragData);
526
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
527 528
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = mainFrame->view();
529
    if (!viewProtector)
530 531
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
532
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
533
    RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
534 535
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
536

537 538
    PlatformMouseEvent event = createMouseEvent(dragData);
    if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
539
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
540 541 542
        return false;
    }

543
    operation = clipboard->destinationOperation();
544 545 546
    if (clipboard->dropEffectIsUninitialized())
        operation = defaultOperationForDrag(srcOpMask);
    else if (!(srcOpMask & operation)) {
547 548
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
549
    }
550 551 552

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

555
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
556
{
557
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
558 559 560

    for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
        Node* node = renderer->node();
561 562 563 564 565 566 567 568 569 570
        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()) {
571
            EUserDrag dragMode = renderer->style()->userDrag();
572 573
            if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
574 575
                return node;
            }
576 577 578 579 580 581 582 583 584 585 586 587 588
            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;
                }
589 590 591
            }
        }
    }
oliver's avatar
 
oliver committed
592

593 594
    // 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
595
}
596

597 598 599 600
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
601
    if (!renderer || !renderer->isImage())
602
        return 0;
603
    RenderImage* image = toRenderImage(renderer);
604 605
    return image->cachedImage();
}
606

607 608 609
static Image* getImage(Element* element)
{
    ASSERT(element);
610 611 612
    CachedImage* cachedImage = getCachedImage(element);
    return (cachedImage && !cachedImage->errorOccurred()) ?
        cachedImage->image() : 0;
613
}
614

615 616 617 618 619
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);
620 621
    ASSERT(!ec);
    src->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
622 623
    clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, src);
}
624

625 626 627
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.
628 629
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
630 631 632 633
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
634

635 636
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
637

638 639
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
640

641 642
static IntPoint dragLocForSelectionDrag(Frame* src)
{
643
    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
644
    int xpos = draggingRect.maxX();
645
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
646
    int ypos = draggingRect.maxY();
647 648 649 650 651 652 653 654
#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);
}
655

656
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
657
{
658
    ASSERT(src);
659

eric@webkit.org's avatar
eric@webkit.org committed
660
    if (!src->view() || !src->contentRenderer())
661
        return false;
662

663 664 665 666 667 668 669 670
    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();
671

672
    IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
673

674
    m_draggingImageURL = KURL();
675
    m_sourceDragOperation = srcOp;
676

677 678 679
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
680

681 682
    Clipboard* clipboard = state.m_dragClipboard.get();
    if (state.m_dragType == DragSourceActionDHTML)
683
        dragImage = clipboard->createDragImage(dragImageOffset);
684 685 686
    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:
687
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
688
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
689

690 691 692 693 694 695
    // 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;
    }
696

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

699
    Node* node = state.m_dragSrc.get();
700

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

731
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
732

733
        if (!dragImage) {
734
            IntRect imageRect = hitTestResult.imageRect();
735
            imageRect.setLocation(m_page->mainFrame()->view()->windowToContents(src->view()->contentsToWindow(imageRect.location())));
736
            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
737
        } else
738 739 740 741
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
742 743 744
        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.
745
            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
746 747 748 749 750 751 752 753

        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)
754
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
755 756
        }

757 758
        m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
        if (!dragImage) {
759
            dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src);
760 761 762
            IntSize size = dragImageSize(dragImage);
            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
            dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
763
        }
764
        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
765
    } else if (state.m_dragType == DragSourceActionDHTML) {
766 767 768 769
        ASSERT(m_dragSourceAction & DragSourceActionDHTML);
        m_client->willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
    } else {
770 771
        // 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.
772 773
        startedDrag = false;
    }
774

775 776 777 778
    if (dragImage)
        deleteDragImage(dragImage);
    return startedDrag;
}
779

780 781 782 783 784
void DragController::doImageDrag(Element* element, const IntPoint& dragOrigin, const IntRect& rect, Clipboard* clipboard, Frame* frame, IntPoint& dragImageOffset)
{
    IntPoint mouseDownPoint = dragOrigin;
    DragImageRef dragImage;
    IntPoint origin;
785

786
    Image* image = getImage(element);
787 788
    if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
        && (dragImage = createDragImageFromImage(image))) {
789 790
        IntSize originalSize = rect.size();
        origin = rect.location();
791

oliver's avatar
oliver committed
792
        dragImage = fitDragImageToMaxSize(dragImage, rect.size(), maxDragImageSize());
793 794
        dragImage = dissolveDragImageToFraction(dragImage, DragImageAlpha);
        IntSize newSize = dragImageSize(dragImage);
795

796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
        // Properly orient the drag image and orient it differently if it's smaller than the original
        float scale = newSize.width() / (float)originalSize.width();
        float dx = origin.x() - mouseDownPoint.x();
        dx *= scale;
        origin.setX((int)(dx + 0.5));
#if PLATFORM(MAC)
        //Compensate for accursed flipped coordinates in cocoa
        origin.setY(origin.y() + originalSize.height());
#endif
        float dy = origin.y() - mouseDownPoint.y();
        dy *= scale;
        origin.setY((int)(dy + 0.5));
    } else {
        dragImage = createDragImageIconForCachedImage(getCachedImage(element));
        if (dragImage)
            origin = IntPoint(DragIconRightInset - dragImageSize(dragImage).width(), DragIconBottomInset);
    }
813

814
    dragImageOffset = mouseDownPoint + origin;
815
    doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
816

817 818
    deleteDragImage(dragImage);
}
819

820 821 822 823 824 825 826
void DragController::doSystemDrag(DragImageRef image, const IntPoint& dragLoc, const IntPoint& eventPos, Clipboard* clipboard, Frame* frame, bool forLink)
{
    m_didInitiateDrag = true;
    m_dragInitiator = frame->document();
    // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
    RefPtr<Frame> frameProtector = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = frameProtector->view();
827 828
    m_client->startDrag(image, viewProtector->windowToContents(frame->view()->contentsToWindow(dragLoc)),
        viewProtector->windowToContents(frame->view()->contentsToWindow(eventPos)), clipboard, frameProtector.get(), forLink);
829

830
    cleanupAfterSystemDrag();
831
}
832

oliver's avatar
oliver committed
833 834 835
// Manual drag caret manipulation
void DragController::placeDragCaret(const IntPoint& windowPoint)
{
836 837
    mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(windowPoint));
    if (!m_documentUnderMouse)
oliver's avatar
oliver committed
838
        return;
839
    Frame* frame = m_documentUnderMouse->frame();
oliver's avatar
oliver committed
840 841 842 843
    FrameView* frameView = frame->view();
    if (!frameView)
        return;
    IntPoint framePoint = frameView->windowToContents(windowPoint);
844 845

    m_page->dragCaretController()->setCaretPosition(frame->visiblePositionForPoint(framePoint));
oliver's avatar
oliver committed
846
}
847

848
} // namespace WebCore
bolsinga@apple.com's avatar
bolsinga@apple.com committed
849 850

#endif // ENABLE(DRAG_SUPPORT)