DragController.cpp 30.4 KB
Newer Older
1
/*
2
 * Copyright (C) 2007, 2009 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"

darin's avatar
darin committed
29
#include "CSSStyleDeclaration.h"
30 31
#include "Clipboard.h"
#include "ClipboardAccessPolicy.h"
darin's avatar
darin committed
32
#include "DocLoader.h"
33 34 35
#include "Document.h"
#include "DocumentFragment.h"
#include "DragActions.h"
darin's avatar
darin committed
36 37
#include "DragClient.h"
#include "DragData.h"
38 39 40 41
#include "Editor.h"
#include "EditorClient.h"
#include "Element.h"
#include "EventHandler.h"
42
#include "FloatRect.h"
43 44 45 46
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameView.h"
#include "HTMLAnchorElement.h"
47 48
#include "HTMLInputElement.h"
#include "HTMLNames.h"
darin's avatar
darin committed
49
#include "HitTestResult.h"
50
#include "Image.h"
51 52 53
#include "MoveSelectionCommand.h"
#include "Node.h"
#include "Page.h"
54
#include "RenderFileUploadControl.h"
55
#include "RenderImage.h"
56 57 58
#include "ReplaceSelectionCommand.h"
#include "ResourceRequest.h"
#include "SelectionController.h"
oliver's avatar
 
oliver committed
59
#include "Settings.h"
60
#include "Text.h"
61
#include "htmlediting.h"
darin's avatar
darin committed
62
#include "markup.h"
ap@webkit.org's avatar
ap@webkit.org committed
63
#include <wtf/CurrentTime.h>
64
#include <wtf/RefPtr.h>
65 66 67 68 69 70 71

namespace WebCore {

static PlatformMouseEvent createMouseEvent(DragData* dragData)
{
    // FIXME: We should fake modifier keys here.
    return PlatformMouseEvent(dragData->clientPosition(), dragData->globalPosition(),
oliver's avatar
 
oliver committed
72
                              LeftButton, MouseEventMoved, 0, false, false, false, false, currentTime());
73 74

}
75

76 77 78
DragController::DragController(Page* page, DragClient* client)
    : m_page(page)
    , m_client(client)
79
    , m_documentUnderMouse(0)
80 81 82 83
    , m_dragInitiator(0)
    , m_dragDestinationAction(DragDestinationActionNone)
    , m_dragSourceAction(DragSourceActionNone)
    , m_didInitiateDrag(false)
84
    , m_isHandlingDrag(false)
85
    , m_sourceDragOperation(DragOperationNone)
86 87
{
}
88

89
DragController::~DragController()
90
{
91 92
    m_client->dragControllerDestroyed();
}
93

94
static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, RefPtr<Range> context,
oliver's avatar
oliver committed
95
                                          bool allowPlainText, bool& chosePlainText)
96 97 98 99
{
    ASSERT(dragData);
    chosePlainText = false;

100
    Document* document = context->ownerDocument();
101 102
    ASSERT(document);
    if (document && dragData->containsCompatibleContent()) {
103
        if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(document))
104 105 106 107 108
            return fragment;

        if (dragData->containsURL()) {
            String title;
            String url = dragData->asURL(&title);
ggaren's avatar
ggaren committed
109
            if (!url.isEmpty()) {
110
                RefPtr<HTMLAnchorElement> anchor = new HTMLAnchorElement(document);
111
                anchor->setHref(url);
112
                ExceptionCode ec;
113 114 115 116 117 118 119 120 121 122 123 124
                RefPtr<Node> anchorText = document->createTextNode(title);
                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();
    }
125

126 127 128
    return 0;
}

129
bool DragController::dragIsMove(SelectionController* selection)
130
{
131
    return m_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && !isCopyKeyDown();
132 133
}

134
// FIXME: This method is poorly named.  We're just clearing the selection from the document this drag is exiting.
135 136 137 138 139
void DragController::cancelDrag()
{
    m_page->dragCaretController()->clear();
}

oliver's avatar
oliver committed
140 141 142
void DragController::dragEnded()
{
    m_dragInitiator = 0;
143 144 145
    m_didInitiateDrag = false;
    m_page->dragCaretController()->clear();
}
146

147
DragOperation DragController::dragEntered(DragData* dragData)
148 149 150
{
    return dragEnteredOrUpdated(dragData);
}
151 152 153

void DragController::dragExited(DragData* dragData)
{
154 155
    ASSERT(dragData);
    Frame* mainFrame = m_page->mainFrame();
156

157
    if (RefPtr<FrameView> v = mainFrame->view()) {
158
        ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
159 160 161 162 163
        RefPtr<Clipboard> clipboard = dragData->createClipboard(policy);
        clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
        mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
    }
164
    mouseMovedIntoDocument(0);
165
}
ggaren@apple.com's avatar
ggaren@apple.com committed
166

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

172
bool DragController::performDrag(DragData* dragData)
173
{
174
    ASSERT(dragData);
175
    m_documentUnderMouse = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
176 177 178
    if (m_isHandlingDrag) {
        ASSERT(m_dragDestinationAction & DragDestinationActionDHTML);
        m_client->willPerformDragDestinationAction(DragDestinationActionDHTML, dragData);
179
        RefPtr<Frame> mainFrame = m_page->mainFrame();
180 181 182 183 184 185 186
        if (mainFrame->view()) {
            // Sending an event can result in the destruction of the view and part.
            RefPtr<Clipboard> clipboard = dragData->createClipboard(ClipboardReadable);
            clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
            mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
            clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
        }
187
        m_documentUnderMouse = 0;
188
        return true;
189 190
    }

191
    if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
192
        m_documentUnderMouse = 0;
193 194
        return true;
    }
195

196
    m_documentUnderMouse = 0;
197

198
    if (operationForLoad(dragData) == DragOperationNone)
199
        return false;
200 201

    m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
ggaren@apple.com's avatar
ggaren@apple.com committed
202
    m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL()), false);
203 204
    return true;
}
205 206 207 208 209 210 211 212 213 214 215 216

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

217 218 219
DragOperation DragController::dragEnteredOrUpdated(DragData* dragData)
{
    ASSERT(dragData);
220 221 222
    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()));

223
    m_dragDestinationAction = m_client->actionMaskForDrag(dragData);
224
    if (m_dragDestinationAction == DragDestinationActionNone) {
225
        cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
226
        return DragOperationNone;
227
    }
228 229 230 231 232

    DragOperation operation = DragOperationNone;
    bool handledByDocument = tryDocumentDrag(dragData, m_dragDestinationAction, operation);
    if (!handledByDocument && (m_dragDestinationAction & DragDestinationActionLoad))
        return operationForLoad(dragData);
233 234
    return operation;
}
235 236 237 238

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

240 241 242 243 244
    // 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.
    if (node->hasTagName(HTMLNames::inputTag) && node->isShadowNode() && static_cast<HTMLInputElement*>(node)->inputType() != HTMLInputElement::FILE)
      node = node->shadowParentNode();
245

246 247
    if (!node || !node->hasTagName(HTMLNames::inputTag))
        return 0;
248

249 250 251
    HTMLInputElement* inputElem = static_cast<HTMLInputElement*>(node);
    if (inputElem->inputType() == HTMLInputElement::FILE)
        return inputElem;
252

253 254
    return 0;
}
255

256
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragOperation& operation)
257 258
{
    ASSERT(dragData);
259

260
    if (!m_documentUnderMouse)
261
        return false;
262

263
    m_isHandlingDrag = false;
264
    if (actionMask & DragDestinationActionDHTML) {
265
        m_isHandlingDrag = tryDHTMLDrag(dragData, operation);
266 267 268 269 270 271
        // 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)
272
            return false;
273
    }
274

275 276
    // It's unclear why this check is after tryDHTMLDrag.
    // We send drag events in tryDHTMLDrag and that may be the reason.
277
    RefPtr<FrameView> frameView = m_documentUnderMouse->view();
278
    if (!frameView)
279 280 281 282 283 284 285
        return false;

    if (m_isHandlingDrag) {
        m_page->dragCaretController()->clear();
        return true;
    }

286
    if ((actionMask & DragDestinationActionEdit) && !m_isHandlingDrag && canProcessDrag(dragData)) {
287 288 289 290
        if (dragData->containsColor()) {
            operation = DragOperationGeneric;
            return true;
        }
291

292 293
        IntPoint dragPos = dragData->clientPosition();
        IntPoint point = frameView->windowToContents(dragPos);
294
        Element* element = m_documentUnderMouse->elementFromPoint(point.x(), point.y());
295
        ASSERT(element);
296
        if (!asFileInput(element)) {
297
            VisibleSelection dragCaret = m_documentUnderMouse->frame()->visiblePositionForPoint(point);
298 299
            m_page->dragCaretController()->setSelection(dragCaret);
        }
300 301

        Frame* innerFrame = element->document()->frame();
302 303 304 305
        operation = dragIsMove(innerFrame->selection()) ? DragOperationMove : DragOperationCopy;
        return true;
    }
    return false;
306
}
307 308

DragSourceAction DragController::delegateDragSourceAction(const IntPoint& windowPoint)
309
{
310 311 312
    m_dragSourceAction = m_client->dragSourceActionMaskForPoint(windowPoint);
    return m_dragSourceAction;
}
313

314 315 316
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
317
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
318
    if (doc && (m_didInitiateDrag || doc->isPluginDocument() || (doc->frame() && doc->frame()->editor()->clientIsEditable())))
319 320 321 322
        return DragOperationNone;
    return dragOperation(dragData);
}

323
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
324
{
darin@apple.com's avatar
darin@apple.com committed
325 326
    frame->selection()->setSelection(dragCaret);
    if (frame->selection()->isNone()) {
oliver's avatar
oliver committed
327
        dragCaret = frame->visiblePositionForPoint(point);
darin@apple.com's avatar
darin@apple.com committed
328
        frame->selection()->setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
329
        range = dragCaret.toNormalizedRange();
330
    }
darin@apple.com's avatar
darin@apple.com committed
331
    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
332 333
}

334
bool DragController::concludeEditDrag(DragData* dragData)
335 336 337
{
    ASSERT(dragData);
    ASSERT(!m_isHandlingDrag);
338

339
    if (!m_documentUnderMouse)
340
        return false;
341

342 343
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
    Element* element =  m_documentUnderMouse->elementFromPoint(point.x(), point.y());
344 345
    ASSERT(element);
    Frame* innerFrame = element->ownerDocument()->frame();
346
    ASSERT(innerFrame);
347 348 349 350 351 352 353

    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
        if (!innerFrame)
            return false;
eric@webkit.org's avatar
eric@webkit.org committed
354
        RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
355
        RefPtr<CSSStyleDeclaration> style = m_documentUnderMouse->createCSSStyleDeclaration();
356 357 358 359 360 361 362 363
        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;
    }
364

365 366 367 368
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }
369

370
    if (HTMLInputElement* fileInput = asFileInput(element)) {
371
        if (!fileInput->isEnabledFormControl())
adele@apple.com's avatar
adele@apple.com committed
372
            return false;
373

374 375
        if (!dragData->containsFiles())
            return false;
376

377 378 379 380
        Vector<String> filenames;
        dragData->asFilenames(filenames);
        if (filenames.isEmpty())
            return false;
381 382

        // Ugly.  For security none of the API's available to us to set the input value
383 384 385
        // on file inputs.  Even forcing a change in HTMLInputElement doesn't work as
        // RenderFileUploadControl clears the file when doing updateFromElement()
        RenderFileUploadControl* renderer = static_cast<RenderFileUploadControl*>(fileInput->renderer());
386

387 388
        if (!renderer)
            return false;
389

adele@apple.com's avatar
adele@apple.com committed
390
        renderer->receiveDroppedFiles(filenames);
391 392
        return true;
    }
393

394
    VisibleSelection dragCaret(m_page->dragCaretController()->selection());
justing's avatar
justing committed
395
    m_page->dragCaretController()->clear();
eric@webkit.org's avatar
eric@webkit.org committed
396
    RefPtr<Range> range = dragCaret.toNormalizedRange();
397

oliver's avatar
oliver committed
398 399
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
400
    if (!range)
oliver's avatar
oliver committed
401
        return false;
402
    DocLoader* loader = range->ownerDocument()->docLoader();
403
    loader->setAllowStaleResources(true);
404
    if (dragIsMove(innerFrame->selection()) || dragCaret.isContentRichlyEditable()) {
405 406
        bool chosePlainText = false;
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, range, true, chosePlainText);
407
        if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
408
            loader->setAllowStaleResources(false);
409
            return false;
410
        }
411

412
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
413
        if (dragIsMove(innerFrame->selection())) {
414 415
            bool smartMove = innerFrame->selectionGranularity() == WordGranularity
                          && innerFrame->editor()->smartInsertDeleteEnabled()
416
                          && dragData->canSmartReplace();
darin@apple.com's avatar
darin@apple.com committed
417
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartMove));
418
        } else {
419
            if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
420 421
                applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse, fragment, true, dragData->canSmartReplace(), chosePlainText));
        }
422 423
    } else {
        String text = dragData->asPlainText();
424
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
425
            loader->setAllowStaleResources(false);
426
            return false;
427
        }
428

429
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
430
        if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
431
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse, createFragmentFromText(range.get(), text), true, false, true));
432
    }
433
    loader->setAllowStaleResources(false);
434 435 436

    return true;
}
437 438

bool DragController::canProcessDrag(DragData* dragData)
439 440 441 442 443
{
    ASSERT(dragData);

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

445
    IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
446
    HitTestResult result = HitTestResult(point);
eric@webkit.org's avatar
eric@webkit.org committed
447
    if (!m_page->mainFrame()->contentRenderer())
448 449 450
        return false;

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
451 452

    if (!result.innerNonSharedNode())
453
        return false;
454

455 456
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
457

458 459
    if (!result.innerNonSharedNode()->isContentEditable())
        return false;
460

461
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
462
        return false;
463

464 465 466
    return true;
}

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
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 & DragOperationCopy)
         return DragOperationCopy;
    if (srcOpMask & DragOperationMove || srcOpMask & DragOperationGeneric)
        return DragOperationMove;
    if (srcOpMask & DragOperationLink)
        return DragOperationLink;

    // FIXME: Does IE really return "generic" even if no operations were allowed by the source?
    return DragOperationGeneric;
}

bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
483
{
484
    ASSERT(dragData);
485
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
486 487
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = mainFrame->view();
488
    if (!viewProtector)
489 490
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
491
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
492
    RefPtr<Clipboard> clipboard = dragData->createClipboard(policy);
493 494
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
495

496 497
    PlatformMouseEvent event = createMouseEvent(dragData);
    if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
498
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
499 500 501 502 503 504 505 506 507
        return false;
    }

    if (!clipboard->destinationOperation(operation)) {
        // The element accepted but they didn't pick an operation, so we pick one (to match IE).
        operation = defaultOperationForDrag(srcOpMask);
    } else if (!(srcOpMask & operation)) {
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
508
    }
509 510 511

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

oliver's avatar
 
oliver committed
514 515 516
bool DragController::mayStartDragAtEventLocation(const Frame* frame, const IntPoint& framePos)
{
    ASSERT(frame);
ggaren's avatar
ggaren committed
517
    ASSERT(frame->settings());
oliver's avatar
 
oliver committed
518

eric@webkit.org's avatar
eric@webkit.org committed
519
    if (!frame->view() || !frame->contentRenderer())
oliver's avatar
 
oliver committed
520 521 522 523 524 525
        return false;

    HitTestResult mouseDownTarget = HitTestResult(framePos);

    mouseDownTarget = frame->eventHandler()->hitTestResultAtPoint(framePos, true);

526
    if (mouseDownTarget.image()
oliver's avatar
 
oliver committed
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
        && !mouseDownTarget.absoluteImageURL().isEmpty()
        && frame->settings()->loadsImagesAutomatically()
        && m_dragSourceAction & DragSourceActionImage)
        return true;

    if (!mouseDownTarget.absoluteLinkURL().isEmpty()
        && m_dragSourceAction & DragSourceActionLink
        && mouseDownTarget.isLiveLink())
        return true;

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

    return false;

}
544

545 546 547 548
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
549
    if (!renderer || !renderer->isImage())
550
        return 0;
551
    RenderImage* image = toRenderImage(renderer);
552 553
    return image->cachedImage();
}
554

555 556 557 558
static Image* getImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
559
    if (!renderer || !renderer->isImage())
560
        return 0;
561

562
    RenderImage* image = toRenderImage(renderer);
kmccullo's avatar
kmccullo committed
563
    if (image->cachedImage() && !image->cachedImage()->errorOccurred())
564 565 566
        return image->cachedImage()->image();
    return 0;
}
567

568 569 570 571 572
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);
573 574
    ASSERT(!ec);
    src->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
575 576
    clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, src);
}
577

578 579 580
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.
581 582
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
583 584 585 586
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
587

588 589
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
590

591 592
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
593

594 595
static IntPoint dragLocForSelectionDrag(Frame* src)
{
596
    IntRect draggingRect = enclosingIntRect(src->selectionBounds());
597 598 599 600 601 602 603 604 605 606 607
    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);
}
608

609
bool DragController::startDrag(Frame* src, Clipboard* clipboard, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin, bool isDHTMLDrag)
610
{
611 612
    ASSERT(src);
    ASSERT(clipboard);
613

eric@webkit.org's avatar
eric@webkit.org committed
614
    if (!src->view() || !src->contentRenderer())
615
        return false;
616

617 618 619 620 621
    HitTestResult dragSource = HitTestResult(dragOrigin);
    dragSource = src->eventHandler()->hitTestResultAtPoint(dragOrigin, true);
    KURL linkURL = dragSource.absoluteLinkURL();
    KURL imageURL = dragSource.absoluteImageURL();
    bool isSelected = dragSource.isSelected();
622

623
    IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
624

625
    m_draggingImageURL = KURL();
626
    m_sourceDragOperation = srcOp;
627

628 629 630
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
631 632

    if (isDHTMLDrag)
633
        dragImage = clipboard->createDragImage(dragImageOffset);
634

635 636 637 638 639 640
    // 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;
    }
641

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

644
    Node* node = dragSource.innerNonSharedNode();
645

alice.liu@apple.com's avatar
alice.liu@apple.com committed
646 647
    Image* image = getImage(static_cast<Element*>(node));
    if (!imageURL.isEmpty() && node && node->isElementNode() && image
648
            && (m_dragSourceAction & DragSourceActionImage)) {
649
        // 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
650 651
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
652 653
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
654
            m_draggingImageURL = imageURL;
655 656
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, dragSource.altDisplayString());
        }
657

658
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
659

660 661 662 663
        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);
664
        } else
665 666 667 668
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
669 670 671 672
        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);
673 674 675 676 677 678 679 680

        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)
681
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
682 683
        }

684 685 686 687 688 689
        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());
690
        }
691
        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
692
    } else if (isSelected && (m_dragSourceAction & DragSourceActionSelection)) {
eric@webkit.org's avatar
eric@webkit.org committed
693
        RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
694
        ASSERT(selectionRange);
695
        if (!clipboard->hasData())
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
            clipboard->writeRange(selectionRange.get(), src);
        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;
    }
713

714 715 716 717
    if (dragImage)
        deleteDragImage(dragImage);
    return startedDrag;
}
718

719 720 721 722 723
void DragController::doImageDrag(Element* element, const IntPoint& dragOrigin, const IntRect& rect, Clipboard* clipboard, Frame* frame, IntPoint& dragImageOffset)
{
    IntPoint mouseDownPoint = dragOrigin;
    DragImageRef dragImage;
    IntPoint origin;
724

725
    Image* image = getImage(element);
726 727
    if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
        && (dragImage = createDragImageFromImage(image))) {
728 729
        IntSize originalSize = rect.size();
        origin = rect.location();
730

oliver's avatar
oliver committed
731
        dragImage = fitDragImageToMaxSize(dragImage, rect.size(), maxDragImageSize());
732 733
        dragImage = dissolveDragImageToFraction(dragImage, DragImageAlpha);
        IntSize newSize = dragImageSize(dragImage);
734

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
        // 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);
    }
752

753 754 755
    dragImageOffset.setX(mouseDownPoint.x() + origin.x());
    dragImageOffset.setY(mouseDownPoint.y() + origin.y());
    doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
756

757 758
    deleteDragImage(dragImage);
}
759

760 761 762 763 764 765 766
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();
767 768
    m_client->startDrag(image, viewProtector->windowToContents(frame->view()->contentsToWindow(dragLoc)),
        viewProtector->windowToContents(frame->view()->contentsToWindow(eventPos)), clipboard, frameProtector.get(), forLink);
769

770
    cleanupAfterSystemDrag();
771
}
772

oliver's avatar
oliver committed
773 774 775
// Manual drag caret manipulation
void DragController::placeDragCaret(const IntPoint& windowPoint)
{
776 777
    mouseMovedIntoDocument(m_page->mainFrame()->documentAtPoint(windowPoint));
    if (!m_documentUnderMouse)
oliver's avatar
oliver committed
778
        return;
779
    Frame* frame = m_documentUnderMouse->frame();
oliver's avatar
oliver committed
780 781 782 783
    FrameView* frameView = frame->view();
    if (!frameView)
        return;
    IntPoint framePoint = frameView->windowToContents(windowPoint);
784
    VisibleSelection dragCaret(frame->visiblePositionForPoint(framePoint));
oliver's avatar
oliver committed
785 786
    m_page->dragCaretController()->setSelection(dragCaret);
}
787

788
} // namespace WebCore