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

namespace WebCore {

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

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

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

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

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

114
        if (dragData->containsURL(DragData::DoNotConvertFilenames)) {
115
            String title;
116
            String url = dragData->asURL(DragData::DoNotConvertFilenames, &title);
ggaren's avatar
ggaren committed
117
            if (!url.isEmpty()) {
118
                RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(document);
119
                anchor->setHref(url);
120 121 122 123 124 125 126
                if (title.isEmpty()) {
                    // Try the plain text first because the url might be normalized or escaped.
                    if (dragData->containsPlainText())
                        title = dragData->asPlainText();
                    if (title.isEmpty())
                        title = url;
                }
127
                RefPtr<Node> anchorText = document->createTextNode(title);
128
                ExceptionCode ec;
129 130 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;
        return createFragmentFromText(context.get(), dragData->asPlainText()).get();
    }
140

141 142 143
    return 0;
}

144
bool DragController::dragIsMove(SelectionController* selection)
145
{
146
    return m_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && !isCopyKeyDown();
147 148
}

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

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

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

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

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

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

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

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

211
    m_documentUnderMouse = 0;
212

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

    m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
ggaren@apple.com's avatar
ggaren@apple.com committed
217
    m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL()), false);
218 219
    return true;
}
220 221 222 223 224 225 226 227 228 229 230 231

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

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

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

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

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

255 256 257
    // The button for a FILE input is a sub element with no set input type
    // In order to get around this problem we assume any non-FILE input element
    // is this internal button, and try querying the shadow parent node.
258
    if (node->hasTagName(HTMLNames::inputTag) && node->isShadowRoot() && !static_cast<HTMLInputElement*>(node)->isFileUpload())
259
        node = node->shadowHost();
260

261 262
    if (!node || !node->hasTagName(HTMLNames::inputTag))
        return 0;
263

264 265 266
    HTMLInputElement* inputElement = static_cast<HTMLInputElement*>(node);
    if (!inputElement->isFileUpload())
        return 0;
267

268
    return inputElement;
269
}
270

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

291
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragOperation& operation)
292 293
{
    ASSERT(dragData);
294

295
    if (!m_documentUnderMouse)
296
        return false;
297

298 299 300
    if (m_dragInitiator && !m_documentUnderMouse->securityOrigin()->canReceiveDragData(m_dragInitiator->securityOrigin()))
        return false;

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

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

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

328
        IntPoint point = frameView->windowToContents(dragData->clientPosition());
329
        Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
330 331
        if (!element)
            return false;
332
        if (!asFileInput(element)) {
333
            VisibleSelection dragCaret = m_documentUnderMouse->frame()->visiblePositionForPoint(point);
334 335
            m_page->dragCaretController()->setSelection(dragCaret);
        }
336 337

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

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

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

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

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

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

386
    if (!m_documentUnderMouse)
387
        return false;
388

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

396 397 398
    if (!dispatchTextInputEventFor(innerFrame, dragData))
        return true;

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

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

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

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

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

431 432 433 434
        // 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());
435 436
        if (!renderer)
            return false;
437

adele@apple.com's avatar
adele@apple.com committed
438
        renderer->receiveDroppedFiles(filenames);
439 440
        return true;
    }
441

442
    VisibleSelection dragCaret(m_page->dragCaretController()->selection());
justing's avatar
justing committed
443
    m_page->dragCaretController()->clear();
eric@webkit.org's avatar
eric@webkit.org committed
444
    RefPtr<Range> range = dragCaret.toNormalizedRange();
445

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

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

478
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
479
        if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
480
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text), true, false, true));
481
    }
482
    cachedResourceLoader->setAllowStaleResources(false);
483 484 485

    return true;
}
486 487

bool DragController::canProcessDrag(DragData* dragData)
488 489 490 491 492
{
    ASSERT(dragData);

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

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

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
500 501

    if (!result.innerNonSharedNode())
502
        return false;
503

504 505
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
506

507 508
    if (!result.innerNonSharedNode()->isContentEditable())
        return false;
509

510
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
511
        return false;
512

513 514 515
    return true;
}

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

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

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

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

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

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

567
bool DragController::mayStartDragAtEventLocation(const Frame* frame, const IntPoint& framePos, Node* node)
oliver's avatar
 
oliver committed
568 569
{
    ASSERT(frame);
ggaren's avatar
ggaren committed
570
    ASSERT(frame->settings());
oliver's avatar
 
oliver committed
571

eric@webkit.org's avatar
eric@webkit.org committed
572
    if (!frame->view() || !frame->contentRenderer())
oliver's avatar
 
oliver committed
573 574 575 576 577
        return false;

    HitTestResult mouseDownTarget = HitTestResult(framePos);

    mouseDownTarget = frame->eventHandler()->hitTestResultAtPoint(framePos, true);
578 579
    if (node)
        mouseDownTarget.setInnerNonSharedNode(node);
oliver's avatar
 
oliver committed
580

581
    if (mouseDownTarget.image()
oliver's avatar
 
oliver committed
582 583 584 585 586 587 588
        && !mouseDownTarget.absoluteImageURL().isEmpty()
        && frame->settings()->loadsImagesAutomatically()
        && m_dragSourceAction & DragSourceActionImage)
        return true;

    if (!mouseDownTarget.absoluteLinkURL().isEmpty()
        && m_dragSourceAction & DragSourceActionLink
589 590
        && mouseDownTarget.isLiveLink()
        && mouseDownTarget.URLElement()->renderer() && mouseDownTarget.URLElement()->renderer()->style()->userDrag() != DRAG_NONE)
oliver's avatar
 
oliver committed
591 592 593 594 595 596 597 598
        return true;

    if (mouseDownTarget.isSelected()
        && m_dragSourceAction & DragSourceActionSelection)
        return true;

    return false;
}
599

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

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

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

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

638 639
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
640

641 642
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
643

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

659
bool DragController::startDrag(Frame* src, Clipboard* clipboard, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin, bool isDHTMLDrag)
660
{
661 662
    ASSERT(src);
    ASSERT(clipboard);
663

eric@webkit.org's avatar
eric@webkit.org committed
664
    if (!src->view() || !src->contentRenderer())
665
        return false;
666

667 668 669 670 671
    HitTestResult dragSource = HitTestResult(dragOrigin);
    dragSource = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
    KURL linkURL = dragSource.absoluteLinkURL();
    KURL imageURL = dragSource.absoluteImageURL();
    bool isSelected = dragSource.isSelected();
672

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

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

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

    if (isDHTMLDrag)
683
        dragImage = clipboard->createDragImage(dragImageOffset);
684 685 686 687 688 689
    else {
        // This drag operation is not a DHTML drag and may go outside the WebView.
        // We provide a default set of allowed drag operations that follows from:
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
        m_sourceDragOperation = (DragOperation)(DragOperationGeneric | DragOperationCopy);
    }
690

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

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

700
    Node* node = dragSource.innerNonSharedNode();
701

alice.liu@apple.com's avatar
alice.liu@apple.com committed
702 703
    Image* image = getImage(static_cast<Element*>(node));
    if (!imageURL.isEmpty() && node && node->isElementNode() && image
704
            && (m_dragSourceAction & DragSourceActionImage)) {
705
        // 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
706 707
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
708 709
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
710
            m_draggingImageURL = imageURL;
711 712
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, dragSource.altDisplayString());
        }
713

714
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
715

716 717 718 719
        if (!dragImage) {
            IntRect imageRect = dragSource.imageRect();
            imageRect.setLocation(m_page->mainFrame()->view()->windowToContents(src->view()->contentsToWindow(imageRect.location())));
            doImageDrag(element, dragOrigin, dragSource.imageRect(), clipboard, src, m_dragOffset);
720
        } else
721 722 723 724
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
725 726 727 728
        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.
            clipboard->writeURL(linkURL, dragSource.textContent().simplifyWhiteSpace(), src);
729 730 731 732 733 734 735 736

        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)
737
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
738 739
        }

740 741 742 743 744 745
        m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
        if (!dragImage) {
            dragImage = m_client->createDragImageForLink(linkURL, dragSource.textContent(), src);
            IntSize size = dragImageSize(dragImage);
            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
            dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
746
        }
747
        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
748
    } else if (isSelected && (m_dragSourceAction & DragSourceActionSelection)) {
749 750
        if (!clipboard->hasData()) {
            if (isNodeInTextFormControl(src->selection()->start().node()))
751
                clipboard->writePlainText(src->editor()->selectedText());
752 753 754 755 756 757 758
            else {
                RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
                ASSERT(selectionRange);

                clipboard->writeRange(selectionRange.get(), src);
            }
        }
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
        m_client->willPerformDragSourceAction(DragSourceActionSelection, dragOrigin, clipboard);
        if (!dragImage) {
            dragImage = createDragImageForSelection(src);
            dragLoc = dragLocForSelectionDrag(src);
            m_dragOffset = IntPoint((int)(dragOrigin.x() - dragLoc.x()), (int)(dragOrigin.y() - dragLoc.y()));
        }
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
    } else if (isDHTMLDrag) {
        ASSERT(m_dragSourceAction & DragSourceActionDHTML);
        m_client->willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
    } else {
        // Only way I know to get here is if to get here is if the original element clicked on in the mousedown is no longer
        // under the mousedown point, so linkURL, imageURL and isSelected are all false/empty.
        startedDrag = false;
    }
775

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

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

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

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

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
        // 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);
    }
814

815 816 817
    dragImageOffset.setX(mouseDownPoint.x() + origin.x());
    dragImageOffset.setY(mouseDownPoint.y() + origin.y());
    doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
818

819 820
    deleteDragImage(dragImage);
}
821

822 823 824 825 826 827 828
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();
829 830
    m_client->startDrag(image, viewProtector->windowToContents(frame->view()->contentsToWindow(dragLoc)),
        viewProtector->windowToContents(frame->view()->contentsToWindow(eventPos)), clipboard, frameProtector.get(), forLink);
831

832
    cleanupAfterSystemDrag();
833
}
834

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

850
} // namespace WebCore
bolsinga@apple.com's avatar
bolsinga@apple.com committed
851 852

#endif // ENABLE(DRAG_SUPPORT)