Bug 1799258 - Fix constexpr issue on base toolchain builds. r=gfx-reviewers,lsalzman
[gecko.git] / widget / nsBaseDragService.cpp
blob460a287819ce9646574c829fe19d58510ef38c58
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 // GetSourceTopWindowContext
156 // Returns the top-level window context where the drag was initiated. This will
157 // be nullptr if the drag began outside of our application.
159 NS_IMETHODIMP
160 nsBaseDragService::GetSourceTopWindowContext(
161 WindowContext** aSourceTopWindowContext) {
162 *aSourceTopWindowContext = mSourceTopWindowContext.get();
163 NS_IF_ADDREF(*aSourceTopWindowContext);
164 return NS_OK;
167 NS_IMETHODIMP
168 nsBaseDragService::SetSourceTopWindowContext(
169 WindowContext* aSourceTopWindowContext) {
170 // This should only be called in a child process.
171 MOZ_ASSERT(!XRE_IsParentProcess());
172 mSourceTopWindowContext = aSourceTopWindowContext;
173 return NS_OK;
177 // GetSourceNode
179 // Returns the DOM node where the drag was initiated. This will be
180 // nullptr if the drag began outside of our application.
182 NS_IMETHODIMP
183 nsBaseDragService::GetSourceNode(nsINode** aSourceNode) {
184 *aSourceNode = do_AddRef(mSourceNode).take();
185 return NS_OK;
188 void nsBaseDragService::UpdateSource(nsINode* aNewSourceNode,
189 Selection* aNewSelection) {
190 MOZ_ASSERT(mSourceNode);
191 MOZ_ASSERT(aNewSourceNode);
192 MOZ_ASSERT(mSourceNode->IsInNativeAnonymousSubtree() ||
193 aNewSourceNode->IsInNativeAnonymousSubtree());
194 MOZ_ASSERT(mSourceDocument == aNewSourceNode->OwnerDoc());
195 mSourceNode = aNewSourceNode;
196 // Don't set mSelection if the session was invoked without selection or
197 // making it becomes nullptr. The latter occurs when the old frame is
198 // being destroyed.
199 if (mSelection && aNewSelection) {
200 // XXX If the dragging image is created once (e.g., at drag start), the
201 // image won't be updated unless we notify `DrawDrag` callers.
202 // However, it must be okay for now to keep using older image of
203 // Selection.
204 mSelection = aNewSelection;
208 NS_IMETHODIMP
209 nsBaseDragService::GetTriggeringPrincipal(nsIPrincipal** aPrincipal) {
210 NS_IF_ADDREF(*aPrincipal = mTriggeringPrincipal);
211 return NS_OK;
214 NS_IMETHODIMP
215 nsBaseDragService::SetTriggeringPrincipal(nsIPrincipal* aPrincipal) {
216 mTriggeringPrincipal = aPrincipal;
217 return NS_OK;
220 NS_IMETHODIMP
221 nsBaseDragService::GetCsp(nsIContentSecurityPolicy** aCsp) {
222 NS_IF_ADDREF(*aCsp = mCsp);
223 return NS_OK;
226 NS_IMETHODIMP
227 nsBaseDragService::SetCsp(nsIContentSecurityPolicy* aCsp) {
228 mCsp = aCsp;
229 return NS_OK;
232 //-------------------------------------------------------------------------
234 NS_IMETHODIMP
235 nsBaseDragService::GetData(nsITransferable* aTransferable,
236 uint32_t aItemIndex) {
237 return NS_ERROR_FAILURE;
240 //-------------------------------------------------------------------------
241 NS_IMETHODIMP
242 nsBaseDragService::IsDataFlavorSupported(const char* aDataFlavor,
243 bool* _retval) {
244 return NS_ERROR_FAILURE;
247 NS_IMETHODIMP
248 nsBaseDragService::GetDataTransferXPCOM(DataTransfer** aDataTransfer) {
249 *aDataTransfer = mDataTransfer;
250 NS_IF_ADDREF(*aDataTransfer);
251 return NS_OK;
254 NS_IMETHODIMP
255 nsBaseDragService::SetDataTransferXPCOM(DataTransfer* aDataTransfer) {
256 NS_ENSURE_STATE(aDataTransfer);
257 mDataTransfer = aDataTransfer;
258 return NS_OK;
261 DataTransfer* nsBaseDragService::GetDataTransfer() { return mDataTransfer; }
263 void nsBaseDragService::SetDataTransfer(DataTransfer* aDataTransfer) {
264 mDataTransfer = aDataTransfer;
267 bool nsBaseDragService::IsSynthesizedForTests() {
268 return mSessionIsSynthesizedForTests;
271 bool nsBaseDragService::IsDraggingTextInTextControl() {
272 return mIsDraggingTextInTextControl;
275 uint32_t nsBaseDragService::GetEffectAllowedForTests() {
276 MOZ_ASSERT(mSessionIsSynthesizedForTests);
277 return mEffectAllowedForTests;
280 NS_IMETHODIMP nsBaseDragService::SetDragEndPointForTests(int32_t aScreenX,
281 int32_t aScreenY) {
282 MOZ_ASSERT(mDoingDrag);
283 MOZ_ASSERT(mSourceDocument);
284 MOZ_ASSERT(mSessionIsSynthesizedForTests);
286 if (!mDoingDrag || !mSourceDocument || !mSessionIsSynthesizedForTests) {
287 return NS_ERROR_FAILURE;
289 nsPresContext* pc = mSourceDocument->GetPresContext();
290 if (NS_WARN_IF(!pc)) {
291 return NS_ERROR_FAILURE;
293 auto p = LayoutDeviceIntPoint::Round(CSSIntPoint(aScreenX, aScreenY) *
294 pc->CSSToDevPixelScale());
295 // p is screen-relative, and we want them to be top-level-widget-relative.
296 if (nsCOMPtr<nsIWidget> widget = pc->GetRootWidget()) {
297 p -= widget->WidgetToScreenOffset();
298 p += widget->WidgetToTopLevelWidgetOffset();
300 SetDragEndPoint(p);
301 return NS_OK;
304 //-------------------------------------------------------------------------
305 NS_IMETHODIMP
306 nsBaseDragService::InvokeDragSession(
307 nsINode* aDOMNode, nsIPrincipal* aPrincipal, nsIContentSecurityPolicy* aCsp,
308 nsICookieJarSettings* aCookieJarSettings, nsIArray* aTransferableArray,
309 uint32_t aActionType,
310 nsContentPolicyType aContentPolicyType = nsIContentPolicy::TYPE_OTHER) {
311 AUTO_PROFILER_LABEL("nsBaseDragService::InvokeDragSession", OTHER);
313 NS_ENSURE_TRUE(aDOMNode, NS_ERROR_INVALID_ARG);
314 NS_ENSURE_TRUE(mSuppressLevel == 0, NS_ERROR_FAILURE);
316 // stash the document of the dom node
317 mSourceDocument = aDOMNode->OwnerDoc();
318 mTriggeringPrincipal = aPrincipal;
319 mCsp = aCsp;
320 mSourceNode = aDOMNode;
321 mIsDraggingTextInTextControl =
322 mSourceNode->IsInNativeAnonymousSubtree() &&
323 TextControlElement::FromNodeOrNull(
324 mSourceNode->GetClosestNativeAnonymousSubtreeRootParent());
325 mContentPolicyType = aContentPolicyType;
326 mEndDragPoint = LayoutDeviceIntPoint(0, 0);
328 // When the mouse goes down, the selection code starts a mouse
329 // capture. However, this gets in the way of determining drag
330 // feedback for things like trees because the event coordinates
331 // are in the wrong coord system, so turn off mouse capture.
332 PresShell::ClearMouseCapture();
334 if (mSessionIsSynthesizedForTests) {
335 mDoingDrag = true;
336 mDragAction = aActionType;
337 mEffectAllowedForTests = aActionType;
338 return NS_OK;
341 // If you're hitting this, a test is causing the browser to attempt to enter
342 // the drag-drop native nested event loop, which will put the browser in a
343 // state that won't run tests properly until there's manual intervention
344 // to exit the drag-drop loop (either by moving the mouse or hitting escape),
345 // which can't be done from script since we're in the nested loop.
347 // The best way to avoid this is to catch the dragstart event on the item
348 // being dragged, and then to call preventDefault() and stopPropagating() on
349 // it.
350 if (XRE_IsParentProcess()) {
351 MOZ_ASSERT(
352 !xpc::IsInAutomation(),
353 "About to start drag-drop native loop on which will prevent later "
354 "tests from running properly.");
357 uint32_t length = 0;
358 mozilla::Unused << aTransferableArray->GetLength(&length);
359 if (!length) {
360 nsCOMPtr<nsIMutableArray> mutableArray =
361 do_QueryInterface(aTransferableArray);
362 if (mutableArray) {
363 // In order to be able trigger dnd, we need to have some transferable
364 // object.
365 nsCOMPtr<nsITransferable> trans =
366 do_CreateInstance("@mozilla.org/widget/transferable;1");
367 trans->Init(nullptr);
368 trans->SetRequestingPrincipal(mSourceNode->NodePrincipal());
369 trans->SetContentPolicyType(mContentPolicyType);
370 trans->SetCookieJarSettings(aCookieJarSettings);
371 mutableArray->AppendElement(trans);
373 } else {
374 for (uint32_t i = 0; i < length; ++i) {
375 nsCOMPtr<nsITransferable> trans =
376 do_QueryElementAt(aTransferableArray, i);
377 if (trans) {
378 // Set the requestingPrincipal on the transferable.
379 trans->SetRequestingPrincipal(mSourceNode->NodePrincipal());
380 trans->SetContentPolicyType(mContentPolicyType);
381 trans->SetCookieJarSettings(aCookieJarSettings);
386 nsresult rv = InvokeDragSessionImpl(aTransferableArray, mRegion, aActionType);
388 if (NS_FAILED(rv)) {
389 // Set mDoingDrag so that EndDragSession cleans up and sends the dragend
390 // event after the aborted drag.
391 mDoingDrag = true;
392 EndDragSession(true, 0);
395 return rv;
398 NS_IMETHODIMP
399 nsBaseDragService::InvokeDragSessionWithImage(
400 nsINode* aDOMNode, nsIPrincipal* aPrincipal, nsIContentSecurityPolicy* aCsp,
401 nsICookieJarSettings* aCookieJarSettings, nsIArray* aTransferableArray,
402 uint32_t aActionType, nsINode* aImage, int32_t aImageX, int32_t aImageY,
403 DragEvent* aDragEvent, DataTransfer* aDataTransfer) {
404 NS_ENSURE_TRUE(aDragEvent, NS_ERROR_NULL_POINTER);
405 NS_ENSURE_TRUE(aDataTransfer, NS_ERROR_NULL_POINTER);
406 NS_ENSURE_TRUE(mSuppressLevel == 0, NS_ERROR_FAILURE);
408 mSessionIsSynthesizedForTests =
409 aDragEvent->WidgetEventPtr()->mFlags.mIsSynthesizedForTests;
410 mDataTransfer = aDataTransfer;
411 mSelection = nullptr;
412 mHasImage = true;
413 mDragPopup = nullptr;
414 mImage = aImage;
415 mImageOffset = CSSIntPoint(aImageX, aImageY);
416 mDragStartData = nullptr;
417 mSourceWindowContext =
418 aDOMNode ? aDOMNode->OwnerDoc()->GetWindowContext() : nullptr;
419 mSourceTopWindowContext =
420 mSourceWindowContext ? mSourceWindowContext->TopWindowContext() : nullptr;
422 mScreenPosition = aDragEvent->ScreenPoint(CallerType::System);
423 mInputSource = aDragEvent->MozInputSource();
425 // If dragging within a XUL tree and no custom drag image was
426 // set, the region argument to InvokeDragSessionWithImage needs
427 // to be set to the area encompassing the selected rows of the
428 // tree to ensure that the drag feedback gets clipped to those
429 // rows. For other content, region should be null.
430 mRegion = Nothing();
431 if (aDOMNode && aDOMNode->IsContent() && !aImage) {
432 if (aDOMNode->NodeInfo()->Equals(nsGkAtoms::treechildren,
433 kNameSpaceID_XUL)) {
434 nsTreeBodyFrame* treeBody =
435 do_QueryFrame(aDOMNode->AsContent()->GetPrimaryFrame());
436 if (treeBody) {
437 mRegion = treeBody->GetSelectionRegion();
442 nsresult rv = InvokeDragSession(
443 aDOMNode, aPrincipal, aCsp, aCookieJarSettings, aTransferableArray,
444 aActionType, nsIContentPolicy::TYPE_INTERNAL_IMAGE);
445 mRegion = Nothing();
446 return rv;
449 NS_IMETHODIMP
450 nsBaseDragService::InvokeDragSessionWithRemoteImage(
451 nsINode* aDOMNode, nsIPrincipal* aPrincipal, nsIContentSecurityPolicy* aCsp,
452 nsICookieJarSettings* aCookieJarSettings, nsIArray* aTransferableArray,
453 uint32_t aActionType, RemoteDragStartData* aDragStartData,
454 DragEvent* aDragEvent, DataTransfer* aDataTransfer) {
455 NS_ENSURE_TRUE(aDragEvent, NS_ERROR_NULL_POINTER);
456 NS_ENSURE_TRUE(aDataTransfer, NS_ERROR_NULL_POINTER);
457 NS_ENSURE_TRUE(mSuppressLevel == 0, NS_ERROR_FAILURE);
459 mSessionIsSynthesizedForTests =
460 aDragEvent->WidgetEventPtr()->mFlags.mIsSynthesizedForTests;
461 mDataTransfer = aDataTransfer;
462 mSelection = nullptr;
463 mHasImage = true;
464 mDragPopup = nullptr;
465 mImage = nullptr;
466 mDragStartData = aDragStartData;
467 mImageOffset = CSSIntPoint(0, 0);
468 mSourceWindowContext = mDragStartData->GetSourceWindowContext();
469 mSourceTopWindowContext = mDragStartData->GetSourceTopWindowContext();
471 mScreenPosition = aDragEvent->ScreenPoint(CallerType::System);
472 mInputSource = aDragEvent->MozInputSource();
474 nsresult rv = InvokeDragSession(
475 aDOMNode, aPrincipal, aCsp, aCookieJarSettings, aTransferableArray,
476 aActionType, nsIContentPolicy::TYPE_INTERNAL_IMAGE);
477 mRegion = Nothing();
478 return rv;
481 NS_IMETHODIMP
482 nsBaseDragService::InvokeDragSessionWithSelection(
483 Selection* aSelection, nsIPrincipal* aPrincipal,
484 nsIContentSecurityPolicy* aCsp, nsICookieJarSettings* aCookieJarSettings,
485 nsIArray* aTransferableArray, uint32_t aActionType, DragEvent* aDragEvent,
486 DataTransfer* aDataTransfer) {
487 NS_ENSURE_TRUE(aSelection, NS_ERROR_NULL_POINTER);
488 NS_ENSURE_TRUE(aDragEvent, NS_ERROR_NULL_POINTER);
489 NS_ENSURE_TRUE(mSuppressLevel == 0, NS_ERROR_FAILURE);
491 mSessionIsSynthesizedForTests =
492 aDragEvent->WidgetEventPtr()->mFlags.mIsSynthesizedForTests;
493 mDataTransfer = aDataTransfer;
494 mSelection = aSelection;
495 mHasImage = true;
496 mDragPopup = nullptr;
497 mImage = nullptr;
498 mImageOffset = CSSIntPoint();
499 mDragStartData = nullptr;
500 mRegion = Nothing();
502 mScreenPosition.x = aDragEvent->ScreenX(CallerType::System);
503 mScreenPosition.y = aDragEvent->ScreenY(CallerType::System);
504 mInputSource = aDragEvent->MozInputSource();
506 // just get the focused node from the selection
507 // XXXndeakin this should actually be the deepest node that contains both
508 // endpoints of the selection
509 nsCOMPtr<nsINode> node = aSelection->GetFocusNode();
510 mSourceWindowContext = node ? node->OwnerDoc()->GetWindowContext() : nullptr;
511 mSourceTopWindowContext =
512 mSourceWindowContext ? mSourceWindowContext->TopWindowContext() : nullptr;
514 return InvokeDragSession(node, aPrincipal, aCsp, aCookieJarSettings,
515 aTransferableArray, aActionType,
516 nsIContentPolicy::TYPE_OTHER);
519 //-------------------------------------------------------------------------
520 NS_IMETHODIMP
521 nsBaseDragService::GetCurrentSession(nsIDragSession** aSession) {
522 if (!aSession) return NS_ERROR_INVALID_ARG;
524 // "this" also implements a drag session, so say we are one but only
525 // if there is currently a drag going on.
526 if (!mSuppressLevel && mDoingDrag) {
527 *aSession = this;
528 NS_ADDREF(*aSession); // addRef because we're a "getter"
529 } else
530 *aSession = nullptr;
532 return NS_OK;
535 //-------------------------------------------------------------------------
536 NS_IMETHODIMP
537 nsBaseDragService::StartDragSession() {
538 if (mDoingDrag) {
539 return NS_ERROR_FAILURE;
541 mDoingDrag = true;
542 // By default dispatch drop also to content.
543 mOnlyChromeDrop = false;
545 return NS_OK;
548 NS_IMETHODIMP nsBaseDragService::StartDragSessionForTests(
549 uint32_t aAllowedEffect) {
550 if (NS_WARN_IF(NS_FAILED(StartDragSession()))) {
551 return NS_ERROR_FAILURE;
553 mDragAction = aAllowedEffect;
554 mEffectAllowedForTests = aAllowedEffect;
555 mSessionIsSynthesizedForTests = true;
556 return NS_OK;
559 void nsBaseDragService::OpenDragPopup() {
560 if (mDragPopup) {
561 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
562 if (pm) {
563 pm->ShowPopupAtScreen(mDragPopup, mScreenPosition.x - mImageOffset.x,
564 mScreenPosition.y - mImageOffset.y, false, nullptr);
569 int32_t nsBaseDragService::TakeChildProcessDragAction() {
570 // If the last event was dispatched to the child process, use the drag action
571 // assigned from it instead and return it. DRAGDROP_ACTION_UNINITIALIZED is
572 // returned otherwise.
573 int32_t retval = DRAGDROP_ACTION_UNINITIALIZED;
574 if (TakeDragEventDispatchedToChildProcess() &&
575 mDragActionFromChildProcess != DRAGDROP_ACTION_UNINITIALIZED) {
576 retval = mDragActionFromChildProcess;
579 return retval;
582 //-------------------------------------------------------------------------
583 NS_IMETHODIMP
584 nsBaseDragService::EndDragSession(bool aDoneDrag, uint32_t aKeyModifiers) {
585 if (!mDoingDrag || mEndingSession) {
586 return NS_ERROR_FAILURE;
589 mEndingSession = true;
591 if (aDoneDrag && !mSuppressLevel) {
592 FireDragEventAtSource(eDragEnd, aKeyModifiers);
595 if (mDragPopup) {
596 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
597 if (pm) {
598 pm->HidePopup(mDragPopup, {HidePopupOption::DeselectMenu});
602 uint32_t dropEffect = nsIDragService::DRAGDROP_ACTION_NONE;
603 if (mDataTransfer) {
604 dropEffect = mDataTransfer->DropEffectInt();
607 for (uint32_t i = 0; i < mChildProcesses.Length(); ++i) {
608 mozilla::Unused << mChildProcesses[i]->SendEndDragSession(
609 aDoneDrag, mUserCancelled, mEndDragPoint, aKeyModifiers, dropEffect);
610 // Continue sending input events with input priority when stopping the dnd
611 // session.
612 mChildProcesses[i]->SetInputPriorityEventEnabled(true);
614 mChildProcesses.Clear();
616 // mDataTransfer and the items it owns are going to die anyway, but we
617 // explicitly deref the contained data here so that we don't have to wait for
618 // CC to reclaim the memory.
619 if (XRE_IsParentProcess()) {
620 DiscardInternalTransferData();
623 mDoingDrag = false;
624 mSessionIsSynthesizedForTests = false;
625 mIsDraggingTextInTextControl = false;
626 mEffectAllowedForTests = nsIDragService::DRAGDROP_ACTION_UNINITIALIZED;
627 mEndingSession = false;
628 mCanDrop = false;
630 // release the source we've been holding on to.
631 mSourceDocument = nullptr;
632 mSourceNode = nullptr;
633 mSourceWindowContext = nullptr;
634 mTriggeringPrincipal = nullptr;
635 mCsp = nullptr;
636 mSelection = nullptr;
637 mDataTransfer = nullptr;
638 mHasImage = false;
639 mUserCancelled = false;
640 mDragPopup = nullptr;
641 mDragStartData = nullptr;
642 mImage = nullptr;
643 mImageOffset = CSSIntPoint();
644 mScreenPosition = CSSIntPoint();
645 mEndDragPoint = LayoutDeviceIntPoint(0, 0);
646 mInputSource = MouseEvent_Binding::MOZ_SOURCE_MOUSE;
647 mRegion = Nothing();
649 return NS_OK;
652 void nsBaseDragService::DiscardInternalTransferData() {
653 if (mDataTransfer && mSourceNode) {
654 MOZ_ASSERT(mDataTransfer);
656 DataTransferItemList* items = mDataTransfer->Items();
657 for (size_t i = 0; i < items->Length(); i++) {
658 bool found;
659 DataTransferItem* item = items->IndexedGetter(i, found);
661 // Non-OTHER items may still be needed by JS. Skip them.
662 if (!found || item->Kind() != DataTransferItem::KIND_OTHER) {
663 continue;
666 nsCOMPtr<nsIVariant> variant = item->DataNoSecurityCheck();
667 nsCOMPtr<nsIWritableVariant> writable = do_QueryInterface(variant);
669 if (writable) {
670 writable->SetAsEmpty();
676 NS_IMETHODIMP
677 nsBaseDragService::FireDragEventAtSource(EventMessage aEventMessage,
678 uint32_t aKeyModifiers) {
679 if (!mSourceNode || !mSourceDocument || mSuppressLevel) {
680 return NS_OK;
682 RefPtr<PresShell> presShell = mSourceDocument->GetPresShell();
683 if (!presShell) {
684 return NS_OK;
687 RefPtr<nsPresContext> pc = presShell->GetPresContext();
688 nsCOMPtr<nsIWidget> widget = pc ? pc->GetRootWidget() : nullptr;
690 nsEventStatus status = nsEventStatus_eIgnore;
691 WidgetDragEvent event(true, aEventMessage, widget);
692 event.mFlags.mIsSynthesizedForTests = mSessionIsSynthesizedForTests;
693 event.mInputSource = mInputSource;
694 if (aEventMessage == eDragEnd) {
695 event.mRefPoint = mEndDragPoint;
696 if (widget) {
697 event.mRefPoint -= widget->WidgetToTopLevelWidgetOffset();
699 event.mUserCancelled = mUserCancelled;
701 event.mModifiers = aKeyModifiers;
703 if (widget) {
704 // Send the drag event to APZ, which needs to know about them to be
705 // able to accurately detect the end of a drag gesture.
706 widget->DispatchEventToAPZOnly(&event);
709 nsCOMPtr<nsIContent> content = do_QueryInterface(mSourceNode);
710 return presShell->HandleDOMEventWithTarget(content, &event, &status);
713 /* This is used by Windows and Mac to update the position of a popup being
714 * used as a drag image during the drag. This isn't used on GTK as it manages
715 * the drag popup itself.
717 NS_IMETHODIMP
718 nsBaseDragService::DragMoved(int32_t aX, int32_t aY) {
719 if (mDragPopup) {
720 nsIFrame* frame = mDragPopup->GetPrimaryFrame();
721 if (frame && frame->IsMenuPopupFrame()) {
722 CSSIntPoint cssPos =
723 RoundedToInt(LayoutDeviceIntPoint(aX, aY) /
724 frame->PresContext()->CSSToDevPixelScale()) -
725 mImageOffset;
726 static_cast<nsMenuPopupFrame*>(frame)->MoveTo(cssPos, true);
730 return NS_OK;
733 static PresShell* GetPresShellForContent(nsINode* aDOMNode) {
734 nsCOMPtr<nsIContent> content = do_QueryInterface(aDOMNode);
735 if (!content) return nullptr;
737 RefPtr<Document> document = content->GetComposedDoc();
738 if (document) {
739 document->FlushPendingNotifications(FlushType::Display);
740 return document->GetPresShell();
743 return nullptr;
746 nsresult nsBaseDragService::DrawDrag(nsINode* aDOMNode,
747 const Maybe<CSSIntRegion>& aRegion,
748 CSSIntPoint aScreenPosition,
749 LayoutDeviceIntRect* aScreenDragRect,
750 RefPtr<SourceSurface>* aSurface,
751 nsPresContext** aPresContext) {
752 *aSurface = nullptr;
753 *aPresContext = nullptr;
755 // use a default size, in case of an error.
756 aScreenDragRect->SetRect(aScreenPosition.x - mImageOffset.x,
757 aScreenPosition.y - mImageOffset.y, 1, 1);
759 // if a drag image was specified, use that, otherwise, use the source node
760 nsCOMPtr<nsINode> dragNode = mImage ? mImage.get() : aDOMNode;
762 // get the presshell for the node being dragged. If the drag image is not in
763 // a document or has no frame, get the presshell from the source drag node
764 PresShell* presShell = GetPresShellForContent(dragNode);
765 if (!presShell && mImage) {
766 presShell = GetPresShellForContent(aDOMNode);
768 if (!presShell) {
769 return NS_ERROR_FAILURE;
772 *aPresContext = presShell->GetPresContext();
774 if (mDragStartData) {
775 if (mImage) {
776 // Just clear the surface if chrome has overridden it with an image.
777 *aSurface = nullptr;
778 } else {
779 *aSurface = mDragStartData->TakeVisualization(aScreenDragRect);
782 mDragStartData = nullptr;
783 return NS_OK;
786 // convert mouse position to dev pixels of the prescontext
787 const CSSIntPoint screenPosition = aScreenPosition - mImageOffset;
788 const auto screenPoint = LayoutDeviceIntPoint::Round(
789 screenPosition * (*aPresContext)->CSSToDevPixelScale());
790 aScreenDragRect->MoveTo(screenPoint.x, screenPoint.y);
792 // check if drag images are disabled
793 bool enableDragImages = Preferences::GetBool(DRAGIMAGES_PREF, true);
795 // didn't want an image, so just set the screen rectangle to the frame size
796 if (!enableDragImages || !mHasImage) {
797 // This holds a quantity in RelativeTo{presShell->GetRootFrame(),
798 // ViewportType::Layout} space.
799 nsRect presLayoutRect;
800 if (aRegion) {
801 // if a region was specified, set the screen rectangle to the area that
802 // the region occupies
803 presLayoutRect = ToAppUnits(aRegion->GetBounds(), AppUnitsPerCSSPixel());
804 } else {
805 // otherwise, there was no region so just set the rectangle to
806 // the size of the primary frame of the content.
807 nsCOMPtr<nsIContent> content = do_QueryInterface(dragNode);
808 if (nsIFrame* frame = content->GetPrimaryFrame()) {
809 presLayoutRect = frame->GetBoundingClientRect();
813 LayoutDeviceRect screenVisualRect = ViewportUtils::ToScreenRelativeVisual(
814 LayoutDeviceRect::FromAppUnits(presLayoutRect,
815 (*aPresContext)->AppUnitsPerDevPixel()),
816 *aPresContext);
817 aScreenDragRect->SizeTo(screenVisualRect.Width(),
818 screenVisualRect.Height());
819 return NS_OK;
822 // draw the image for selections
823 if (mSelection) {
824 LayoutDeviceIntPoint pnt(aScreenDragRect->TopLeft());
825 *aSurface = presShell->RenderSelection(
826 mSelection, pnt, aScreenDragRect,
827 mImage ? RenderImageFlags::None : RenderImageFlags::AutoScale);
828 return NS_OK;
831 // if a custom image was specified, check if it is an image node and draw
832 // using the source rather than the displayed image. But if mImage isn't
833 // an image or canvas, fall through to RenderNode below.
834 if (mImage) {
835 nsCOMPtr<nsIContent> content = do_QueryInterface(dragNode);
836 HTMLCanvasElement* canvas = HTMLCanvasElement::FromNodeOrNull(content);
837 if (canvas) {
838 return DrawDragForImage(*aPresContext, nullptr, canvas, aScreenDragRect,
839 aSurface);
842 nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(dragNode);
843 // for image nodes, create the drag image from the actual image data
844 if (imageLoader) {
845 return DrawDragForImage(*aPresContext, imageLoader, nullptr,
846 aScreenDragRect, aSurface);
849 // If the image is a popup, use that as the image. This allows custom drag
850 // images that can change during the drag, but means that any platform
851 // default image handling won't occur.
852 // XXXndeakin this should be chrome-only
854 nsIFrame* frame = content->GetPrimaryFrame();
855 if (frame && frame->IsMenuPopupFrame()) {
856 mDragPopup = content;
860 if (!mDragPopup) {
861 // otherwise, just draw the node
862 RenderImageFlags renderFlags =
863 mImage ? RenderImageFlags::None : RenderImageFlags::AutoScale;
864 if (renderFlags != RenderImageFlags::None) {
865 // check if the dragged node itself is an img element
866 if (dragNode->NodeName().LowerCaseEqualsLiteral("img")) {
867 renderFlags = renderFlags | RenderImageFlags::IsImage;
868 } else {
869 nsINodeList* childList = dragNode->ChildNodes();
870 uint32_t length = childList->Length();
871 // check every childnode for being an img element
872 // XXXbz why don't we need to check descendants recursively?
873 for (uint32_t count = 0; count < length; ++count) {
874 if (childList->Item(count)->NodeName().LowerCaseEqualsLiteral(
875 "img")) {
876 // if the dragnode contains an image, set RenderImageFlags::IsImage
877 // flag
878 renderFlags = renderFlags | RenderImageFlags::IsImage;
879 break;
884 LayoutDeviceIntPoint pnt(aScreenDragRect->TopLeft());
885 *aSurface = presShell->RenderNode(dragNode, aRegion, pnt, aScreenDragRect,
886 renderFlags);
889 // If an image was specified, reset the position from the offset that was
890 // supplied.
891 if (mImage) {
892 aScreenDragRect->MoveTo(screenPoint.x, screenPoint.y);
895 return NS_OK;
898 nsresult nsBaseDragService::DrawDragForImage(
899 nsPresContext* aPresContext, nsIImageLoadingContent* aImageLoader,
900 HTMLCanvasElement* aCanvas, LayoutDeviceIntRect* aScreenDragRect,
901 RefPtr<SourceSurface>* aSurface) {
902 nsCOMPtr<imgIContainer> imgContainer;
903 if (aImageLoader) {
904 nsCOMPtr<imgIRequest> imgRequest;
905 nsresult rv = aImageLoader->GetRequest(
906 nsIImageLoadingContent::CURRENT_REQUEST, getter_AddRefs(imgRequest));
907 NS_ENSURE_SUCCESS(rv, rv);
908 if (!imgRequest) return NS_ERROR_NOT_AVAILABLE;
910 rv = imgRequest->GetImage(getter_AddRefs(imgContainer));
911 NS_ENSURE_SUCCESS(rv, rv);
912 if (!imgContainer) return NS_ERROR_NOT_AVAILABLE;
914 // use the size of the image as the size of the drag image
915 int32_t imageWidth, imageHeight;
916 rv = imgContainer->GetWidth(&imageWidth);
917 NS_ENSURE_SUCCESS(rv, rv);
919 rv = imgContainer->GetHeight(&imageHeight);
920 NS_ENSURE_SUCCESS(rv, rv);
922 aScreenDragRect->SizeTo(aPresContext->CSSPixelsToDevPixels(imageWidth),
923 aPresContext->CSSPixelsToDevPixels(imageHeight));
924 } else {
925 // XXX The canvas size should be converted to dev pixels.
926 NS_ASSERTION(aCanvas, "both image and canvas are null");
927 nsIntSize sz = aCanvas->GetSize();
928 aScreenDragRect->SizeTo(sz.width, sz.height);
931 nsIntSize destSize;
932 destSize.width = aScreenDragRect->Width();
933 destSize.height = aScreenDragRect->Height();
934 if (destSize.width == 0 || destSize.height == 0) return NS_ERROR_FAILURE;
936 nsresult result = NS_OK;
937 if (aImageLoader) {
938 RefPtr<DrawTarget> dt =
939 gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
940 destSize, SurfaceFormat::B8G8R8A8);
941 if (!dt || !dt->IsValid()) return NS_ERROR_FAILURE;
943 gfxContext ctx(dt);
945 ImgDrawResult res = imgContainer->Draw(
946 &ctx, destSize, ImageRegion::Create(destSize),
947 imgIContainer::FRAME_CURRENT, SamplingFilter::GOOD, SVGImageContext(),
948 imgIContainer::FLAG_SYNC_DECODE, 1.0);
949 if (res == ImgDrawResult::BAD_IMAGE || res == ImgDrawResult::BAD_ARGS ||
950 res == ImgDrawResult::NOT_SUPPORTED) {
951 return NS_ERROR_FAILURE;
953 *aSurface = dt->Snapshot();
954 } else {
955 *aSurface = aCanvas->GetSurfaceSnapshot();
958 return result;
961 NS_IMETHODIMP
962 nsBaseDragService::Suppress() {
963 EndDragSession(false, 0);
964 ++mSuppressLevel;
965 return NS_OK;
968 NS_IMETHODIMP
969 nsBaseDragService::Unsuppress() {
970 --mSuppressLevel;
971 return NS_OK;
974 NS_IMETHODIMP
975 nsBaseDragService::UserCancelled() {
976 mUserCancelled = true;
977 return NS_OK;
980 NS_IMETHODIMP
981 nsBaseDragService::UpdateDragEffect() {
982 mDragActionFromChildProcess = mDragAction;
983 return NS_OK;
986 NS_IMETHODIMP
987 nsBaseDragService::UpdateDragImage(nsINode* aImage, int32_t aImageX,
988 int32_t aImageY) {
989 // Don't change the image if this is a drag from another source or if there
990 // is a drag popup.
991 if (!mSourceNode || mDragPopup) return NS_OK;
993 mImage = aImage;
994 mImageOffset = CSSIntPoint(aImageX, aImageY);
995 return NS_OK;
998 NS_IMETHODIMP
999 nsBaseDragService::DragEventDispatchedToChildProcess() {
1000 mDragEventDispatchedToChildProcess = true;
1001 return NS_OK;
1004 bool nsBaseDragService::MaybeAddChildProcess(
1005 mozilla::dom::ContentParent* aChild) {
1006 if (!mChildProcesses.Contains(aChild)) {
1007 mChildProcesses.AppendElement(aChild);
1008 return true;
1010 return false;
1013 bool nsBaseDragService::RemoveAllChildProcesses() {
1014 for (uint32_t c = 0; c < mChildProcesses.Length(); c++) {
1015 mozilla::Unused << mChildProcesses[c]->SendEndDragSession(
1016 true, false, LayoutDeviceIntPoint(), 0,
1017 nsIDragService::DRAGDROP_ACTION_NONE);
1019 mChildProcesses.Clear();
1020 return true;