DragController.cpp 35.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)
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 424 425 426
        // Ugly. For security none of the APIs available to us can set the input value
        // on file inputs. Even forcing a change in HTMLInputElement doesn't work as
        // RenderFileUploadControl clears the file when doing updateFromElement().
        RenderFileUploadControl* renderer = toRenderFileUploadControl(fileInput->renderer());
427 428
        if (!renderer)
            return false;
429

adele@apple.com's avatar
adele@apple.com committed
430
        renderer->receiveDroppedFiles(filenames);
431 432
        return true;
    }
433

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

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

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

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

    return true;
}
481 482

bool DragController::canProcessDrag(DragData* dragData)
483 484 485 486 487
{
    ASSERT(dragData);

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

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

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
495 496

    if (!result.innerNonSharedNode())
497
        return false;
498

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

502
    if (!result.innerNonSharedNode()->rendererIsEditable())
503
        return false;
504

505
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
506
        return false;
507

508 509 510
    return true;
}

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

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

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

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

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

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

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

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

600 601
    // 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
602
}
603

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

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

622 623 624 625 626
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);
627 628
    ASSERT(!ec);
    src->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
629 630
    clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, src);
}
631

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

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

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

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

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

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

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

679
    IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
680

681
    m_draggingImageURL = KURL();
682
    m_sourceDragOperation = srcOp;
683

684 685 686
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
687

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

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

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

706
    Node* node = state.m_dragSrc.get();
707

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

738
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
739

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

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

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

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

782 783 784 785
    if (dragImage)
        deleteDragImage(dragImage);
    return startedDrag;
}
786

787 788 789 790 791
void DragController::doImageDrag(Element* element, const IntPoint& dragOrigin, const IntRect& rect, Clipboard* clipboard, Frame* frame, IntPoint& dragImageOffset)
{
    IntPoint mouseDownPoint = dragOrigin;
    DragImageRef dragImage;
    IntPoint origin;
792

793
    Image* image = getImage(element);
794 795
    if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
        && (dragImage = createDragImageFromImage(image))) {
796 797
        IntSize originalSize = rect.size();
        origin = rect.location();
798

oliver's avatar
oliver committed
799
        dragImage = fitDragImageToMaxSize(dragImage, rect.size(), maxDragImageSize());
800 801
        dragImage = dissolveDragImageToFraction(dragImage, DragImageAlpha);
        IntSize newSize = dragImageSize(dragImage);
802

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
        // 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);
    }
820

821
    dragImageOffset = mouseDownPoint + origin;
822
    doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
823

824 825
    deleteDragImage(dragImage);
}
826

827 828 829 830 831 832 833
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();
834 835
    m_client->startDrag(image, viewProtector->windowToContents(frame->view()->contentsToWindow(dragLoc)),
        viewProtector->windowToContents(frame->view()->contentsToWindow(eventPos)), clipboard, frameProtector.get(), forLink);
836

837
    cleanupAfterSystemDrag();
838
}
839

oliver's avatar
oliver committed
840 841 842
// Manual drag caret manipulation
void DragController::placeDragCaret(const IntPoint& windowPoint)
{
843 844
    mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(windowPoint));
    if (!m_documentUnderMouse)
oliver's avatar
oliver committed
845
        return;
846
    Frame* frame = m_documentUnderMouse->frame();
oliver's avatar
oliver committed
847 848 849 850
    FrameView* frameView = frame->view();
    if (!frameView)
        return;
    IntPoint framePoint = frameView->windowToContents(windowPoint);
851 852

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

855
} // namespace WebCore
bolsinga@apple.com's avatar
bolsinga@apple.com committed
856 857

#endif // ENABLE(DRAG_SUPPORT)