1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "nsBaseDragService.h"
7 #include "nsITransferable.h"
9 #include "nsArrayUtils.h"
10 #include "nsITransferable.h"
14 #include "nsIInterfaceRequestorUtils.h"
16 #include "nsFrameLoaderOwner.h"
17 #include "nsIContent.h"
18 #include "nsViewManager.h"
20 #include "nsPresContext.h"
21 #include "nsIImageLoadingContent.h"
22 #include "imgIContainer.h"
23 #include "imgIRequest.h"
24 #include "ImageRegion.h"
25 #include "nsQueryObject.h"
27 #include "nsXULPopupManager.h"
28 #include "nsMenuPopupFrame.h"
29 #include "nsTreeBodyFrame.h"
30 #include "mozilla/MouseEvents.h"
31 #include "mozilla/Preferences.h"
32 #include "mozilla/PresShell.h"
33 #include "mozilla/ProfilerLabels.h"
34 #include "mozilla/SVGImageContext.h"
35 #include "mozilla/TextControlElement.h"
36 #include "mozilla/Unused.h"
37 #include "mozilla/ViewportUtils.h"
38 #include "mozilla/dom/BindingDeclarations.h"
39 #include "mozilla/dom/DataTransferItemList.h"
40 #include "mozilla/dom/DataTransfer.h"
41 #include "mozilla/dom/Document.h"
42 #include "mozilla/dom/DocumentInlines.h"
43 #include "mozilla/dom/DragEvent.h"
44 #include "mozilla/dom/MouseEventBinding.h"
45 #include "mozilla/dom/Selection.h"
46 #include "mozilla/gfx/2D.h"
47 #include "nsFrameLoader.h"
48 #include "BrowserParent.h"
49 #include "nsIMutableArray.h"
50 #include "gfxContext.h"
51 #include "gfxPlatform.h"
55 using namespace mozilla
;
56 using namespace mozilla::dom
;
57 using namespace mozilla::gfx
;
58 using namespace mozilla::image
;
60 #define DRAGIMAGES_PREF "nglayout.enable_drag_images"
62 nsBaseDragService::nsBaseDragService()
64 mOnlyChromeDrop(false),
66 mSessionIsSynthesizedForTests(false),
67 mIsDraggingTextInTextControl(false),
68 mEndingSession(false),
70 mUserCancelled(false),
71 mDragEventDispatchedToChildProcess(false),
72 mDragAction(DRAGDROP_ACTION_NONE
),
73 mDragActionFromChildProcess(DRAGDROP_ACTION_UNINITIALIZED
),
74 mEffectAllowedForTests(DRAGDROP_ACTION_UNINITIALIZED
),
75 mContentPolicyType(nsIContentPolicy::TYPE_OTHER
),
77 mInputSource(MouseEvent_Binding::MOZ_SOURCE_MOUSE
) {}
79 nsBaseDragService::~nsBaseDragService() = default;
81 NS_IMPL_ISUPPORTS(nsBaseDragService
, nsIDragService
, nsIDragSession
)
83 //---------------------------------------------------------
85 nsBaseDragService::SetCanDrop(bool aCanDrop
) {
90 //---------------------------------------------------------
92 nsBaseDragService::GetCanDrop(bool* aCanDrop
) {
96 //---------------------------------------------------------
98 nsBaseDragService::SetOnlyChromeDrop(bool aOnlyChrome
) {
99 mOnlyChromeDrop
= aOnlyChrome
;
103 //---------------------------------------------------------
105 nsBaseDragService::GetOnlyChromeDrop(bool* aOnlyChrome
) {
106 *aOnlyChrome
= mOnlyChromeDrop
;
110 //---------------------------------------------------------
112 nsBaseDragService::SetDragAction(uint32_t anAction
) {
113 mDragAction
= anAction
;
117 //---------------------------------------------------------
119 nsBaseDragService::GetDragAction(uint32_t* anAction
) {
120 *anAction
= mDragAction
;
124 //-------------------------------------------------------------------------
127 nsBaseDragService::GetNumDropItems(uint32_t* aNumItems
) {
129 return NS_ERROR_FAILURE
;
133 // GetSourceWindowContext
135 // Returns the window context where the drag was initiated. This will be
136 // nullptr if the drag began outside of our application.
139 nsBaseDragService::GetSourceWindowContext(
140 WindowContext
** aSourceWindowContext
) {
141 *aSourceWindowContext
= mSourceWindowContext
.get();
142 NS_IF_ADDREF(*aSourceWindowContext
);
147 nsBaseDragService::SetSourceWindowContext(WindowContext
* aSourceWindowContext
) {
148 // This should only be called in a child process.
149 MOZ_ASSERT(!XRE_IsParentProcess());
150 mSourceWindowContext
= aSourceWindowContext
;
155 // GetSourceTopWindowContext
157 // Returns the top-level window context where the drag was initiated. This will
158 // be nullptr if the drag began outside of our application.
161 nsBaseDragService::GetSourceTopWindowContext(
162 WindowContext
** aSourceTopWindowContext
) {
163 *aSourceTopWindowContext
= mSourceTopWindowContext
.get();
164 NS_IF_ADDREF(*aSourceTopWindowContext
);
169 nsBaseDragService::SetSourceTopWindowContext(
170 WindowContext
* aSourceTopWindowContext
) {
171 // This should only be called in a child process.
172 MOZ_ASSERT(!XRE_IsParentProcess());
173 mSourceTopWindowContext
= aSourceTopWindowContext
;
180 // Returns the DOM node where the drag was initiated. This will be
181 // nullptr if the drag began outside of our application.
184 nsBaseDragService::GetSourceNode(nsINode
** aSourceNode
) {
185 *aSourceNode
= do_AddRef(mSourceNode
).take();
189 void nsBaseDragService::UpdateSource(nsINode
* aNewSourceNode
,
190 Selection
* aNewSelection
) {
191 MOZ_ASSERT(mSourceNode
);
192 MOZ_ASSERT(aNewSourceNode
);
193 MOZ_ASSERT(mSourceNode
->IsInNativeAnonymousSubtree() ||
194 aNewSourceNode
->IsInNativeAnonymousSubtree());
195 MOZ_ASSERT(mSourceDocument
== aNewSourceNode
->OwnerDoc());
196 mSourceNode
= aNewSourceNode
;
197 // Don't set mSelection if the session was invoked without selection or
198 // making it becomes nullptr. The latter occurs when the old frame is
200 if (mSelection
&& aNewSelection
) {
201 // XXX If the dragging image is created once (e.g., at drag start), the
202 // image won't be updated unless we notify `DrawDrag` callers.
203 // However, it must be okay for now to keep using older image of
205 mSelection
= aNewSelection
;
210 nsBaseDragService::GetTriggeringPrincipal(nsIPrincipal
** aPrincipal
) {
211 NS_IF_ADDREF(*aPrincipal
= mTriggeringPrincipal
);
216 nsBaseDragService::SetTriggeringPrincipal(nsIPrincipal
* aPrincipal
) {
217 mTriggeringPrincipal
= aPrincipal
;
222 nsBaseDragService::GetCsp(nsIContentSecurityPolicy
** aCsp
) {
223 NS_IF_ADDREF(*aCsp
= mCsp
);
228 nsBaseDragService::SetCsp(nsIContentSecurityPolicy
* aCsp
) {
233 //-------------------------------------------------------------------------
236 nsBaseDragService::GetData(nsITransferable
* aTransferable
,
237 uint32_t aItemIndex
) {
238 return NS_ERROR_FAILURE
;
241 //-------------------------------------------------------------------------
243 nsBaseDragService::IsDataFlavorSupported(const char* aDataFlavor
,
245 return NS_ERROR_FAILURE
;
249 nsBaseDragService::GetDataTransferXPCOM(DataTransfer
** aDataTransfer
) {
250 *aDataTransfer
= mDataTransfer
;
251 NS_IF_ADDREF(*aDataTransfer
);
256 nsBaseDragService::SetDataTransferXPCOM(DataTransfer
* aDataTransfer
) {
257 NS_ENSURE_STATE(aDataTransfer
);
258 mDataTransfer
= aDataTransfer
;
262 DataTransfer
* nsBaseDragService::GetDataTransfer() { return mDataTransfer
; }
264 void nsBaseDragService::SetDataTransfer(DataTransfer
* aDataTransfer
) {
265 mDataTransfer
= aDataTransfer
;
268 bool nsBaseDragService::IsSynthesizedForTests() {
269 return mSessionIsSynthesizedForTests
;
272 bool nsBaseDragService::IsDraggingTextInTextControl() {
273 return mIsDraggingTextInTextControl
;
276 uint32_t nsBaseDragService::GetEffectAllowedForTests() {
277 MOZ_ASSERT(mSessionIsSynthesizedForTests
);
278 return mEffectAllowedForTests
;
281 NS_IMETHODIMP
nsBaseDragService::SetDragEndPointForTests(int32_t aScreenX
,
283 MOZ_ASSERT(mDoingDrag
);
284 MOZ_ASSERT(mSourceDocument
);
285 MOZ_ASSERT(mSessionIsSynthesizedForTests
);
287 if (!mDoingDrag
|| !mSourceDocument
|| !mSessionIsSynthesizedForTests
) {
288 return NS_ERROR_FAILURE
;
290 nsPresContext
* pc
= mSourceDocument
->GetPresContext();
291 if (NS_WARN_IF(!pc
)) {
292 return NS_ERROR_FAILURE
;
294 auto p
= LayoutDeviceIntPoint::Round(CSSIntPoint(aScreenX
, aScreenY
) *
295 pc
->CSSToDevPixelScale());
296 // p is screen-relative, and we want them to be top-level-widget-relative.
297 if (nsCOMPtr
<nsIWidget
> widget
= pc
->GetRootWidget()) {
298 p
-= widget
->WidgetToScreenOffset();
299 p
+= widget
->WidgetToTopLevelWidgetOffset();
305 //-------------------------------------------------------------------------
307 nsBaseDragService::InvokeDragSession(
308 nsINode
* aDOMNode
, nsIPrincipal
* aPrincipal
, nsIContentSecurityPolicy
* aCsp
,
309 nsICookieJarSettings
* aCookieJarSettings
, nsIArray
* aTransferableArray
,
310 uint32_t aActionType
,
311 nsContentPolicyType aContentPolicyType
= nsIContentPolicy::TYPE_OTHER
) {
312 AUTO_PROFILER_LABEL("nsBaseDragService::InvokeDragSession", OTHER
);
314 NS_ENSURE_TRUE(aDOMNode
, NS_ERROR_INVALID_ARG
);
315 NS_ENSURE_TRUE(mSuppressLevel
== 0, NS_ERROR_FAILURE
);
317 // stash the document of the dom node
318 mSourceDocument
= aDOMNode
->OwnerDoc();
319 mTriggeringPrincipal
= aPrincipal
;
321 mSourceNode
= aDOMNode
;
322 mIsDraggingTextInTextControl
=
323 mSourceNode
->IsInNativeAnonymousSubtree() &&
324 TextControlElement::FromNodeOrNull(
325 mSourceNode
->GetClosestNativeAnonymousSubtreeRootParent());
326 mContentPolicyType
= aContentPolicyType
;
327 mEndDragPoint
= LayoutDeviceIntPoint(0, 0);
329 // When the mouse goes down, the selection code starts a mouse
330 // capture. However, this gets in the way of determining drag
331 // feedback for things like trees because the event coordinates
332 // are in the wrong coord system, so turn off mouse capture.
333 PresShell::ClearMouseCapture();
335 if (mSessionIsSynthesizedForTests
) {
337 mDragAction
= aActionType
;
338 mEffectAllowedForTests
= aActionType
;
342 // If you're hitting this, a test is causing the browser to attempt to enter
343 // the drag-drop native nested event loop, which will put the browser in a
344 // state that won't run tests properly until there's manual intervention
345 // to exit the drag-drop loop (either by moving the mouse or hitting escape),
346 // which can't be done from script since we're in the nested loop.
348 // The best way to avoid this is to catch the dragstart event on the item
349 // being dragged, and then to call preventDefault() and stopPropagating() on
351 if (XRE_IsParentProcess()) {
353 !xpc::IsInAutomation(),
354 "About to start drag-drop native loop on which will prevent later "
355 "tests from running properly.");
359 mozilla::Unused
<< aTransferableArray
->GetLength(&length
);
361 nsCOMPtr
<nsIMutableArray
> mutableArray
=
362 do_QueryInterface(aTransferableArray
);
364 // In order to be able trigger dnd, we need to have some transferable
366 nsCOMPtr
<nsITransferable
> trans
=
367 do_CreateInstance("@mozilla.org/widget/transferable;1");
368 trans
->Init(nullptr);
369 trans
->SetRequestingPrincipal(mSourceNode
->NodePrincipal());
370 trans
->SetContentPolicyType(mContentPolicyType
);
371 trans
->SetCookieJarSettings(aCookieJarSettings
);
372 mutableArray
->AppendElement(trans
);
375 for (uint32_t i
= 0; i
< length
; ++i
) {
376 nsCOMPtr
<nsITransferable
> trans
=
377 do_QueryElementAt(aTransferableArray
, i
);
379 // Set the requestingPrincipal on the transferable.
380 trans
->SetRequestingPrincipal(mSourceNode
->NodePrincipal());
381 trans
->SetContentPolicyType(mContentPolicyType
);
382 trans
->SetCookieJarSettings(aCookieJarSettings
);
387 nsresult rv
= InvokeDragSessionImpl(aTransferableArray
, mRegion
, aActionType
);
390 // Set mDoingDrag so that EndDragSession cleans up and sends the dragend
391 // event after the aborted drag.
393 EndDragSession(true, 0);
400 nsBaseDragService::InvokeDragSessionWithImage(
401 nsINode
* aDOMNode
, nsIPrincipal
* aPrincipal
, nsIContentSecurityPolicy
* aCsp
,
402 nsICookieJarSettings
* aCookieJarSettings
, nsIArray
* aTransferableArray
,
403 uint32_t aActionType
, nsINode
* aImage
, int32_t aImageX
, int32_t aImageY
,
404 DragEvent
* aDragEvent
, DataTransfer
* aDataTransfer
) {
405 NS_ENSURE_TRUE(aDragEvent
, NS_ERROR_NULL_POINTER
);
406 NS_ENSURE_TRUE(aDataTransfer
, NS_ERROR_NULL_POINTER
);
407 NS_ENSURE_TRUE(mSuppressLevel
== 0, NS_ERROR_FAILURE
);
409 mSessionIsSynthesizedForTests
=
410 aDragEvent
->WidgetEventPtr()->mFlags
.mIsSynthesizedForTests
;
411 mDataTransfer
= aDataTransfer
;
412 mSelection
= nullptr;
414 mDragPopup
= nullptr;
416 mImageOffset
= CSSIntPoint(aImageX
, aImageY
);
417 mDragStartData
= nullptr;
418 mSourceWindowContext
=
419 aDOMNode
? aDOMNode
->OwnerDoc()->GetWindowContext() : nullptr;
420 mSourceTopWindowContext
=
421 mSourceWindowContext
? mSourceWindowContext
->TopWindowContext() : nullptr;
423 mScreenPosition
= aDragEvent
->ScreenPoint(CallerType::System
);
424 mInputSource
= aDragEvent
->MozInputSource();
426 // If dragging within a XUL tree and no custom drag image was
427 // set, the region argument to InvokeDragSessionWithImage needs
428 // to be set to the area encompassing the selected rows of the
429 // tree to ensure that the drag feedback gets clipped to those
430 // rows. For other content, region should be null.
432 if (aDOMNode
&& aDOMNode
->IsContent() && !aImage
) {
433 if (aDOMNode
->NodeInfo()->Equals(nsGkAtoms::treechildren
,
435 nsTreeBodyFrame
* treeBody
=
436 do_QueryFrame(aDOMNode
->AsContent()->GetPrimaryFrame());
438 mRegion
= treeBody
->GetSelectionRegion();
443 nsresult rv
= InvokeDragSession(
444 aDOMNode
, aPrincipal
, aCsp
, aCookieJarSettings
, aTransferableArray
,
445 aActionType
, nsIContentPolicy::TYPE_INTERNAL_IMAGE
);
451 nsBaseDragService::InvokeDragSessionWithRemoteImage(
452 nsINode
* aDOMNode
, nsIPrincipal
* aPrincipal
, nsIContentSecurityPolicy
* aCsp
,
453 nsICookieJarSettings
* aCookieJarSettings
, nsIArray
* aTransferableArray
,
454 uint32_t aActionType
, RemoteDragStartData
* aDragStartData
,
455 DragEvent
* aDragEvent
, DataTransfer
* aDataTransfer
) {
456 NS_ENSURE_TRUE(aDragEvent
, NS_ERROR_NULL_POINTER
);
457 NS_ENSURE_TRUE(aDataTransfer
, NS_ERROR_NULL_POINTER
);
458 NS_ENSURE_TRUE(mSuppressLevel
== 0, NS_ERROR_FAILURE
);
460 mSessionIsSynthesizedForTests
=
461 aDragEvent
->WidgetEventPtr()->mFlags
.mIsSynthesizedForTests
;
462 mDataTransfer
= aDataTransfer
;
463 mSelection
= nullptr;
465 mDragPopup
= nullptr;
467 mDragStartData
= aDragStartData
;
468 mImageOffset
= CSSIntPoint(0, 0);
469 mSourceWindowContext
= mDragStartData
->GetSourceWindowContext();
470 mSourceTopWindowContext
= mDragStartData
->GetSourceTopWindowContext();
472 mScreenPosition
= aDragEvent
->ScreenPoint(CallerType::System
);
473 mInputSource
= aDragEvent
->MozInputSource();
475 nsresult rv
= InvokeDragSession(
476 aDOMNode
, aPrincipal
, aCsp
, aCookieJarSettings
, aTransferableArray
,
477 aActionType
, nsIContentPolicy::TYPE_INTERNAL_IMAGE
);
483 nsBaseDragService::InvokeDragSessionWithSelection(
484 Selection
* aSelection
, nsIPrincipal
* aPrincipal
,
485 nsIContentSecurityPolicy
* aCsp
, nsICookieJarSettings
* aCookieJarSettings
,
486 nsIArray
* aTransferableArray
, uint32_t aActionType
, DragEvent
* aDragEvent
,
487 DataTransfer
* aDataTransfer
) {
488 NS_ENSURE_TRUE(aSelection
, NS_ERROR_NULL_POINTER
);
489 NS_ENSURE_TRUE(aDragEvent
, NS_ERROR_NULL_POINTER
);
490 NS_ENSURE_TRUE(mSuppressLevel
== 0, NS_ERROR_FAILURE
);
492 mSessionIsSynthesizedForTests
=
493 aDragEvent
->WidgetEventPtr()->mFlags
.mIsSynthesizedForTests
;
494 mDataTransfer
= aDataTransfer
;
495 mSelection
= aSelection
;
497 mDragPopup
= nullptr;
499 mImageOffset
= CSSIntPoint();
500 mDragStartData
= nullptr;
503 mScreenPosition
.x
= aDragEvent
->ScreenX(CallerType::System
);
504 mScreenPosition
.y
= aDragEvent
->ScreenY(CallerType::System
);
505 mInputSource
= aDragEvent
->MozInputSource();
507 // just get the focused node from the selection
508 // XXXndeakin this should actually be the deepest node that contains both
509 // endpoints of the selection
510 nsCOMPtr
<nsINode
> node
= aSelection
->GetFocusNode();
511 mSourceWindowContext
= node
? node
->OwnerDoc()->GetWindowContext() : nullptr;
512 mSourceTopWindowContext
=
513 mSourceWindowContext
? mSourceWindowContext
->TopWindowContext() : nullptr;
515 return InvokeDragSession(node
, aPrincipal
, aCsp
, aCookieJarSettings
,
516 aTransferableArray
, aActionType
,
517 nsIContentPolicy::TYPE_OTHER
);
520 //-------------------------------------------------------------------------
522 nsBaseDragService::GetCurrentSession(nsIDragSession
** aSession
) {
523 if (!aSession
) return NS_ERROR_INVALID_ARG
;
525 // "this" also implements a drag session, so say we are one but only
526 // if there is currently a drag going on.
527 if (!mSuppressLevel
&& mDoingDrag
) {
529 NS_ADDREF(*aSession
); // addRef because we're a "getter"
536 //-------------------------------------------------------------------------
538 nsBaseDragService::StartDragSession() {
540 return NS_ERROR_FAILURE
;
543 // By default dispatch drop also to content.
544 mOnlyChromeDrop
= false;
549 NS_IMETHODIMP
nsBaseDragService::StartDragSessionForTests(
550 uint32_t aAllowedEffect
) {
551 if (NS_WARN_IF(NS_FAILED(StartDragSession()))) {
552 return NS_ERROR_FAILURE
;
554 mDragAction
= aAllowedEffect
;
555 mEffectAllowedForTests
= aAllowedEffect
;
556 mSessionIsSynthesizedForTests
= true;
560 void nsBaseDragService::OpenDragPopup() {
562 nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance();
564 pm
->ShowPopupAtScreen(mDragPopup
, mScreenPosition
.x
- mImageOffset
.x
,
565 mScreenPosition
.y
- mImageOffset
.y
, false, nullptr);
570 int32_t nsBaseDragService::TakeChildProcessDragAction() {
571 // If the last event was dispatched to the child process, use the drag action
572 // assigned from it instead and return it. DRAGDROP_ACTION_UNINITIALIZED is
573 // returned otherwise.
574 int32_t retval
= DRAGDROP_ACTION_UNINITIALIZED
;
575 if (TakeDragEventDispatchedToChildProcess() &&
576 mDragActionFromChildProcess
!= DRAGDROP_ACTION_UNINITIALIZED
) {
577 retval
= mDragActionFromChildProcess
;
583 //-------------------------------------------------------------------------
585 nsBaseDragService::EndDragSession(bool aDoneDrag
, uint32_t aKeyModifiers
) {
586 if (!mDoingDrag
|| mEndingSession
) {
587 return NS_ERROR_FAILURE
;
590 mEndingSession
= true;
592 if (aDoneDrag
&& !mSuppressLevel
) {
593 FireDragEventAtSource(eDragEnd
, aKeyModifiers
);
597 nsXULPopupManager
* pm
= nsXULPopupManager::GetInstance();
599 pm
->HidePopup(mDragPopup
, {HidePopupOption::DeselectMenu
});
603 uint32_t dropEffect
= nsIDragService::DRAGDROP_ACTION_NONE
;
605 dropEffect
= mDataTransfer
->DropEffectInt();
608 for (uint32_t i
= 0; i
< mChildProcesses
.Length(); ++i
) {
609 mozilla::Unused
<< mChildProcesses
[i
]->SendEndDragSession(
610 aDoneDrag
, mUserCancelled
, mEndDragPoint
, aKeyModifiers
, dropEffect
);
611 // Continue sending input events with input priority when stopping the dnd
613 mChildProcesses
[i
]->SetInputPriorityEventEnabled(true);
615 mChildProcesses
.Clear();
617 // mDataTransfer and the items it owns are going to die anyway, but we
618 // explicitly deref the contained data here so that we don't have to wait for
619 // CC to reclaim the memory.
620 if (XRE_IsParentProcess()) {
621 DiscardInternalTransferData();
625 mSessionIsSynthesizedForTests
= false;
626 mIsDraggingTextInTextControl
= false;
627 mEffectAllowedForTests
= nsIDragService::DRAGDROP_ACTION_UNINITIALIZED
;
628 mEndingSession
= false;
631 // release the source we've been holding on to.
632 mSourceDocument
= nullptr;
633 mSourceNode
= nullptr;
634 mSourceWindowContext
= nullptr;
635 mTriggeringPrincipal
= nullptr;
637 mSelection
= nullptr;
638 mDataTransfer
= nullptr;
640 mUserCancelled
= false;
641 mDragPopup
= nullptr;
642 mDragStartData
= nullptr;
644 mImageOffset
= CSSIntPoint();
645 mScreenPosition
= CSSIntPoint();
646 mEndDragPoint
= LayoutDeviceIntPoint(0, 0);
647 mInputSource
= MouseEvent_Binding::MOZ_SOURCE_MOUSE
;
653 void nsBaseDragService::DiscardInternalTransferData() {
654 if (mDataTransfer
&& mSourceNode
) {
655 MOZ_ASSERT(mDataTransfer
);
657 DataTransferItemList
* items
= mDataTransfer
->Items();
658 for (size_t i
= 0; i
< items
->Length(); i
++) {
660 DataTransferItem
* item
= items
->IndexedGetter(i
, found
);
662 // Non-OTHER items may still be needed by JS. Skip them.
663 if (!found
|| item
->Kind() != DataTransferItem::KIND_OTHER
) {
667 nsCOMPtr
<nsIVariant
> variant
= item
->DataNoSecurityCheck();
668 nsCOMPtr
<nsIWritableVariant
> writable
= do_QueryInterface(variant
);
671 writable
->SetAsEmpty();
678 nsBaseDragService::FireDragEventAtSource(EventMessage aEventMessage
,
679 uint32_t aKeyModifiers
) {
680 if (!mSourceNode
|| !mSourceDocument
|| mSuppressLevel
) {
683 RefPtr
<PresShell
> presShell
= mSourceDocument
->GetPresShell();
688 RefPtr
<nsPresContext
> pc
= presShell
->GetPresContext();
689 nsCOMPtr
<nsIWidget
> widget
= pc
? pc
->GetRootWidget() : nullptr;
691 nsEventStatus status
= nsEventStatus_eIgnore
;
692 WidgetDragEvent
event(true, aEventMessage
, widget
);
693 event
.mFlags
.mIsSynthesizedForTests
= mSessionIsSynthesizedForTests
;
694 event
.mInputSource
= mInputSource
;
695 if (aEventMessage
== eDragEnd
) {
696 event
.mRefPoint
= mEndDragPoint
;
698 event
.mRefPoint
-= widget
->WidgetToTopLevelWidgetOffset();
700 event
.mUserCancelled
= mUserCancelled
;
702 event
.mModifiers
= aKeyModifiers
;
705 // Send the drag event to APZ, which needs to know about them to be
706 // able to accurately detect the end of a drag gesture.
707 widget
->DispatchEventToAPZOnly(&event
);
710 nsCOMPtr
<nsIContent
> content
= do_QueryInterface(mSourceNode
);
711 return presShell
->HandleDOMEventWithTarget(content
, &event
, &status
);
714 /* This is used by Windows and Mac to update the position of a popup being
715 * used as a drag image during the drag. This isn't used on GTK as it manages
716 * the drag popup itself.
719 nsBaseDragService::DragMoved(int32_t aX
, int32_t aY
) {
721 nsIFrame
* frame
= mDragPopup
->GetPrimaryFrame();
722 if (frame
&& frame
->IsMenuPopupFrame()) {
724 RoundedToInt(LayoutDeviceIntPoint(aX
, aY
) /
725 frame
->PresContext()->CSSToDevPixelScale()) -
727 static_cast<nsMenuPopupFrame
*>(frame
)->MoveTo(cssPos
, true);
734 static PresShell
* GetPresShellForContent(nsINode
* aDOMNode
) {
735 nsCOMPtr
<nsIContent
> content
= do_QueryInterface(aDOMNode
);
736 if (!content
) return nullptr;
738 RefPtr
<Document
> document
= content
->GetComposedDoc();
740 document
->FlushPendingNotifications(FlushType::Display
);
741 return document
->GetPresShell();
747 nsresult
nsBaseDragService::DrawDrag(nsINode
* aDOMNode
,
748 const Maybe
<CSSIntRegion
>& aRegion
,
749 CSSIntPoint aScreenPosition
,
750 LayoutDeviceIntRect
* aScreenDragRect
,
751 RefPtr
<SourceSurface
>* aSurface
,
752 nsPresContext
** aPresContext
) {
754 *aPresContext
= nullptr;
756 // use a default size, in case of an error.
757 aScreenDragRect
->SetRect(aScreenPosition
.x
- mImageOffset
.x
,
758 aScreenPosition
.y
- mImageOffset
.y
, 1, 1);
760 // if a drag image was specified, use that, otherwise, use the source node
761 nsCOMPtr
<nsINode
> dragNode
= mImage
? mImage
.get() : aDOMNode
;
763 // get the presshell for the node being dragged. If the drag image is not in
764 // a document or has no frame, get the presshell from the source drag node
765 PresShell
* presShell
= GetPresShellForContent(dragNode
);
766 if (!presShell
&& mImage
) {
767 presShell
= GetPresShellForContent(aDOMNode
);
770 return NS_ERROR_FAILURE
;
773 *aPresContext
= presShell
->GetPresContext();
775 if (mDragStartData
) {
777 // Just clear the surface if chrome has overridden it with an image.
780 *aSurface
= mDragStartData
->TakeVisualization(aScreenDragRect
);
783 mDragStartData
= nullptr;
787 // convert mouse position to dev pixels of the prescontext
788 const CSSIntPoint screenPosition
= aScreenPosition
- mImageOffset
;
789 const auto screenPoint
= LayoutDeviceIntPoint::Round(
790 screenPosition
* (*aPresContext
)->CSSToDevPixelScale());
791 aScreenDragRect
->MoveTo(screenPoint
.x
, screenPoint
.y
);
793 // check if drag images are disabled
794 bool enableDragImages
= Preferences::GetBool(DRAGIMAGES_PREF
, true);
796 // didn't want an image, so just set the screen rectangle to the frame size
797 if (!enableDragImages
|| !mHasImage
) {
798 // This holds a quantity in RelativeTo{presShell->GetRootFrame(),
799 // ViewportType::Layout} space.
800 nsRect presLayoutRect
;
802 // if a region was specified, set the screen rectangle to the area that
803 // the region occupies
804 presLayoutRect
= ToAppUnits(aRegion
->GetBounds(), AppUnitsPerCSSPixel());
806 // otherwise, there was no region so just set the rectangle to
807 // the size of the primary frame of the content.
808 nsCOMPtr
<nsIContent
> content
= do_QueryInterface(dragNode
);
809 if (nsIFrame
* frame
= content
->GetPrimaryFrame()) {
810 presLayoutRect
= frame
->GetBoundingClientRect();
814 LayoutDeviceRect screenVisualRect
= ViewportUtils::ToScreenRelativeVisual(
815 LayoutDeviceRect::FromAppUnits(presLayoutRect
,
816 (*aPresContext
)->AppUnitsPerDevPixel()),
818 aScreenDragRect
->SizeTo(screenVisualRect
.Width(),
819 screenVisualRect
.Height());
823 // draw the image for selections
825 LayoutDeviceIntPoint
pnt(aScreenDragRect
->TopLeft());
826 *aSurface
= presShell
->RenderSelection(
827 mSelection
, pnt
, aScreenDragRect
,
828 mImage
? RenderImageFlags::None
: RenderImageFlags::AutoScale
);
832 // if a custom image was specified, check if it is an image node and draw
833 // using the source rather than the displayed image. But if mImage isn't
834 // an image or canvas, fall through to RenderNode below.
836 nsCOMPtr
<nsIContent
> content
= do_QueryInterface(dragNode
);
837 HTMLCanvasElement
* canvas
= HTMLCanvasElement::FromNodeOrNull(content
);
839 return DrawDragForImage(*aPresContext
, nullptr, canvas
, aScreenDragRect
,
843 nsCOMPtr
<nsIImageLoadingContent
> imageLoader
= do_QueryInterface(dragNode
);
844 // for image nodes, create the drag image from the actual image data
846 return DrawDragForImage(*aPresContext
, imageLoader
, nullptr,
847 aScreenDragRect
, aSurface
);
850 // If the image is a popup, use that as the image. This allows custom drag
851 // images that can change during the drag, but means that any platform
852 // default image handling won't occur.
853 // XXXndeakin this should be chrome-only
855 nsIFrame
* frame
= content
->GetPrimaryFrame();
856 if (frame
&& frame
->IsMenuPopupFrame()) {
857 mDragPopup
= content
;
862 // otherwise, just draw the node
863 RenderImageFlags renderFlags
=
864 mImage
? RenderImageFlags::None
: RenderImageFlags::AutoScale
;
865 if (renderFlags
!= RenderImageFlags::None
) {
866 // check if the dragged node itself is an img element
867 if (dragNode
->NodeName().LowerCaseEqualsLiteral("img")) {
868 renderFlags
= renderFlags
| RenderImageFlags::IsImage
;
870 nsINodeList
* childList
= dragNode
->ChildNodes();
871 uint32_t length
= childList
->Length();
872 // check every childnode for being an img element
873 // XXXbz why don't we need to check descendants recursively?
874 for (uint32_t count
= 0; count
< length
; ++count
) {
875 if (childList
->Item(count
)->NodeName().LowerCaseEqualsLiteral(
877 // if the dragnode contains an image, set RenderImageFlags::IsImage
879 renderFlags
= renderFlags
| RenderImageFlags::IsImage
;
885 LayoutDeviceIntPoint
pnt(aScreenDragRect
->TopLeft());
886 *aSurface
= presShell
->RenderNode(dragNode
, aRegion
, pnt
, aScreenDragRect
,
890 // If an image was specified, reset the position from the offset that was
893 aScreenDragRect
->MoveTo(screenPoint
.x
, screenPoint
.y
);
899 nsresult
nsBaseDragService::DrawDragForImage(
900 nsPresContext
* aPresContext
, nsIImageLoadingContent
* aImageLoader
,
901 HTMLCanvasElement
* aCanvas
, LayoutDeviceIntRect
* aScreenDragRect
,
902 RefPtr
<SourceSurface
>* aSurface
) {
903 nsCOMPtr
<imgIContainer
> imgContainer
;
905 nsCOMPtr
<imgIRequest
> imgRequest
;
906 nsresult rv
= aImageLoader
->GetRequest(
907 nsIImageLoadingContent::CURRENT_REQUEST
, getter_AddRefs(imgRequest
));
908 NS_ENSURE_SUCCESS(rv
, rv
);
909 if (!imgRequest
) return NS_ERROR_NOT_AVAILABLE
;
911 rv
= imgRequest
->GetImage(getter_AddRefs(imgContainer
));
912 NS_ENSURE_SUCCESS(rv
, rv
);
913 if (!imgContainer
) return NS_ERROR_NOT_AVAILABLE
;
915 // use the size of the image as the size of the drag image
916 int32_t imageWidth
, imageHeight
;
917 rv
= imgContainer
->GetWidth(&imageWidth
);
918 NS_ENSURE_SUCCESS(rv
, rv
);
920 rv
= imgContainer
->GetHeight(&imageHeight
);
921 NS_ENSURE_SUCCESS(rv
, rv
);
923 aScreenDragRect
->SizeTo(aPresContext
->CSSPixelsToDevPixels(imageWidth
),
924 aPresContext
->CSSPixelsToDevPixels(imageHeight
));
926 // XXX The canvas size should be converted to dev pixels.
927 NS_ASSERTION(aCanvas
, "both image and canvas are null");
928 nsIntSize sz
= aCanvas
->GetSize();
929 aScreenDragRect
->SizeTo(sz
.width
, sz
.height
);
933 destSize
.width
= aScreenDragRect
->Width();
934 destSize
.height
= aScreenDragRect
->Height();
935 if (destSize
.width
== 0 || destSize
.height
== 0) return NS_ERROR_FAILURE
;
937 nsresult result
= NS_OK
;
939 RefPtr
<DrawTarget
> dt
=
940 gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
941 destSize
, SurfaceFormat::B8G8R8A8
);
942 if (!dt
|| !dt
->IsValid()) return NS_ERROR_FAILURE
;
946 ImgDrawResult res
= imgContainer
->Draw(
947 &ctx
, destSize
, ImageRegion::Create(destSize
),
948 imgIContainer::FRAME_CURRENT
, SamplingFilter::GOOD
, SVGImageContext(),
949 imgIContainer::FLAG_SYNC_DECODE
, 1.0);
950 if (res
== ImgDrawResult::BAD_IMAGE
|| res
== ImgDrawResult::BAD_ARGS
||
951 res
== ImgDrawResult::NOT_SUPPORTED
) {
952 return NS_ERROR_FAILURE
;
954 *aSurface
= dt
->Snapshot();
956 *aSurface
= aCanvas
->GetSurfaceSnapshot();
963 nsBaseDragService::Suppress() {
964 EndDragSession(false, 0);
970 nsBaseDragService::Unsuppress() {
976 nsBaseDragService::UserCancelled() {
977 mUserCancelled
= true;
982 nsBaseDragService::UpdateDragEffect() {
983 mDragActionFromChildProcess
= mDragAction
;
988 nsBaseDragService::UpdateDragImage(nsINode
* aImage
, int32_t aImageX
,
990 // Don't change the image if this is a drag from another source or if there
992 if (!mSourceNode
|| mDragPopup
) return NS_OK
;
995 mImageOffset
= CSSIntPoint(aImageX
, aImageY
);
1000 nsBaseDragService::DragEventDispatchedToChildProcess() {
1001 mDragEventDispatchedToChildProcess
= true;
1005 bool nsBaseDragService::MaybeAddChildProcess(
1006 mozilla::dom::ContentParent
* aChild
) {
1007 if (!mChildProcesses
.Contains(aChild
)) {
1008 mChildProcesses
.AppendElement(aChild
);
1014 bool nsBaseDragService::RemoveAllChildProcesses() {
1015 for (uint32_t c
= 0; c
< mChildProcesses
.Length(); c
++) {
1016 mozilla::Unused
<< mChildProcesses
[c
]->SendEndDragSession(
1017 true, false, LayoutDeviceIntPoint(), 0,
1018 nsIDragService::DRAGDROP_ACTION_NONE
);
1020 mChildProcesses
.Clear();
1025 nsBaseDragService::MaybeEditorDeletedSourceNode(Element
* aEditingHost
) {
1026 // If builtin editor of Blink and WebKit deletes the source node,they retarget
1027 // the source node to the editing host.
1028 // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/page/drag_controller.cc;l=724;drc=d9ba13b8cd8ac0faed7afc3d1f7e4b67ebac2a0b
1029 // That allows editor apps listens to "dragend" event in editing host or its
1030 // ancestors. Therefore, we should follow them for compatibility.
1031 if (mSourceNode
&& !mSourceNode
->IsInComposedDoc()) {
1032 mSourceNode
= aEditingHost
;