Bug 1791155 [wpt PR 35927] - Move webkit-mask-box-enumeration.html into compat/,...
[gecko.git] / widget / nsBaseDragService.cpp
blob2dbb28b3601d7dd2d0e9b353b9e7ad75d4f0d271
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"
11 #include "nsSize.h"
12 #include "nsXPCOM.h"
13 #include "nsCOMPtr.h"
14 #include "nsIInterfaceRequestorUtils.h"
15 #include "nsIFrame.h"
16 #include "nsFrameLoaderOwner.h"
17 #include "nsIContent.h"
18 #include "nsViewManager.h"
19 #include "nsINode.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"
26 #include "nsRegion.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"
52 #include <algorithm>
54 using namespace mozilla;
55 using namespace mozilla::dom;
56 using namespace mozilla::gfx;
57 using namespace mozilla::image;
59 #define DRAGIMAGES_PREF "nglayout.enable_drag_images"
61 nsBaseDragService::nsBaseDragService()
62 : mCanDrop(false),
63 mOnlyChromeDrop(false),
64 mDoingDrag(false),
65 mSessionIsSynthesizedForTests(false),
66 mIsDraggingTextInTextControl(false),
67 mEndingSession(false),
68 mHasImage(false),
69 mUserCancelled(false),
70 mDragEventDispatchedToChildProcess(false),
71 mDragAction(DRAGDROP_ACTION_NONE),
72 mDragActionFromChildProcess(DRAGDROP_ACTION_UNINITIALIZED),
73 mEffectAllowedForTests(DRAGDROP_ACTION_UNINITIALIZED),
74 mContentPolicyType(nsIContentPolicy::TYPE_OTHER),
75 mSuppressLevel(0),
76 mInputSource(MouseEvent_Binding::MOZ_SOURCE_MOUSE) {}
78 nsBaseDragService::~nsBaseDragService() = default;
80 NS_IMPL_ISUPPORTS(nsBaseDragService, nsIDragService, nsIDragSession)
82 //---------------------------------------------------------
83 NS_IMETHODIMP
84 nsBaseDragService::SetCanDrop(bool aCanDrop) {
85 mCanDrop = aCanDrop;
86 return NS_OK;
89 //---------------------------------------------------------
90 NS_IMETHODIMP
91 nsBaseDragService::GetCanDrop(bool* aCanDrop) {
92 *aCanDrop = mCanDrop;
93 return NS_OK;
95 //---------------------------------------------------------
96 NS_IMETHODIMP
97 nsBaseDragService::SetOnlyChromeDrop(bool aOnlyChrome) {
98 mOnlyChromeDrop = aOnlyChrome;
99 return NS_OK;
102 //---------------------------------------------------------
103 NS_IMETHODIMP
104 nsBaseDragService::GetOnlyChromeDrop(bool* aOnlyChrome) {
105 *aOnlyChrome = mOnlyChromeDrop;
106 return NS_OK;
109 //---------------------------------------------------------
110 NS_IMETHODIMP
111 nsBaseDragService::SetDragAction(uint32_t anAction) {
112 mDragAction = anAction;
113 return NS_OK;
116 //---------------------------------------------------------
117 NS_IMETHODIMP
118 nsBaseDragService::GetDragAction(uint32_t* anAction) {
119 *anAction = mDragAction;
120 return NS_OK;
123 //-------------------------------------------------------------------------
125 NS_IMETHODIMP
126 nsBaseDragService::GetNumDropItems(uint32_t* aNumItems) {
127 *aNumItems = 0;
128 return NS_ERROR_FAILURE;
132 // GetSourceWindowContext
134 // Returns the window context where the drag was initiated. This will be
135 // nullptr if the drag began outside of our application.
137 NS_IMETHODIMP
138 nsBaseDragService::GetSourceWindowContext(
139 WindowContext** aSourceWindowContext) {
140 *aSourceWindowContext = mSourceWindowContext.get();
141 NS_IF_ADDREF(*aSourceWindowContext);
142 return NS_OK;
145 NS_IMETHODIMP
146 nsBaseDragService::SetSourceWindowContext(WindowContext* aSourceWindowContext) {
147 // This should only be called in a child process.
148 MOZ_ASSERT(!XRE_IsParentProcess());
149 mSourceWindowContext = aSourceWindowContext;
150 return NS_OK;
154 // GetSourceNode
156 // Returns the DOM node where the drag was initiated. This will be
157 // nullptr if the drag began outside of our application.
159 NS_IMETHODIMP
160 nsBaseDragService::GetSourceNode(nsINode** aSourceNode) {
161 *aSourceNode = do_AddRef(mSourceNode).take();
162 return NS_OK;
165 void nsBaseDragService::UpdateSource(nsINode* aNewSourceNode,
166 Selection* aNewSelection) {
167 MOZ_ASSERT(mSourceNode);
168 MOZ_ASSERT(aNewSourceNode);
169 MOZ_ASSERT(mSourceNode->IsInNativeAnonymousSubtree() ||
170 aNewSourceNode->IsInNativeAnonymousSubtree());
171 MOZ_ASSERT(mSourceDocument == aNewSourceNode->OwnerDoc());
172 mSourceNode = aNewSourceNode;
173 // Don't set mSelection if the session was invoked without selection or
174 // making it becomes nullptr. The latter occurs when the old frame is
175 // being destroyed.
176 if (mSelection && aNewSelection) {
177 // XXX If the dragging image is created once (e.g., at drag start), the
178 // image won't be updated unless we notify `DrawDrag` callers.
179 // However, it must be okay for now to keep using older image of
180 // Selection.
181 mSelection = aNewSelection;
185 NS_IMETHODIMP
186 nsBaseDragService::GetTriggeringPrincipal(nsIPrincipal** aPrincipal) {
187 NS_IF_ADDREF(*aPrincipal = mTriggeringPrincipal);
188 return NS_OK;
191 NS_IMETHODIMP
192 nsBaseDragService::SetTriggeringPrincipal(nsIPrincipal* aPrincipal) {
193 mTriggeringPrincipal = aPrincipal;
194 return NS_OK;
197 NS_IMETHODIMP
198 nsBaseDragService::GetCsp(nsIContentSecurityPolicy** aCsp) {
199 NS_IF_ADDREF(*aCsp = mCsp);
200 return NS_OK;
203 NS_IMETHODIMP
204 nsBaseDragService::SetCsp(nsIContentSecurityPolicy* aCsp) {
205 mCsp = aCsp;
206 return NS_OK;
209 //-------------------------------------------------------------------------
211 NS_IMETHODIMP
212 nsBaseDragService::GetData(nsITransferable* aTransferable,
213 uint32_t aItemIndex) {
214 return NS_ERROR_FAILURE;
217 //-------------------------------------------------------------------------
218 NS_IMETHODIMP
219 nsBaseDragService::IsDataFlavorSupported(const char* aDataFlavor,
220 bool* _retval) {
221 return NS_ERROR_FAILURE;
224 NS_IMETHODIMP
225 nsBaseDragService::GetDataTransferXPCOM(DataTransfer** aDataTransfer) {
226 *aDataTransfer = mDataTransfer;
227 NS_IF_ADDREF(*aDataTransfer);
228 return NS_OK;
231 NS_IMETHODIMP
232 nsBaseDragService::SetDataTransferXPCOM(DataTransfer* aDataTransfer) {
233 NS_ENSURE_STATE(aDataTransfer);
234 mDataTransfer = aDataTransfer;
235 return NS_OK;
238 DataTransfer* nsBaseDragService::GetDataTransfer() { return mDataTransfer; }
240 void nsBaseDragService::SetDataTransfer(DataTransfer* aDataTransfer) {
241 mDataTransfer = aDataTransfer;
244 bool nsBaseDragService::IsSynthesizedForTests() {
245 return mSessionIsSynthesizedForTests;
248 bool nsBaseDragService::IsDraggingTextInTextControl() {
249 return mIsDraggingTextInTextControl;
252 uint32_t nsBaseDragService::GetEffectAllowedForTests() {
253 MOZ_ASSERT(mSessionIsSynthesizedForTests);
254 return mEffectAllowedForTests;
257 NS_IMETHODIMP nsBaseDragService::SetDragEndPointForTests(int32_t aScreenX,
258 int32_t aScreenY) {
259 MOZ_ASSERT(mDoingDrag);
260 MOZ_ASSERT(mSourceDocument);
261 MOZ_ASSERT(mSessionIsSynthesizedForTests);
263 if (!mDoingDrag || !mSourceDocument || !mSessionIsSynthesizedForTests) {
264 return NS_ERROR_FAILURE;
266 nsPresContext* pc = mSourceDocument->GetPresContext();
267 if (NS_WARN_IF(!pc)) {
268 return NS_ERROR_FAILURE;
270 auto p = LayoutDeviceIntPoint::Round(CSSIntPoint(aScreenX, aScreenY) *
271 pc->CSSToDevPixelScale());
272 // p is screen-relative, and we want them to be top-level-widget-relative.
273 if (nsCOMPtr<nsIWidget> widget = pc->GetRootWidget()) {
274 p -= widget->WidgetToScreenOffset();
275 p += widget->WidgetToTopLevelWidgetOffset();
277 SetDragEndPoint(p);
278 return NS_OK;
281 //-------------------------------------------------------------------------
282 NS_IMETHODIMP
283 nsBaseDragService::InvokeDragSession(
284 nsINode* aDOMNode, nsIPrincipal* aPrincipal, nsIContentSecurityPolicy* aCsp,
285 nsICookieJarSettings* aCookieJarSettings, nsIArray* aTransferableArray,
286 uint32_t aActionType,
287 nsContentPolicyType aContentPolicyType = nsIContentPolicy::TYPE_OTHER) {
288 AUTO_PROFILER_LABEL("nsBaseDragService::InvokeDragSession", OTHER);
290 NS_ENSURE_TRUE(aDOMNode, NS_ERROR_INVALID_ARG);
291 NS_ENSURE_TRUE(mSuppressLevel == 0, NS_ERROR_FAILURE);
293 // stash the document of the dom node
294 mSourceDocument = aDOMNode->OwnerDoc();
295 mTriggeringPrincipal = aPrincipal;
296 mCsp = aCsp;
297 mSourceNode = aDOMNode;
298 mIsDraggingTextInTextControl =
299 mSourceNode->IsInNativeAnonymousSubtree() &&
300 TextControlElement::FromNodeOrNull(
301 mSourceNode->GetClosestNativeAnonymousSubtreeRootParent());
302 mContentPolicyType = aContentPolicyType;
303 mEndDragPoint = LayoutDeviceIntPoint(0, 0);
305 // When the mouse goes down, the selection code starts a mouse
306 // capture. However, this gets in the way of determining drag
307 // feedback for things like trees because the event coordinates
308 // are in the wrong coord system, so turn off mouse capture.
309 PresShell::ClearMouseCapture();
311 if (mSessionIsSynthesizedForTests) {
312 mDoingDrag = true;
313 mDragAction = aActionType;
314 mEffectAllowedForTests = aActionType;
315 return NS_OK;
318 // If you're hitting this, a test is causing the browser to attempt to enter
319 // the drag-drop native nested event loop, which will put the browser in a
320 // state that won't run tests properly until there's manual intervention
321 // to exit the drag-drop loop (either by moving the mouse or hitting escape),
322 // which can't be done from script since we're in the nested loop.
324 // The best way to avoid this is to catch the dragstart event on the item
325 // being dragged, and then to call preventDefault() and stopPropagating() on
326 // it.
327 if (XRE_IsParentProcess()) {
328 MOZ_ASSERT(
329 !xpc::IsInAutomation(),
330 "About to start drag-drop native loop on which will prevent later "
331 "tests from running properly.");
334 uint32_t length = 0;
335 mozilla::Unused << aTransferableArray->GetLength(&length);
336 if (!length) {
337 nsCOMPtr<nsIMutableArray> mutableArray =
338 do_QueryInterface(aTransferableArray);
339 if (mutableArray) {
340 // In order to be able trigger dnd, we need to have some transferable
341 // object.
342 nsCOMPtr<nsITransferable> trans =
343 do_CreateInstance("@mozilla.org/widget/transferable;1");
344 trans->Init(nullptr);
345 trans->SetRequestingPrincipal(mSourceNode->NodePrincipal());
346 trans->SetContentPolicyType(mContentPolicyType);
347 trans->SetCookieJarSettings(aCookieJarSettings);
348 mutableArray->AppendElement(trans);
350 } else {
351 for (uint32_t i = 0; i < length; ++i) {
352 nsCOMPtr<nsITransferable> trans =
353 do_QueryElementAt(aTransferableArray, i);
354 if (trans) {
355 // Set the requestingPrincipal on the transferable.
356 trans->SetRequestingPrincipal(mSourceNode->NodePrincipal());
357 trans->SetContentPolicyType(mContentPolicyType);
358 trans->SetCookieJarSettings(aCookieJarSettings);
363 nsresult rv = InvokeDragSessionImpl(aTransferableArray, mRegion, aActionType);
365 if (NS_FAILED(rv)) {
366 // Set mDoingDrag so that EndDragSession cleans up and sends the dragend
367 // event after the aborted drag.
368 mDoingDrag = true;
369 EndDragSession(true, 0);
372 return rv;
375 NS_IMETHODIMP
376 nsBaseDragService::InvokeDragSessionWithImage(
377 nsINode* aDOMNode, nsIPrincipal* aPrincipal, nsIContentSecurityPolicy* aCsp,
378 nsICookieJarSettings* aCookieJarSettings, nsIArray* aTransferableArray,
379 uint32_t aActionType, nsINode* aImage, int32_t aImageX, int32_t aImageY,
380 DragEvent* aDragEvent, DataTransfer* aDataTransfer) {
381 NS_ENSURE_TRUE(aDragEvent, NS_ERROR_NULL_POINTER);
382 NS_ENSURE_TRUE(aDataTransfer, NS_ERROR_NULL_POINTER);
383 NS_ENSURE_TRUE(mSuppressLevel == 0, NS_ERROR_FAILURE);
385 mSessionIsSynthesizedForTests =
386 aDragEvent->WidgetEventPtr()->mFlags.mIsSynthesizedForTests;
387 mDataTransfer = aDataTransfer;
388 mSelection = nullptr;
389 mHasImage = true;
390 mDragPopup = nullptr;
391 mImage = aImage;
392 mImageOffset = CSSIntPoint(aImageX, aImageY);
393 mDragStartData = nullptr;
394 mSourceWindowContext =
395 aDOMNode ? aDOMNode->OwnerDoc()->GetWindowContext() : nullptr;
397 mScreenPosition = aDragEvent->ScreenPoint(CallerType::System);
398 mInputSource = aDragEvent->MozInputSource();
400 // If dragging within a XUL tree and no custom drag image was
401 // set, the region argument to InvokeDragSessionWithImage needs
402 // to be set to the area encompassing the selected rows of the
403 // tree to ensure that the drag feedback gets clipped to those
404 // rows. For other content, region should be null.
405 mRegion = Nothing();
406 if (aDOMNode && aDOMNode->IsContent() && !aImage) {
407 if (aDOMNode->NodeInfo()->Equals(nsGkAtoms::treechildren,
408 kNameSpaceID_XUL)) {
409 nsTreeBodyFrame* treeBody =
410 do_QueryFrame(aDOMNode->AsContent()->GetPrimaryFrame());
411 if (treeBody) {
412 mRegion = treeBody->GetSelectionRegion();
417 nsresult rv = InvokeDragSession(
418 aDOMNode, aPrincipal, aCsp, aCookieJarSettings, aTransferableArray,
419 aActionType, nsIContentPolicy::TYPE_INTERNAL_IMAGE);
420 mRegion = Nothing();
421 return rv;
424 NS_IMETHODIMP
425 nsBaseDragService::InvokeDragSessionWithRemoteImage(
426 nsINode* aDOMNode, nsIPrincipal* aPrincipal, nsIContentSecurityPolicy* aCsp,
427 nsICookieJarSettings* aCookieJarSettings, nsIArray* aTransferableArray,
428 uint32_t aActionType, RemoteDragStartData* aDragStartData,
429 DragEvent* aDragEvent, DataTransfer* aDataTransfer) {
430 NS_ENSURE_TRUE(aDragEvent, NS_ERROR_NULL_POINTER);
431 NS_ENSURE_TRUE(aDataTransfer, NS_ERROR_NULL_POINTER);
432 NS_ENSURE_TRUE(mSuppressLevel == 0, NS_ERROR_FAILURE);
434 mSessionIsSynthesizedForTests =
435 aDragEvent->WidgetEventPtr()->mFlags.mIsSynthesizedForTests;
436 mDataTransfer = aDataTransfer;
437 mSelection = nullptr;
438 mHasImage = true;
439 mDragPopup = nullptr;
440 mImage = nullptr;
441 mDragStartData = aDragStartData;
442 mImageOffset = CSSIntPoint(0, 0);
443 mSourceWindowContext = mDragStartData->GetSourceWindowContext();
445 mScreenPosition = aDragEvent->ScreenPoint(CallerType::System);
446 mInputSource = aDragEvent->MozInputSource();
448 nsresult rv = InvokeDragSession(
449 aDOMNode, aPrincipal, aCsp, aCookieJarSettings, aTransferableArray,
450 aActionType, nsIContentPolicy::TYPE_INTERNAL_IMAGE);
451 mRegion = Nothing();
452 return rv;
455 NS_IMETHODIMP
456 nsBaseDragService::InvokeDragSessionWithSelection(
457 Selection* aSelection, nsIPrincipal* aPrincipal,
458 nsIContentSecurityPolicy* aCsp, nsICookieJarSettings* aCookieJarSettings,
459 nsIArray* aTransferableArray, uint32_t aActionType, DragEvent* aDragEvent,
460 DataTransfer* aDataTransfer) {
461 NS_ENSURE_TRUE(aSelection, NS_ERROR_NULL_POINTER);
462 NS_ENSURE_TRUE(aDragEvent, NS_ERROR_NULL_POINTER);
463 NS_ENSURE_TRUE(mSuppressLevel == 0, NS_ERROR_FAILURE);
465 mSessionIsSynthesizedForTests =
466 aDragEvent->WidgetEventPtr()->mFlags.mIsSynthesizedForTests;
467 mDataTransfer = aDataTransfer;
468 mSelection = aSelection;
469 mHasImage = true;
470 mDragPopup = nullptr;
471 mImage = nullptr;
472 mImageOffset = CSSIntPoint();
473 mDragStartData = nullptr;
474 mRegion = Nothing();
476 mScreenPosition.x = aDragEvent->ScreenX(CallerType::System);
477 mScreenPosition.y = aDragEvent->ScreenY(CallerType::System);
478 mInputSource = aDragEvent->MozInputSource();
480 // just get the focused node from the selection
481 // XXXndeakin this should actually be the deepest node that contains both
482 // endpoints of the selection
483 nsCOMPtr<nsINode> node = aSelection->GetFocusNode();
484 mSourceWindowContext = node ? node->OwnerDoc()->GetWindowContext() : nullptr;
486 return InvokeDragSession(node, aPrincipal, aCsp, aCookieJarSettings,
487 aTransferableArray, aActionType,
488 nsIContentPolicy::TYPE_OTHER);
491 //-------------------------------------------------------------------------
492 NS_IMETHODIMP
493 nsBaseDragService::GetCurrentSession(nsIDragSession** aSession) {
494 if (!aSession) return NS_ERROR_INVALID_ARG;
496 // "this" also implements a drag session, so say we are one but only
497 // if there is currently a drag going on.
498 if (!mSuppressLevel && mDoingDrag) {
499 *aSession = this;
500 NS_ADDREF(*aSession); // addRef because we're a "getter"
501 } else
502 *aSession = nullptr;
504 return NS_OK;
507 //-------------------------------------------------------------------------
508 NS_IMETHODIMP
509 nsBaseDragService::StartDragSession() {
510 if (mDoingDrag) {
511 return NS_ERROR_FAILURE;
513 mDoingDrag = true;
514 // By default dispatch drop also to content.
515 mOnlyChromeDrop = false;
517 return NS_OK;
520 NS_IMETHODIMP nsBaseDragService::StartDragSessionForTests(
521 uint32_t aAllowedEffect) {
522 if (NS_WARN_IF(NS_FAILED(StartDragSession()))) {
523 return NS_ERROR_FAILURE;
525 mDragAction = aAllowedEffect;
526 mEffectAllowedForTests = aAllowedEffect;
527 mSessionIsSynthesizedForTests = true;
528 return NS_OK;
531 void nsBaseDragService::OpenDragPopup() {
532 if (mDragPopup) {
533 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
534 if (pm) {
535 pm->ShowPopupAtScreen(mDragPopup, mScreenPosition.x - mImageOffset.x,
536 mScreenPosition.y - mImageOffset.y, false, nullptr);
541 int32_t nsBaseDragService::TakeChildProcessDragAction() {
542 // If the last event was dispatched to the child process, use the drag action
543 // assigned from it instead and return it. DRAGDROP_ACTION_UNINITIALIZED is
544 // returned otherwise.
545 int32_t retval = DRAGDROP_ACTION_UNINITIALIZED;
546 if (TakeDragEventDispatchedToChildProcess() &&
547 mDragActionFromChildProcess != DRAGDROP_ACTION_UNINITIALIZED) {
548 retval = mDragActionFromChildProcess;
551 return retval;
554 //-------------------------------------------------------------------------
555 NS_IMETHODIMP
556 nsBaseDragService::EndDragSession(bool aDoneDrag, uint32_t aKeyModifiers) {
557 if (!mDoingDrag || mEndingSession) {
558 return NS_ERROR_FAILURE;
561 mEndingSession = true;
563 if (aDoneDrag && !mSuppressLevel) {
564 FireDragEventAtSource(eDragEnd, aKeyModifiers);
567 if (mDragPopup) {
568 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
569 if (pm) {
570 pm->HidePopup(mDragPopup, false, true, false, false);
574 uint32_t dropEffect = nsIDragService::DRAGDROP_ACTION_NONE;
575 if (mDataTransfer) {
576 dropEffect = mDataTransfer->DropEffectInt();
579 for (uint32_t i = 0; i < mChildProcesses.Length(); ++i) {
580 mozilla::Unused << mChildProcesses[i]->SendEndDragSession(
581 aDoneDrag, mUserCancelled, mEndDragPoint, aKeyModifiers, dropEffect);
582 // Continue sending input events with input priority when stopping the dnd
583 // session.
584 mChildProcesses[i]->SetInputPriorityEventEnabled(true);
586 mChildProcesses.Clear();
588 // mDataTransfer and the items it owns are going to die anyway, but we
589 // explicitly deref the contained data here so that we don't have to wait for
590 // CC to reclaim the memory.
591 if (XRE_IsParentProcess()) {
592 DiscardInternalTransferData();
595 mDoingDrag = false;
596 mSessionIsSynthesizedForTests = false;
597 mIsDraggingTextInTextControl = false;
598 mEffectAllowedForTests = nsIDragService::DRAGDROP_ACTION_UNINITIALIZED;
599 mEndingSession = false;
600 mCanDrop = false;
602 // release the source we've been holding on to.
603 mSourceDocument = nullptr;
604 mSourceNode = nullptr;
605 mSourceWindowContext = nullptr;
606 mTriggeringPrincipal = nullptr;
607 mCsp = nullptr;
608 mSelection = nullptr;
609 mDataTransfer = nullptr;
610 mHasImage = false;
611 mUserCancelled = false;
612 mDragPopup = nullptr;
613 mDragStartData = nullptr;
614 mImage = nullptr;
615 mImageOffset = CSSIntPoint();
616 mScreenPosition = CSSIntPoint();
617 mEndDragPoint = LayoutDeviceIntPoint(0, 0);
618 mInputSource = MouseEvent_Binding::MOZ_SOURCE_MOUSE;
619 mRegion = Nothing();
621 return NS_OK;
624 void nsBaseDragService::DiscardInternalTransferData() {
625 if (mDataTransfer && mSourceNode) {
626 MOZ_ASSERT(mDataTransfer);
628 DataTransferItemList* items = mDataTransfer->Items();
629 for (size_t i = 0; i < items->Length(); i++) {
630 bool found;
631 DataTransferItem* item = items->IndexedGetter(i, found);
633 // Non-OTHER items may still be needed by JS. Skip them.
634 if (!found || item->Kind() != DataTransferItem::KIND_OTHER) {
635 continue;
638 nsCOMPtr<nsIVariant> variant = item->DataNoSecurityCheck();
639 nsCOMPtr<nsIWritableVariant> writable = do_QueryInterface(variant);
641 if (writable) {
642 writable->SetAsEmpty();
648 NS_IMETHODIMP
649 nsBaseDragService::FireDragEventAtSource(EventMessage aEventMessage,
650 uint32_t aKeyModifiers) {
651 if (!mSourceNode || !mSourceDocument || mSuppressLevel) {
652 return NS_OK;
654 RefPtr<PresShell> presShell = mSourceDocument->GetPresShell();
655 if (!presShell) {
656 return NS_OK;
659 RefPtr<nsPresContext> pc = presShell->GetPresContext();
660 nsCOMPtr<nsIWidget> widget = pc ? pc->GetRootWidget() : nullptr;
662 nsEventStatus status = nsEventStatus_eIgnore;
663 WidgetDragEvent event(true, aEventMessage, widget);
664 event.mFlags.mIsSynthesizedForTests = mSessionIsSynthesizedForTests;
665 event.mInputSource = mInputSource;
666 if (aEventMessage == eDragEnd) {
667 event.mRefPoint = mEndDragPoint;
668 if (widget) {
669 event.mRefPoint -= widget->WidgetToTopLevelWidgetOffset();
671 event.mUserCancelled = mUserCancelled;
673 event.mModifiers = aKeyModifiers;
675 if (widget) {
676 // Send the drag event to APZ, which needs to know about them to be
677 // able to accurately detect the end of a drag gesture.
678 widget->DispatchEventToAPZOnly(&event);
681 nsCOMPtr<nsIContent> content = do_QueryInterface(mSourceNode);
682 return presShell->HandleDOMEventWithTarget(content, &event, &status);
685 /* This is used by Windows and Mac to update the position of a popup being
686 * used as a drag image during the drag. This isn't used on GTK as it manages
687 * the drag popup itself.
689 NS_IMETHODIMP
690 nsBaseDragService::DragMoved(int32_t aX, int32_t aY) {
691 if (mDragPopup) {
692 nsIFrame* frame = mDragPopup->GetPrimaryFrame();
693 if (frame && frame->IsMenuPopupFrame()) {
694 CSSIntPoint cssPos =
695 RoundedToInt(LayoutDeviceIntPoint(aX, aY) /
696 frame->PresContext()->CSSToDevPixelScale()) -
697 mImageOffset;
698 static_cast<nsMenuPopupFrame*>(frame)->MoveTo(cssPos, true);
702 return NS_OK;
705 static PresShell* GetPresShellForContent(nsINode* aDOMNode) {
706 nsCOMPtr<nsIContent> content = do_QueryInterface(aDOMNode);
707 if (!content) return nullptr;
709 RefPtr<Document> document = content->GetComposedDoc();
710 if (document) {
711 document->FlushPendingNotifications(FlushType::Display);
712 return document->GetPresShell();
715 return nullptr;
718 nsresult nsBaseDragService::DrawDrag(nsINode* aDOMNode,
719 const Maybe<CSSIntRegion>& aRegion,
720 CSSIntPoint aScreenPosition,
721 LayoutDeviceIntRect* aScreenDragRect,
722 RefPtr<SourceSurface>* aSurface,
723 nsPresContext** aPresContext) {
724 *aSurface = nullptr;
725 *aPresContext = nullptr;
727 // use a default size, in case of an error.
728 aScreenDragRect->SetRect(aScreenPosition.x - mImageOffset.x,
729 aScreenPosition.y - mImageOffset.y, 1, 1);
731 // if a drag image was specified, use that, otherwise, use the source node
732 nsCOMPtr<nsINode> dragNode = mImage ? mImage.get() : aDOMNode;
734 // get the presshell for the node being dragged. If the drag image is not in
735 // a document or has no frame, get the presshell from the source drag node
736 PresShell* presShell = GetPresShellForContent(dragNode);
737 if (!presShell && mImage) {
738 presShell = GetPresShellForContent(aDOMNode);
740 if (!presShell) {
741 return NS_ERROR_FAILURE;
744 *aPresContext = presShell->GetPresContext();
746 if (mDragStartData) {
747 if (mImage) {
748 // Just clear the surface if chrome has overridden it with an image.
749 *aSurface = nullptr;
750 } else {
751 *aSurface = mDragStartData->TakeVisualization(aScreenDragRect);
754 mDragStartData = nullptr;
755 return NS_OK;
758 // convert mouse position to dev pixels of the prescontext
759 const CSSIntPoint screenPosition = aScreenPosition - mImageOffset;
760 const auto screenPoint = LayoutDeviceIntPoint::Round(
761 screenPosition * (*aPresContext)->CSSToDevPixelScale());
762 aScreenDragRect->MoveTo(screenPoint.x, screenPoint.y);
764 // check if drag images are disabled
765 bool enableDragImages = Preferences::GetBool(DRAGIMAGES_PREF, true);
767 // didn't want an image, so just set the screen rectangle to the frame size
768 if (!enableDragImages || !mHasImage) {
769 // This holds a quantity in RelativeTo{presShell->GetRootFrame(),
770 // ViewportType::Layout} space.
771 nsRect presLayoutRect;
772 if (aRegion) {
773 // if a region was specified, set the screen rectangle to the area that
774 // the region occupies
775 presLayoutRect = ToAppUnits(aRegion->GetBounds(), AppUnitsPerCSSPixel());
776 } else {
777 // otherwise, there was no region so just set the rectangle to
778 // the size of the primary frame of the content.
779 nsCOMPtr<nsIContent> content = do_QueryInterface(dragNode);
780 if (nsIFrame* frame = content->GetPrimaryFrame()) {
781 presLayoutRect = frame->GetBoundingClientRect();
785 LayoutDeviceRect screenVisualRect = ViewportUtils::ToScreenRelativeVisual(
786 LayoutDeviceRect::FromAppUnits(presLayoutRect,
787 (*aPresContext)->AppUnitsPerDevPixel()),
788 *aPresContext);
789 aScreenDragRect->SizeTo(screenVisualRect.Width(),
790 screenVisualRect.Height());
791 return NS_OK;
794 // draw the image for selections
795 if (mSelection) {
796 LayoutDeviceIntPoint pnt(aScreenDragRect->TopLeft());
797 *aSurface = presShell->RenderSelection(
798 mSelection, pnt, aScreenDragRect,
799 mImage ? RenderImageFlags::None : RenderImageFlags::AutoScale);
800 return NS_OK;
803 // if a custom image was specified, check if it is an image node and draw
804 // using the source rather than the displayed image. But if mImage isn't
805 // an image or canvas, fall through to RenderNode below.
806 if (mImage) {
807 nsCOMPtr<nsIContent> content = do_QueryInterface(dragNode);
808 HTMLCanvasElement* canvas = HTMLCanvasElement::FromNodeOrNull(content);
809 if (canvas) {
810 return DrawDragForImage(*aPresContext, nullptr, canvas, aScreenDragRect,
811 aSurface);
814 nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(dragNode);
815 // for image nodes, create the drag image from the actual image data
816 if (imageLoader) {
817 return DrawDragForImage(*aPresContext, imageLoader, nullptr,
818 aScreenDragRect, aSurface);
821 // If the image is a popup, use that as the image. This allows custom drag
822 // images that can change during the drag, but means that any platform
823 // default image handling won't occur.
824 // XXXndeakin this should be chrome-only
826 nsIFrame* frame = content->GetPrimaryFrame();
827 if (frame && frame->IsMenuPopupFrame()) {
828 mDragPopup = content;
832 if (!mDragPopup) {
833 // otherwise, just draw the node
834 RenderImageFlags renderFlags =
835 mImage ? RenderImageFlags::None : RenderImageFlags::AutoScale;
836 if (renderFlags != RenderImageFlags::None) {
837 // check if the dragged node itself is an img element
838 if (dragNode->NodeName().LowerCaseEqualsLiteral("img")) {
839 renderFlags = renderFlags | RenderImageFlags::IsImage;
840 } else {
841 nsINodeList* childList = dragNode->ChildNodes();
842 uint32_t length = childList->Length();
843 // check every childnode for being an img element
844 // XXXbz why don't we need to check descendants recursively?
845 for (uint32_t count = 0; count < length; ++count) {
846 if (childList->Item(count)->NodeName().LowerCaseEqualsLiteral(
847 "img")) {
848 // if the dragnode contains an image, set RenderImageFlags::IsImage
849 // flag
850 renderFlags = renderFlags | RenderImageFlags::IsImage;
851 break;
856 LayoutDeviceIntPoint pnt(aScreenDragRect->TopLeft());
857 *aSurface = presShell->RenderNode(dragNode, aRegion, pnt, aScreenDragRect,
858 renderFlags);
861 // If an image was specified, reset the position from the offset that was
862 // supplied.
863 if (mImage) {
864 aScreenDragRect->MoveTo(screenPoint.x, screenPoint.y);
867 return NS_OK;
870 nsresult nsBaseDragService::DrawDragForImage(
871 nsPresContext* aPresContext, nsIImageLoadingContent* aImageLoader,
872 HTMLCanvasElement* aCanvas, LayoutDeviceIntRect* aScreenDragRect,
873 RefPtr<SourceSurface>* aSurface) {
874 nsCOMPtr<imgIContainer> imgContainer;
875 if (aImageLoader) {
876 nsCOMPtr<imgIRequest> imgRequest;
877 nsresult rv = aImageLoader->GetRequest(
878 nsIImageLoadingContent::CURRENT_REQUEST, getter_AddRefs(imgRequest));
879 NS_ENSURE_SUCCESS(rv, rv);
880 if (!imgRequest) return NS_ERROR_NOT_AVAILABLE;
882 rv = imgRequest->GetImage(getter_AddRefs(imgContainer));
883 NS_ENSURE_SUCCESS(rv, rv);
884 if (!imgContainer) return NS_ERROR_NOT_AVAILABLE;
886 // use the size of the image as the size of the drag image
887 int32_t imageWidth, imageHeight;
888 rv = imgContainer->GetWidth(&imageWidth);
889 NS_ENSURE_SUCCESS(rv, rv);
891 rv = imgContainer->GetHeight(&imageHeight);
892 NS_ENSURE_SUCCESS(rv, rv);
894 aScreenDragRect->SizeTo(aPresContext->CSSPixelsToDevPixels(imageWidth),
895 aPresContext->CSSPixelsToDevPixels(imageHeight));
896 } else {
897 // XXX The canvas size should be converted to dev pixels.
898 NS_ASSERTION(aCanvas, "both image and canvas are null");
899 nsIntSize sz = aCanvas->GetSize();
900 aScreenDragRect->SizeTo(sz.width, sz.height);
903 nsIntSize destSize;
904 destSize.width = aScreenDragRect->Width();
905 destSize.height = aScreenDragRect->Height();
906 if (destSize.width == 0 || destSize.height == 0) return NS_ERROR_FAILURE;
908 nsresult result = NS_OK;
909 if (aImageLoader) {
910 RefPtr<DrawTarget> dt =
911 gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
912 destSize, SurfaceFormat::B8G8R8A8);
913 if (!dt || !dt->IsValid()) return NS_ERROR_FAILURE;
915 RefPtr<gfxContext> ctx = gfxContext::CreateOrNull(dt);
916 if (!ctx) return NS_ERROR_FAILURE;
918 ImgDrawResult res = imgContainer->Draw(
919 ctx, destSize, ImageRegion::Create(destSize),
920 imgIContainer::FRAME_CURRENT, SamplingFilter::GOOD, SVGImageContext(),
921 imgIContainer::FLAG_SYNC_DECODE, 1.0);
922 if (res == ImgDrawResult::BAD_IMAGE || res == ImgDrawResult::BAD_ARGS ||
923 res == ImgDrawResult::NOT_SUPPORTED) {
924 return NS_ERROR_FAILURE;
926 *aSurface = dt->Snapshot();
927 } else {
928 *aSurface = aCanvas->GetSurfaceSnapshot();
931 return result;
934 NS_IMETHODIMP
935 nsBaseDragService::Suppress() {
936 EndDragSession(false, 0);
937 ++mSuppressLevel;
938 return NS_OK;
941 NS_IMETHODIMP
942 nsBaseDragService::Unsuppress() {
943 --mSuppressLevel;
944 return NS_OK;
947 NS_IMETHODIMP
948 nsBaseDragService::UserCancelled() {
949 mUserCancelled = true;
950 return NS_OK;
953 NS_IMETHODIMP
954 nsBaseDragService::UpdateDragEffect() {
955 mDragActionFromChildProcess = mDragAction;
956 return NS_OK;
959 NS_IMETHODIMP
960 nsBaseDragService::UpdateDragImage(nsINode* aImage, int32_t aImageX,
961 int32_t aImageY) {
962 // Don't change the image if this is a drag from another source or if there
963 // is a drag popup.
964 if (!mSourceNode || mDragPopup) return NS_OK;
966 mImage = aImage;
967 mImageOffset = CSSIntPoint(aImageX, aImageY);
968 return NS_OK;
971 NS_IMETHODIMP
972 nsBaseDragService::DragEventDispatchedToChildProcess() {
973 mDragEventDispatchedToChildProcess = true;
974 return NS_OK;
977 bool nsBaseDragService::MaybeAddChildProcess(
978 mozilla::dom::ContentParent* aChild) {
979 if (!mChildProcesses.Contains(aChild)) {
980 mChildProcesses.AppendElement(aChild);
981 return true;
983 return false;
986 bool nsBaseDragService::RemoveAllChildProcesses() {
987 for (uint32_t c = 0; c < mChildProcesses.Length(); c++) {
988 mozilla::Unused << mChildProcesses[c]->SendEndDragSession(
989 true, false, LayoutDeviceIntPoint(), 0,
990 nsIDragService::DRAGDROP_ACTION_NONE);
992 mChildProcesses.Clear();
993 return true;