DragController.cpp 37.1 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
                              LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
83
                              metaKey, currentTime());
84
}
85

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

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

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

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

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

144 145 146
    return 0;
}

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

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

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

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

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

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

190
DragSession DragController::dragUpdated(DragData* dragData)
191 192 193
{
    return dragEnteredOrUpdated(dragData);
}
194

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

214
    if ((m_dragDestinationAction & DragDestinationActionEdit) && concludeEditDrag(dragData)) {
215
        m_documentUnderMouse = 0;
216 217
        return true;
    }
218

219
    m_documentUnderMouse = 0;
220

221
    if (operationForLoad(dragData) == DragOperationNone)
222
        return false;
223 224

    m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData);
225
    m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL(m_page->mainFrame())), false);
226 227
    return true;
}
228 229 230 231 232 233 234 235 236 237 238 239

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

240
DragSession DragController::dragEnteredOrUpdated(DragData* dragData)
241 242
{
    ASSERT(dragData);
243 244 245
    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()));

246
    m_dragDestinationAction = m_client->actionMaskForDrag(dragData);
247
    if (m_dragDestinationAction == DragDestinationActionNone) {
248
        cancelDrag(); // FIXME: Why not call mouseMovedIntoDocument(0)?
249
        return DragSession();
250
    }
251

252 253
    DragSession dragSession;
    bool handledByDocument = tryDocumentDrag(dragData, m_dragDestinationAction, dragSession);
254
    if (!handledByDocument && (m_dragDestinationAction & DragDestinationActionLoad))
255 256
        dragSession.operation = operationForLoad(dragData);
    return dragSession;
257
}
258 259 260 261

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

263
    HTMLInputElement* inputElement = node->toInputElement();
264

265
    // If this is a button inside of the a file input, move up to the file input.
266 267
    if (inputElement && inputElement->isTextButton() && inputElement->treeScope()->isShadowRoot())
        inputElement = inputElement->treeScope()->shadowHost()->toInputElement();
268

269
    return inputElement && inputElement->isFileUpload() ? inputElement : 0;
270
}
271

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

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

292
bool DragController::tryDocumentDrag(DragData* dragData, DragDestinationAction actionMask, DragSession& dragSession)
293 294
{
    ASSERT(dragData);
295

296
    if (!m_documentUnderMouse)
297
        return false;
298

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

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

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

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

329
        IntPoint point = frameView->windowToContents(dragData->clientPosition());
330
        Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
331 332
        if (!element)
            return false;
333 334
        
        HTMLInputElement* elementAsFileInput = asFileInput(element);
335 336 337 338 339 340 341
        if (m_fileInputElementUnderMouse != elementAsFileInput) {
            if (m_fileInputElementUnderMouse)
                m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
            m_fileInputElementUnderMouse = elementAsFileInput;
        }
        
        if (!m_fileInputElementUnderMouse)
342
            m_page->dragCaretController()->setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
343 344

        Frame* innerFrame = element->document()->frame();
345
        dragSession.operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
346
        dragSession.mouseIsOverFileInput = m_fileInputElementUnderMouse;
347 348 349
        dragSession.numberOfItemsToBeAccepted = 0;

        unsigned numberOfFiles = dragData->numberOfFiles();
350 351
        if (m_fileInputElementUnderMouse) {
            if (m_fileInputElementUnderMouse->disabled())
352
                dragSession.numberOfItemsToBeAccepted = 0;
353
            else if (m_fileInputElementUnderMouse->multiple())
354 355 356 357 358 359
                dragSession.numberOfItemsToBeAccepted = numberOfFiles;
            else
                dragSession.numberOfItemsToBeAccepted = 1;
            
            if (!dragSession.numberOfItemsToBeAccepted)
                dragSession.operation = DragOperationNone;
360
            m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(dragSession.numberOfItemsToBeAccepted);
361 362 363 364 365 366
        } 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;
        }
        
367 368
        return true;
    }
369 370
    
    // We are not over an editable region. Make sure we're clearing any prior drag cursor.
371
    m_page->dragCaretController()->clear();
372 373 374
    if (m_fileInputElementUnderMouse)
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
    m_fileInputElementUnderMouse = 0;
375
    return false;
376
}
377

378
DragSourceAction DragController::delegateDragSourceAction(const IntPoint& rootViewPoint)
379
{
380
    m_dragSourceAction = m_client->dragSourceActionMaskForPoint(rootViewPoint);
381 382
    return m_dragSourceAction;
}
383

384 385 386
DragOperation DragController::operationForLoad(DragData* dragData)
{
    ASSERT(dragData);
387
    Document* doc = m_page->mainFrame()->documentAtPoint(dragData->clientPosition());
388
    if (doc && (m_didInitiateDrag || doc->isPluginDocument() || doc->rendererIsEditable()))
389 390 391 392
        return DragOperationNone;
    return dragOperation(dragData);
}

393
static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
394
{
darin@apple.com's avatar
darin@apple.com committed
395 396
    frame->selection()->setSelection(dragCaret);
    if (frame->selection()->isNone()) {
oliver's avatar
oliver committed
397
        dragCaret = frame->visiblePositionForPoint(point);
darin@apple.com's avatar
darin@apple.com committed
398
        frame->selection()->setSelection(dragCaret);
eric@webkit.org's avatar
eric@webkit.org committed
399
        range = dragCaret.toNormalizedRange();
400
    }
darin@apple.com's avatar
darin@apple.com committed
401
    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
402 403
}

404 405
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
406 407 408
    ASSERT(m_page->dragCaretController()->hasCaret());
    String text = m_page->dragCaretController()->isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
    Node* target = innerFrame->editor()->findEventTargetFrom(m_page->dragCaretController()->caretPosition());
409 410 411 412
    ExceptionCode ec = 0;
    return target->dispatchEvent(TextEvent::createForDrop(innerFrame->domWindow(), text), ec);
}

413
bool DragController::concludeEditDrag(DragData* dragData)
414 415 416
{
    ASSERT(dragData);
    ASSERT(!m_isHandlingDrag);
417

418 419 420 421 422
    if (m_fileInputElementUnderMouse) {
        m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
        m_fileInputElementUnderMouse = 0;
    }

423
    if (!m_documentUnderMouse)
424
        return false;
425

426
    IntPoint point = m_documentUnderMouse->view()->windowToContents(dragData->clientPosition());
427
    Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
428 429
    if (!element)
        return false;
430
    Frame* innerFrame = element->ownerDocument()->frame();
431
    ASSERT(innerFrame);
432

433
    if (m_page->dragCaretController()->hasCaret() && !dispatchTextInputEventFor(innerFrame, dragData))
434 435
        return true;

436 437 438 439
    if (dragData->containsColor()) {
        Color color = dragData->asColor();
        if (!color.isValid())
            return false;
eric@webkit.org's avatar
eric@webkit.org committed
440
        RefPtr<Range> innerRange = innerFrame->selection()->toNormalizedRange();
441
        RefPtr<CSSStyleDeclaration> style = m_documentUnderMouse->createCSSStyleDeclaration();
442
        ExceptionCode ec;
443
        style->setProperty(CSSPropertyColor, color.serialized(), false, ec);
444 445 446 447 448 449
        if (!innerFrame->editor()->shouldApplyStyle(style.get(), innerRange.get()))
            return false;
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
        innerFrame->editor()->applyStyle(style.get(), EditActionSetColor);
        return true;
    }
450

451 452 453 454
    if (!m_page->dragController()->canProcessDrag(dragData)) {
        m_page->dragCaretController()->clear();
        return false;
    }
455

456
    if (HTMLInputElement* fileInput = asFileInput(element)) {
457
        if (fileInput->disabled())
adele@apple.com's avatar
adele@apple.com committed
458
            return false;
459

460 461
        if (!dragData->containsFiles())
            return false;
462

463 464 465 466
        Vector<String> filenames;
        dragData->asFilenames(filenames);
        if (filenames.isEmpty())
            return false;
467

468
        fileInput->receiveDroppedFiles(filenames);
469 470
        return true;
    }
471

472
    VisibleSelection dragCaret = m_page->dragCaretController()->caretPosition();
justing's avatar
justing committed
473
    m_page->dragCaretController()->clear();
eric@webkit.org's avatar
eric@webkit.org committed
474
    RefPtr<Range> range = dragCaret.toNormalizedRange();
475

oliver's avatar
oliver committed
476 477
    // For range to be null a WebKit client must have done something bad while
    // manually controlling drag behaviour
478
    if (!range)
oliver's avatar
oliver committed
479
        return false;
480
    CachedResourceLoader* cachedResourceLoader = range->ownerDocument()->cachedResourceLoader();
481
    ResourceCacheValidationSuppressor validationSuppressor(cachedResourceLoader);
482
    if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
483
        bool chosePlainText = false;
484
        RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame, range, true, chosePlainText);
485
        if (!fragment || !innerFrame->editor()->shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
486
            return false;
487
        }
488

489
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
490
        if (dragIsMove(innerFrame->selection(), dragData)) {
491 492 493
            // 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();
494
            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
495
            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
496
        } else {
497 498 499 500 501 502 503 504
            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));
            }
505
        }
506
    } else {
507
        String text = dragData->asPlainText(innerFrame);
508
        if (text.isEmpty() || !innerFrame->editor()->shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
509
            return false;
510
        }
511

512
        m_client->willPerformDragDestinationAction(DragDestinationActionEdit, dragData);
513
        if (setSelectionToDragCaret(innerFrame, dragCaret, range, point))
514
            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
515 516 517 518
    }

    return true;
}
519 520

bool DragController::canProcessDrag(DragData* dragData)
521 522 523 524 525
{
    ASSERT(dragData);

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

527
    IntPoint point = m_page->mainFrame()->view()->windowToContents(dragData->clientPosition());
528
    HitTestResult result = HitTestResult(point);
eric@webkit.org's avatar
eric@webkit.org committed
529
    if (!m_page->mainFrame()->contentRenderer())
530 531 532
        return false;

    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, true);
533 534

    if (!result.innerNonSharedNode())
535
        return false;
536

537 538
    if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
        return true;
539

540
    if (!result.innerNonSharedNode()->rendererIsEditable())
541
        return false;
542

543
    if (m_didInitiateDrag && m_documentUnderMouse == m_dragInitiator && result.isSelected())
544
        return false;
545

546 547 548
    return true;
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
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;
}

568
bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
569
{
570
    ASSERT(dragData);
571
    ASSERT(m_documentUnderMouse);
ggaren@apple.com's avatar
ggaren@apple.com committed
572 573
    RefPtr<Frame> mainFrame = m_page->mainFrame();
    RefPtr<FrameView> viewProtector = mainFrame->view();
574
    if (!viewProtector)
575 576
        return false;

ggaren@apple.com's avatar
ggaren@apple.com committed
577
    ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
578
    RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
579 580
    DragOperation srcOpMask = dragData->draggingSourceOperationMask();
    clipboard->setSourceOperation(srcOpMask);
581

582 583
    PlatformMouseEvent event = createMouseEvent(dragData);
    if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
584
        clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
585 586 587
        return false;
    }

588
    operation = clipboard->destinationOperation();
589 590 591
    if (clipboard->dropEffectIsUninitialized())
        operation = defaultOperationForDrag(srcOpMask);
    else if (!(srcOpMask & operation)) {
592 593
        // The element picked an operation which is not supported by the source
        operation = DragOperationNone;
594
    }
595 596 597

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

600
Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
601
{
602
    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
603 604 605

    for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
        Node* node = renderer->node();
606 607 608 609 610 611 612 613 614 615
        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()) {
616
            EUserDrag dragMode = renderer->style()->userDrag();
617 618
            if ((m_dragSourceAction & DragSourceActionDHTML) && dragMode == DRAG_ELEMENT) {
                state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
619 620
                return node;
            }
621 622 623 624 625 626 627 628 629 630 631 632 633
            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;
                }
634 635 636
            }
        }
    }
oliver's avatar
 
oliver committed
637

638 639
    // 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
640
}
641

642 643 644 645
static CachedImage* getCachedImage(Element* element)
{
    ASSERT(element);
    RenderObject* renderer = element->renderer();
646
    if (!renderer || !renderer->isImage())
647
        return 0;
648
    RenderImage* image = toRenderImage(renderer);
649 650
    return image->cachedImage();
}
651

652 653 654
static Image* getImage(Element* element)
{
    ASSERT(element);
655
    CachedImage* cachedImage = getCachedImage(element);
656 657 658
    // Don't use cachedImage->imageForRenderer() here as that may return BitmapImages for cached SVG Images.
    // Users of getImage() want access to the SVGImage, in order to figure out the filename extensions,
    // which would be empty when asking the cached BitmapImages.
659
    return (cachedImage && !cachedImage->errorOccurred()) ?
660
        cachedImage->image() : 0;
661
}
662

663
static void prepareClipboardForImageDrag(Frame* source, Clipboard* clipboard, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
664
{
665 666 667 668 669 670 671 672
    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);
673
}
674

675 676 677
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.
678 679
#if PLATFORM(MAC)
    // We add in the Y dimension because we are a flipped view, so adding moves the image down.
680 681 682 683
    const int yOffset = dragImageOffset.y();
#else
    const int yOffset = -dragImageOffset.y();
#endif
684

685 686
    if (isLinkImage)
        return IntPoint(mouseDraggedPoint.x() - dragImageOffset.x(), mouseDraggedPoint.y() + yOffset);
687

688 689
    return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
}
690

691 692
static IntPoint dragLocForSelectionDrag(Frame* src)
{
693
    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
694
    int xpos = draggingRect.maxX();
695
    xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
696
    int ypos = draggingRect.maxY();
697 698 699 700 701 702 703 704
#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);
}
705

706
bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
707
{
708
    ASSERT(src);
709

eric@webkit.org's avatar
eric@webkit.org committed
710
    if (!src->view() || !src->contentRenderer())
711
        return false;
712

713 714 715 716 717 718 719 720
    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();
721

722
    IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.pos());
723

724
    m_draggingImageURL = KURL();
725
    m_sourceDragOperation = srcOp;
726

727 728 729
    DragImageRef dragImage = 0;
    IntPoint dragLoc(0, 0);
    IntPoint dragImageOffset(0, 0);
730

731 732
    Clipboard* clipboard = state.m_dragClipboard.get();
    if (state.m_dragType == DragSourceActionDHTML)
733
        dragImage = clipboard->createDragImage(dragImageOffset);
734 735 736
    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:
737
        // http://trac.webkit.org/browser/trunk/WebKit/mac/WebView/WebHTMLView.mm?rev=48526#L3430
738
        m_sourceDragOperation = static_cast<DragOperation>(m_sourceDragOperation | DragOperationGeneric | DragOperationCopy);
739

740 741 742 743 744 745
    // 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;
    }
746

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

749
    Node* node = state.m_dragSrc.get();
750

alice.liu@apple.com's avatar
alice.liu@apple.com committed
751
    Image* image = getImage(static_cast<Element*>(node));
752 753
    if (state.m_dragType == DragSourceActionSelection) {
        if (!clipboard->hasData()) {
754
            if (enclosingTextFormControl(src->selection()->start()))
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
                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);
770
    } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
771
               && (m_dragSourceAction & DragSourceActionImage)) {
772
        // 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
773 774
        // This is an early detection for problems encountered later upon drop.
        ASSERT(!image->filenameExtension().isEmpty());
775 776
        Element* element = static_cast<Element*>(node);
        if (!clipboard->hasData()) {
777
            m_draggingImageURL = imageURL;
778
            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
779
        }
780

781
        m_client->willPerformDragSourceAction(DragSourceActionImage, dragOrigin, clipboard);
782

783
        if (!dragImage) {
784
            IntRect imageRect = hitTestResult.imageRect();
785
            imageRect.setLocation(m_page->mainFrame()->view()->rootViewToContents(src->view()->contentsToRootView(imageRect.location())));
786
            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
787
        } else
788 789 790 791
            // DHTML defined drag image
            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);

    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
sullivan's avatar
sullivan committed
792 793 794
        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.
795
            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
796 797 798 799 800 801 802 803

        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)
804
                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
805 806
        }

807 808
        m_client->willPerformDragSourceAction(DragSourceActionLink, dragOrigin, clipboard);
        if (!dragImage) {
809
            dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), src);
810 811 812
            IntSize size = dragImageSize(dragImage);
            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
            dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
813
        }
814
        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
815
    } else if (state.m_dragType == DragSourceActionDHTML) {
816 817 818 819
        ASSERT(m_dragSourceAction & DragSourceActionDHTML);
        m_client->willPerformDragSourceAction(DragSourceActionDHTML, dragOrigin, clipboard);
        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
    } else {
820 821
        // draggableNode() determined an image or link node was draggable, but it turns out the
        // image or link had no URL, so there is nothing to drag.
822 823
        startedDrag = false;
    }
824

825 826 827 828
    if (dragImage)
        deleteDragImage(dragImage);
    return startedDrag;
}
829

830 831 832 833 834
void DragController::doImageDrag(Element* element, const IntPoint& dragOrigin, const IntRect& rect, Clipboard* clipboard, Frame* frame, IntPoint& dragImageOffset)
{
    IntPoint mouseDownPoint = dragOrigin;
    DragImageRef dragImage;
    IntPoint origin;
835

836
    Image* image = getImage(element);
837 838
    if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
        && (dragImage = createDragImageFromImage(image))) {
839 840
        IntSize originalSize = rect.size();
        origin = rect.location();
841

oliver's avatar
oliver committed
842
        dragImage = fitDragImageToMaxSize(dragImage, rect.size(), maxDragImageSize());
oliver's avatar