DragController.cpp 36 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
#include "DragSession.h"
40 41 42 43
#include "Editor.h"
#include "EditorClient.h"
#include "Element.h"
#include "EventHandler.h"
44
#include "FloatRect.h"
45 46
#include "Frame.h"
#include "FrameLoader.h"
47
#include "FrameSelection.h"
48 49
#include "FrameView.h"
#include "HTMLAnchorElement.h"
50 51
#include "HTMLInputElement.h"
#include "HTMLNames.h"
52
#include "HitTestRequest.h"
darin's avatar
darin committed
53
#include "HitTestResult.h"
54
#include "Image.h"
55 56 57
#include "MoveSelectionCommand.h"
#include "Node.h"
#include "Page.h"
58
#include "PlatformKeyboardEvent.h"
59
#include "RenderFileUploadControl.h"
60
#include "RenderImage.h"
61
#include "RenderLayer.h"
62
#include "RenderView.h"
63 64
#include "ReplaceSelectionCommand.h"
#include "ResourceRequest.h"
65
#include "SecurityOrigin.h"
oliver's avatar
 
oliver committed
66
#include "Settings.h"
67
#include "Text.h"
68
#include "TextEvent.h"
69
#include "htmlediting.h"
darin's avatar
darin committed
70
#include "markup.h"
ap@webkit.org's avatar
ap@webkit.org committed
71
#include <wtf/CurrentTime.h>
72
#include <wtf/RefPtr.h>
73 74 75 76 77

namespace WebCore {

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

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

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

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

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

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

143 144 145
    return 0;
}

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

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

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

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

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

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

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

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

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

215
    m_documentUnderMouse = 0;
216

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

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

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

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

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

248 249
    DragSession dragSession;
    bool handledByDocument = tryDocumentDrag(dragData, m_dragDestinationAction, dragSession);
250
    if (!handledByDocument && (m_dragDestinationAction & DragDestinationActionLoad))
251 252
        dragSession.operation = operationForLoad(dragData);
    return dragSession;
253
}
254 255 256 257

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

259
    HTMLInputElement* inputElement = node->toInputElement();
260

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

265
    return inputElement && inputElement->isFileUpload() ? inputElement : 0;
266
}
267

268
// This can return null if an empty document is loaded.
269 270
static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint& p)
{
271 272
    Frame* frame = documentUnderMouse->frame();
    float zoomFactor = frame ? frame->pageZoomFactor() : 1;
273
    LayoutPoint point = roundedLayoutPoint(FloatPoint(p.x() * zoomFactor, p.y() * zoomFactor));
274 275 276 277 278 279 280 281 282 283 284 285 286 287

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

288
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragSession& dragSession)
289 290
{
    ASSERT(dragData);
291

292
    if (!m_documentUnderMouse)
293
        return false;
294

295 296 297
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

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

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

    if (m_isHandlingDrag) {
        m_page->dragCaretController()->clear();
        return true;
319
    } else if ((actionMask & DragDestinationActionEdit) && canProcessDrag(dragData)) {
320
        if (dragData->containsColor()) {
321
            dragSession.operation = DragOperationGeneric;
322 323
            return true;
        }
324

325
        IntPoint point = frameView->windowToContents(dragData->clientPosition());
326
        Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
327 328
        if (!element)
            return false;
329 330 331
        
        HTMLInputElement* elementAsFileInput = asFileInput(element);
        if (!elementAsFileInput)
332
            m_page->dragCaretController()->setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
333 334

        Frame* innerFrame = element->document()->frame();
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        dragSession.operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
        dragSession.mouseIsOverFileInput = elementAsFileInput;
        dragSession.numberOfItemsToBeAccepted = 0;

        unsigned numberOfFiles = dragData->numberOfFiles();
        if (elementAsFileInput) {
            if (elementAsFileInput->disabled())
                dragSession.numberOfItemsToBeAccepted = 0;
            else if (elementAsFileInput->multiple())
                dragSession.numberOfItemsToBeAccepted = numberOfFiles;
            else
                dragSession.numberOfItemsToBeAccepted = 1;
            
            if (!dragSession.numberOfItemsToBeAccepted)
                dragSession.operation = DragOperationNone;
        } else {
            // We are not over a file input element. The dragged item(s) will only
            // be loaded into the view the number of dragged items is 1.
            dragSession.numberOfItemsToBeAccepted = numberOfFiles != 1 ? 0 : 1;
        }
        
356 357
        return true;
    }
358 359
    // If we're not over an editable region, make sure we're clearing any prior drag cursor.
    m_page->dragCaretController()->clear();
360
    return false;
361
}
362 363

DragSourceAction DragController::delegateDragSourceAction(const IntPoint& windowPoint)
364
{
365 366 367
    m_dragSourceAction = m_client->dragSourceActionMaskForPoint(windowPoint);
    return m_dragSourceAction;
}
368

369 370 371
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
372
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
373
    if (doc && (m_didInitiateDrag || doc->isPluginDocument() || doc->rendererIsEditable()))
374 375 376 377
        return DragOperationNone;
    return dragOperation(dragData);
}

378
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
379
{
darin@apple.com's avatar
darin@apple.com committed
380 381
    frame->selection()->setSelection(dragCaret);
    if (frame->selection()->isNone()) {
oliver's avatar
oliver committed
382
        dragCaret = frame->visiblePositionForPoint(point);
darin@apple.com's avatar
darin@apple.com committed
383
        frame->selection()->setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
384
        range = dragCaret.toNormalizedRange();
385
    }
darin@apple.com's avatar
darin@apple.com committed
386
    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
387 388
}

389 390
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
391 392 393
    ASSERT(m_page->dragCaretController()->hasCaret());
    String text = m_page->dragCaretController()->isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
    Node* target = innerFrame->editor()->findEventTargetFrom(m_page->dragCaretController()->caretPosition());
394 395 396 397
    ExceptionCode ec = 0;
    return target->dispatchEvent(TextEvent::createForDrop(innerFrame->domWindow(), text), ec);
}

398
bool DragController::concludeEditDrag(DragData* dragData)
399 400 401
{
    ASSERT(dragData);
    ASSERT(!m_isHandlingDrag);
402

403
    if (!m_documentUnderMouse)
404
        return false;
405

406
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
407
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
408 409
    if (!element)
        return false;
410
    Frame* innerFrame = element->ownerDocument()->frame();
411
    ASSERT(innerFrame);
412

413
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame, dragData))
414 415
        return true;

416 417 418 419
    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
eric@webkit.org's avatar
eric@webkit.org committed
420
        RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
421
        RefPtr<CSSStyleDeclaration> style = m_documentUnderMouse->createCSSStyleDeclaration();
422
        ExceptionCode ec;
423
        style->setProperty("color", color.serialized(), ec);
424 425 426 427 428 429
        if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
            return false;
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
        innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
        return true;
    }
430

431 432 433 434
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }
435

436
    if (HTMLInputElement* fileInput = asFileInput(element)) {
437
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
438
            return false;
439

440 441
        if (!dragData->containsFiles())
            return false;
442

443 444 445 446
        Vector<String> filenames;
        dragData->asFilenames(filenames);
        if (filenames.isEmpty())
            return false;
447

448
        fileInput->receiveDroppedFiles(filenames);
449 450
        return true;
    }
451

452
    VisibleSelection dragCaret = m_page->dragCaretController()->caretPosition();
justing's avatar
justing committed
453
    m_page->dragCaretController()->clear();
eric@webkit.org's avatar
eric@webkit.org committed
454
    RefPtr<Range> range = dragCaret.toNormalizedRange();
455

oliver's avatar
oliver committed
456 457
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
458
    if (!range)
oliver's avatar
oliver committed
459
        return false;
460
    CachedResourceLoader* cachedResourceLoader = range->ownerDocument()->cachedResourceLoader();
461
    ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
462
    if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
463
        bool chosePlainText = false;
464
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame, range, true, chosePlainText);
465
        if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
466
            return false;
467
        }
468

469
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
470
        if (dragIsMove(innerFrame->selection(), dragData)) {
471 472 473
            // 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();
474
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
475
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
476
        } else {
477 478 479 480 481 482 483 484
            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));
            }
485
        }
486
    } else {
487
        String text = dragData->asPlainText(innerFrame);
488
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
489
            return false;
490
        }
491

492
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
493
        if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
494
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
495 496 497 498
    }

    return true;
}
499 500

bool DragController::canProcessDrag(DragData* dragData)
501 502 503 504 505
{
    ASSERT(dragData);

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

507
    IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
508
    HitTestResult result = HitTestResult(point);
eric@webkit.org's avatar
eric@webkit.org committed
509
    if (!m_page->mainFrame()->contentRenderer())
510 511 512
        return false;

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
513 514

    if (!result.innerNonSharedNode())
515
        return false;
516

517 518
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
519

520
    if (!result.innerNonSharedNode()->rendererIsEditable())
521
        return false;
522

523
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
524
        return false;
525

526 527 528
    return true;
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
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;
}

548
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
549
{
550
    ASSERT(dragData);
551
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
552 553
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = mainFrame->view();
554
    if (!viewProtector)
555 556
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
557
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
558
    RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
559 560
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
561

562 563
    PlatformMouseEvent event = createMouseEvent(dragData);
    if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
564
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
565 566 567
        return false;
    }

568
    operation = clipboard->destinationOperation();
569 570 571
    if (clipboard->dropEffectIsUninitialized())
        operation = defaultOperationForDrag(srcOpMask);
    else if (!(srcOpMask & operation)) {
572 573
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
574
    }
575 576 577

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

580
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
581
{
582
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
583 584 585

    for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
        Node* node = renderer->node();
586 587 588 589 590 591 592 593 594 595
        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()) {
596
            EUserDrag dragMode = renderer->style()->userDrag();
597 598
            if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
599 600
                return node;
            }
601 602 603 604 605 606 607 608 609 610 611 612 613
            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;
                }
614 615 616
            }
        }
    }
oliver's avatar
 
oliver committed
617

618 619
    // 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
620
}
621

622 623 624 625
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
626
    if (!renderer || !renderer->isImage())
627
        return 0;
628
    RenderImage* image = toRenderImage(renderer);
629 630
    return image->cachedImage();
}
631

632 633 634
static Image* getImage(Element* element)
{
    ASSERT(element);
635 636
    CachedImage* cachedImage = getCachedImage(element);
    return (cachedImage && !cachedImage->errorOccurred()) ?
637
        cachedImage->imageForRenderer(element->renderer()) : 0;
638
}
639

640
static void prepareClipboardForImageDrag(Frame* source, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
641
{
642 643 644 645 646 647 648 649
    if (node->isContentRichlyEditable()) {
        RefPtr<Range> range = source->document()->createRange();
        ExceptionCode ec = 0;
        range->selectNode(node, ec);
        ASSERT(!ec);
        source->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
    }
    clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, source);
650
}
651

652 653 654
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.
655 656
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
657 658 659 660
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
661

662 663
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
664

665 666
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
667

668 669
static IntPoint dragLocForSelectionDrag(Frame* src)
{
670
    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
671
    int xpos = draggingRect.maxX();
672
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
673
    int ypos = draggingRect.maxY();
674 675 676 677 678 679 680 681
#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);
}
682

683
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
684
{
685
    ASSERT(src);
686

eric@webkit.org's avatar
eric@webkit.org committed
687
    if (!src->view() || !src->contentRenderer())
688
        return false;
689

690 691 692 693 694 695 696 697
    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();
698

699
    IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
700

701
    m_draggingImageURL = KURL();
702
    m_sourceDragOperation = srcOp;
703

704 705 706
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
707

708 709
    Clipboard* clipboard = state.m_dragClipboard.get();
    if (state.m_dragType == DragSourceActionDHTML)
710
        dragImage = clipboard->createDragImage(dragImageOffset);
711 712 713
    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:
714
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
715
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
716

717 718 719 720 721 722
    // 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;
    }
723

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

726
    Node* node = state.m_dragSrc.get();
727

alice.liu@apple.com's avatar
alice.liu@apple.com committed
728
    Image* image = getImage(static_cast<Element*>(node));
729 730
    if (state.m_dragType == DragSourceActionSelection) {
        if (!clipboard->hasData()) {
731
            if (enclosingTextFormControl(src->selection()->start()))
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
                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);
747
    } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
748
               && (m_dragSourceAction & DragSourceActionImage)) {
749
        // 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
750 751
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
752 753
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
754
            m_draggingImageURL = imageURL;
755
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
756
        }
757

758
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
759

760
        if (!dragImage) {
761
            IntRect imageRect = hitTestResult.imageRect();
762
            imageRect.setLocation(m_page->mainFrame()->view()->windowToContents(src->view()->contentsToWindow(imageRect.location())));
763
            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
764
        } else
765 766 767 768
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
769 770 771
        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.
772
            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
773 774 775 776 777 778 779 780

        if (src->selection()->isCaret() && src->selection()->isContentEditable()) {