VirtualBox

source: vbox/trunk/src/VBox/Additions/x11/VBoxClient/draganddrop-x11.cpp

Last change on this file was 99595, checked in by vboxsync, 13 months ago

Guest Additions/VBoxClient: Moved the X11-specific code for drag'n drop into an own submodule and using the actual service as a (runtime) wrapper (for also the Wayland-specific code later). bugref:10427

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 130.2 KB
RevLine 
[55401]1/* $Id: draganddrop-x11.cpp 99595 2023-05-04 08:58:54Z vboxsync $ */
[42261]2/** @file
[99595]3 * Guest Additions - VBoxClient X11 drag'n drop implementation.
[42261]4 */
5
6/*
[98103]7 * Copyright (C) 2011-2023 Oracle and/or its affiliates.
[42261]8 *
[96407]9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
[42261]26 */
27
28#include <X11/Xlib.h>
[55820]29#include <X11/Xutil.h>
[42261]30#include <X11/Xatom.h>
[50724]31#ifdef VBOX_DND_WITH_XTEST
32# include <X11/extensions/XTest.h>
33#endif
[42261]34
[50724]35#include <iprt/asm.h>
[56651]36#include <iprt/buildconfig.h>
[50724]37#include <iprt/critsect.h>
[42261]38#include <iprt/thread.h>
39#include <iprt/time.h>
40
41#include <iprt/cpp/mtlist.h>
42#include <iprt/cpp/ministring.h>
43
44#include <limits.h>
45
[56781]46#ifdef LOG_GROUP
47# undef LOG_GROUP
48#endif
[50724]49#define LOG_GROUP LOG_GROUP_GUEST_DND
[42261]50#include <VBox/log.h>
51#include <VBox/VBoxGuestLib.h>
[97734]52#include <VBox/version.h>
[42261]53
54#include "VBox/HostServices/DragAndDropSvc.h"
55#include "VBoxClient.h"
[99595]56#include "draganddrop.h"
[42261]57
[50724]58
[85927]59/* Enable this to handle drag'n drop "promises".
60 * This is needed for supporting certain applications (i.e. PcManFM on LXDE),
61 * which require the drag'n drop meta data a lot earlier than actually needed.
62 * That behavior is similar to macOS' drag'n drop promises, hence the name.
63 *
64 * Those applications query the data right while dragging over them (see GtkWidget::drag-motion),
65 * instead of when the source dropped the data (GtkWidget::drag-drop).
66 *
67 * This might be entirely implementation-specific, so not being a bug in GTK/GDK. Also see #9820.
68 */
69#ifdef VBOX_WITH_DRAG_AND_DROP_PROMISES
70# undef VBOX_WITH_DRAG_AND_DROP_PROMISES
71#endif
72
[55918]73/**
[56651]74 * For X11 guest Xdnd is used. See http://www.acc.umu.se/~vatten/XDND.html for
[42261]75 * a walk trough.
76 *
[85920]77 * Also useful pages:
78 * - https://www.freedesktop.org/wiki/Draganddropwarts/
79 * - https://www.freedesktop.org/wiki/Specifications/XDNDRevision/
80 *
[55918]81 * Host -> Guest:
82 * For X11 this means mainly forwarding all the events from HGCM to the
83 * appropriate X11 events. There exists a proxy window, which is invisible and
84 * used for all the X11 communication. On a HGCM Enter event, we set our proxy
85 * window as XdndSelection owner with the given mime-types. On every HGCM move
86 * event, we move the X11 mouse cursor to the new position and query for the
87 * window below that position. Depending on if it is XdndAware, a new window or
88 * a known window, we send the appropriate X11 messages to it. On HGCM drop, we
89 * send a XdndDrop message to the current window and wait for a X11
90 * SelectionMessage from the target window. Because we didn't have the data in
91 * the requested mime-type, yet, we save that message and ask the host for the
92 * data. When the data is successfully received from the host, we put the data
93 * as a property to the window and send a X11 SelectionNotify event to the
94 * target window.
[42261]95 *
[55918]96 * Guest -> Host:
97 * This is a lot more trickery than H->G. When a pending event from HGCM
98 * arrives, we ask if there currently is an owner of the XdndSelection
99 * property. If so, our proxy window is shown (1x1, but without backing store)
100 * and some mouse event is triggered. This should be followed by an XdndEnter
101 * event send to the proxy window. From this event we can fetch the necessary
102 * info of the MIME types and allowed actions and send this back to the host.
103 * On a drop request from the host, we query for the selection and should get
104 * the data in the specified mime-type. This data is send back to the host.
105 * After that we send a XdndLeave event to the source window.
[51529]106 *
[55918]107 ** @todo Cancelling (e.g. with ESC key) doesn't work.
108 ** @todo INCR (incremental transfers) support.
109 ** @todo Really check for the Xdnd version and the supported features.
110 ** @todo Either get rid of the xHelpers class or properly unify the code with the drag instance class.
[42261]111 */
112
[85920]113/*********************************************************************************************************************************
114 * Definitions *
115 ********************************************************************************************************************************/
116
117/** The Xdnd protocol version we support. */
118#define VBOX_XDND_VERSION (5)
119
[97735]120/** No flags specified. */
121#define VBOX_XDND_STATUS_FLAG_NONE 0
[85920]122/** Whether the target window accepts the data being dragged over or not. */
[97735]123#define VBOX_XDND_STATUS_FLAG_ACCEPT RT_BIT(0)
[85920]124/** Whether the target window wants XdndPosition messages while dragging stuff over it. */
[97735]125#define VBOX_XDND_STATUS_FLAG_WANTS_POS RT_BIT(1)
[85920]126
127/** Whether the target window accepted the drop data or not. */
[97735]128#define VBOX_XDND_FINISHED_FLAG_SUCCEEDED RT_BIT(0)
[85920]129
130/** How many X properties our proxy window can hold. */
[42261]131#define VBOX_MAX_XPROPERTIES (LONG_MAX-1)
132
[97734]133/** The notification header text for VBClShowNotify(). */
134#define VBOX_DND_SHOWNOTIFY_HEADER VBOX_PRODUCT " Drag'n Drop"
135
[42261]136enum XA_Type
137{
138 /* States */
139 XA_WM_STATE = 0,
140 /* Properties */
141 XA_TARGETS,
142 XA_MULTIPLE,
143 XA_INCR,
144 /* Mime Types */
145 XA_image_bmp,
146 XA_image_jpg,
147 XA_image_tiff,
148 XA_image_png,
149 XA_text_uri_list,
150 XA_text_uri,
151 XA_text_plain,
152 XA_TEXT,
[56651]153 /* Xdnd */
[42261]154 XA_XdndSelection,
155 XA_XdndAware,
156 XA_XdndEnter,
157 XA_XdndLeave,
158 XA_XdndTypeList,
159 XA_XdndActionList,
160 XA_XdndPosition,
161 XA_XdndActionCopy,
162 XA_XdndActionMove,
163 XA_XdndActionLink,
164 XA_XdndStatus,
165 XA_XdndDrop,
166 XA_XdndFinished,
167 /* Our own stop marker */
168 XA_dndstop,
169 /* End marker */
170 XA_End
171};
172
[56651]173/**
[97734]174 * Xdnd message value indices, sorted by message type.
[56651]175 */
176typedef enum XdndMsg
177{
178 /** XdndEnter. */
179 XdndEnterTypeCount = 3, /* Maximum number of types in XdndEnter message. */
180
181 XdndEnterWindow = 0, /* Source window (sender). */
182 XdndEnterFlags, /* Version in high byte, bit 0 => more data types. */
183 XdndEnterType1, /* First available data type. */
184 XdndEnterType2, /* Second available data type. */
185 XdndEnterType3, /* Third available data type. */
186
187 XdndEnterMoreTypesFlag = 1, /* Set if there are more than XdndEnterTypeCount. */
188 XdndEnterVersionRShift = 24, /* Right shift to position version number. */
189 XdndEnterVersionMask = 0xFF, /* Mask to get version after shifting. */
190
191 /** XdndHere. */
192 XdndHereWindow = 0, /* Source window (sender). */
193 XdndHereFlags, /* Reserved. */
194 XdndHerePt, /* X + Y coordinates of mouse (root window coords). */
195 XdndHereTimeStamp, /* Timestamp for requesting data. */
196 XdndHereAction, /* Action requested by user. */
197
198 /** XdndPosition. */
199 XdndPositionWindow = 0, /* Source window (sender). */
200 XdndPositionFlags, /* Flags. */
[56781]201 XdndPositionXY, /* X/Y coordinates of the mouse position relative to the root window. */
[56651]202 XdndPositionTimeStamp, /* Time stamp for retrieving the data. */
203 XdndPositionAction, /* Action requested by the user. */
204
205 /** XdndStatus. */
206 XdndStatusWindow = 0, /* Target window (sender).*/
207 XdndStatusFlags, /* Flags returned by target. */
[56781]208 XdndStatusNoMsgXY, /* X + Y of "no msg" rectangle (root window coords). */
209 XdndStatusNoMsgWH, /* Width + height of "no msg" rectangle. */
[56651]210 XdndStatusAction, /* Action accepted by target. */
211
212 XdndStatusAcceptDropFlag = 1, /* Set if target will accept the drop. */
213 XdndStatusSendHereFlag = 2, /* Set if target wants a stream of XdndPosition. */
214
215 /** XdndLeave. */
216 XdndLeaveWindow = 0, /* Source window (sender). */
217 XdndLeaveFlags, /* Reserved. */
218
219 /** XdndDrop. */
220 XdndDropWindow = 0, /* Source window (sender). */
221 XdndDropFlags, /* Reserved. */
222 XdndDropTimeStamp, /* Timestamp for requesting data. */
223
224 /** XdndFinished. */
225 XdndFinishedWindow = 0, /* Target window (sender). */
[97734]226 XdndFinishedFlags, /* Since version 5: Bit 0 is set if the current target accepted the drop. */
227 XdndFinishedAction /* Since version 5: Contains the action performed by the target. */
[56651]228
229} XdndMsg;
230
[99595]231class VBClX11DnDSvc;
[42261]232
[55918]233/** List of Atoms. */
234#define VBoxDnDAtomList RTCList<Atom>
235
[99595]236class VBClX11DnDXHelpers
[42261]237{
238public:
239
[99595]240 static VBClX11DnDXHelpers *getInstance(Display *pDisplay = 0)
[42261]241 {
242 if (!m_pInstance)
243 {
[49891]244 AssertPtrReturn(pDisplay, NULL);
[99595]245 m_pInstance = new VBClX11DnDXHelpers(pDisplay);
[42261]246 }
[49891]247
[42261]248 return m_pInstance;
249 }
250
[60981]251 static void destroyInstance(void)
252 {
253 if (m_pInstance)
254 {
255 delete m_pInstance;
256 m_pInstance = NULL;
257 }
258 }
259
[42261]260 inline Display *display() const { return m_pDisplay; }
261 inline Atom xAtom(XA_Type e) const { return m_xAtoms[e]; }
262
263 inline Atom stringToxAtom(const char *pcszString) const
264 {
265 return XInternAtom(m_pDisplay, pcszString, False);
266 }
267 inline RTCString xAtomToString(Atom atom) const
268 {
269 if (atom == None) return "None";
270
271 char* pcsAtom = XGetAtomName(m_pDisplay, atom);
272 RTCString strAtom(pcsAtom);
273 XFree(pcsAtom);
274
275 return strAtom;
276 }
277
[97827]278 inline RTCString xAtomListToString(const VBoxDnDAtomList &formatList, const RTCString &strSep = DND_FORMATS_SEPARATOR_STR)
[42261]279 {
280 RTCString format;
281 for (size_t i = 0; i < formatList.size(); ++i)
[97827]282 format += xAtomToString(formatList.at(i)) + strSep;
[42261]283 return format;
284 }
285
[97826]286 /**
287 * Returns a filtered X11 atom list.
288 *
289 * @returns Filtered list.
290 * @param formatList Atom list to convert.
291 * @param filterList Atom list to filter out.
292 */
293 inline VBoxDnDAtomList xAtomListFiltered(const VBoxDnDAtomList &formatList, const VBoxDnDAtomList &filterList)
294 {
295 VBoxDnDAtomList tempList = formatList;
296 tempList.filter(filterList);
297 return tempList;
298 }
299
[55707]300 RTCString xErrorToString(int xRc) const;
[42261]301 Window applicationWindowBelowCursor(Window parentWin) const;
302
303private:
[79482]304#ifdef RT_NEED_NEW_AND_DELETE
305 RTMEM_IMPLEMENT_NEW_AND_DELETE();
306#endif
[99595]307 VBClX11DnDXHelpers(Display *pDisplay)
[42261]308 : m_pDisplay(pDisplay)
309 {
310 /* Not all x11 atoms we use are defined in the headers. Create the
311 * additional one we need here. */
312 for (int i = 0; i < XA_End; ++i)
313 m_xAtoms[i] = XInternAtom(m_pDisplay, m_xAtomNames[i], False);
314 };
315
316 /* Private member vars */
[99595]317 static VBClX11DnDXHelpers *m_pInstance;
[42261]318 Display *m_pDisplay;
319 Atom m_xAtoms[XA_End];
320 static const char *m_xAtomNames[XA_End];
321};
322
323/* Some xHelpers convenience defines. */
[99595]324#define gX11 VBClX11DnDXHelpers::getInstance()
325#define xAtom(xa) VBClX11DnDXHelpers::getInstance()->xAtom((xa))
326#define xAtomToString(xa) VBClX11DnDXHelpers::getInstance()->xAtomToString((xa))
[42261]327
[85920]328/*********************************************************************************************************************************
329 * xHelpers implementation. *
330 ********************************************************************************************************************************/
[42261]331
[99595]332VBClX11DnDXHelpers *VBClX11DnDXHelpers::m_pInstance = NULL;
[55918]333
[42261]334/* Has to be in sync with the XA_Type enum. */
[99595]335const char *VBClX11DnDXHelpers::m_xAtomNames[] =
[42261]336{
337 /* States */
338 "WM_STATE",
339 /* Properties */
340 "TARGETS",
341 "MULTIPLE",
342 "INCR",
343 /* Mime Types */
344 "image/bmp",
345 "image/jpg",
346 "image/tiff",
347 "image/png",
348 "text/uri-list",
349 "text/uri",
350 "text/plain",
351 "TEXT",
[56651]352 /* Xdnd */
[42261]353 "XdndSelection",
354 "XdndAware",
355 "XdndEnter",
356 "XdndLeave",
357 "XdndTypeList",
358 "XdndActionList",
359 "XdndPosition",
360 "XdndActionCopy",
361 "XdndActionMove",
362 "XdndActionLink",
363 "XdndStatus",
364 "XdndDrop",
365 "XdndFinished",
366 /* Our own stop marker */
367 "dndstop"
368};
369
[99595]370RTCString VBClX11DnDXHelpers::xErrorToString(int xRc) const
[42261]371{
[55707]372 switch (xRc)
[42261]373 {
[55707]374 case Success: return RTCStringFmt("%d (Success)", xRc); break;
375 case BadRequest: return RTCStringFmt("%d (BadRequest)", xRc); break;
376 case BadValue: return RTCStringFmt("%d (BadValue)", xRc); break;
377 case BadWindow: return RTCStringFmt("%d (BadWindow)", xRc); break;
378 case BadPixmap: return RTCStringFmt("%d (BadPixmap)", xRc); break;
379 case BadAtom: return RTCStringFmt("%d (BadAtom)", xRc); break;
380 case BadCursor: return RTCStringFmt("%d (BadCursor)", xRc); break;
381 case BadFont: return RTCStringFmt("%d (BadFont)", xRc); break;
382 case BadMatch: return RTCStringFmt("%d (BadMatch)", xRc); break;
383 case BadDrawable: return RTCStringFmt("%d (BadDrawable)", xRc); break;
384 case BadAccess: return RTCStringFmt("%d (BadAccess)", xRc); break;
385 case BadAlloc: return RTCStringFmt("%d (BadAlloc)", xRc); break;
386 case BadColor: return RTCStringFmt("%d (BadColor)", xRc); break;
387 case BadGC: return RTCStringFmt("%d (BadGC)", xRc); break;
388 case BadIDChoice: return RTCStringFmt("%d (BadIDChoice)", xRc); break;
389 case BadName: return RTCStringFmt("%d (BadName)", xRc); break;
390 case BadLength: return RTCStringFmt("%d (BadLength)", xRc); break;
391 case BadImplementation: return RTCStringFmt("%d (BadImplementation)", xRc); break;
[42261]392 }
[55707]393 return RTCStringFmt("%d (unknown)", xRc);
[42261]394}
395
[63566]396/** @todo Make this iterative. */
[99595]397Window VBClX11DnDXHelpers::applicationWindowBelowCursor(Window wndParent) const
[42261]398{
399 /* No parent, nothing to do. */
[49891]400 if(wndParent == 0)
[42261]401 return 0;
402
[49891]403 Window wndApp = 0;
[42261]404 int cProps = -1;
[56651]405
[42261]406 /* Fetch all x11 window properties of the parent window. */
[49891]407 Atom *pProps = XListProperties(m_pDisplay, wndParent, &cProps);
[42261]408 if (cProps > 0)
409 {
410 /* We check the window for the WM_STATE property. */
[49891]411 for (int i = 0; i < cProps; ++i)
[56651]412 {
[49891]413 if (pProps[i] == xAtom(XA_WM_STATE))
[42261]414 {
415 /* Found it. */
[49891]416 wndApp = wndParent;
[42261]417 break;
418 }
[56651]419 }
420
[42261]421 /* Cleanup */
422 XFree(pProps);
423 }
424
[49891]425 if (!wndApp)
[42261]426 {
[49891]427 Window wndChild, wndTemp;
[42261]428 int tmp;
429 unsigned int utmp;
[50724]430
[42261]431 /* Query the next child window of the parent window at the current
432 * mouse position. */
[49891]433 XQueryPointer(m_pDisplay, wndParent, &wndTemp, &wndChild, &tmp, &tmp, &tmp, &tmp, &utmp);
[50724]434
[42261]435 /* Recursive call our self to dive into the child tree. */
[49891]436 wndApp = applicationWindowBelowCursor(wndChild);
[42261]437 }
438
[49891]439 return wndApp;
[42261]440}
441
[55459]442#ifdef DEBUG
[55918]443# define VBOX_DND_FN_DECL_LOG(x) inline x /* For LogFlowXXX logging. */
[55459]444#else
445# define VBOX_DND_FN_DECL_LOG(x) x
446#endif
447
[85920]448/**
449 * Class which handles a single drag'n drop proxy window.
450 ** @todo Move all proxy window-related stuff into this class! Clean up this mess.
451 */
[99595]452class VBClX11DnDProxyWnd
[56781]453{
454
455public:
[79482]456#ifdef RT_NEED_NEW_AND_DELETE
457 RTMEM_IMPLEMENT_NEW_AND_DELETE();
458#endif
[99595]459 VBClX11DnDProxyWnd(void);
460 virtual ~VBClX11DnDProxyWnd(void);
[56781]461
462public:
463
464 int init(Display *pDisplay);
465 void destroy();
466
[74439]467 int sendFinished(Window hWndSource, VBOXDNDACTION dndAction);
[56781]468
469public:
470
471 Display *pDisp;
472 /** Proxy window handle. */
473 Window hWnd;
474 int iX;
475 int iY;
476 int iWidth;
477 int iHeight;
478};
479
[79482]480/** This class only serve to avoid dragging in generic new() and delete(). */
[99595]481class VBClX11DnDWrappedXEvent
[79482]482{
483public:
484 XEvent m_Event;
485
486public:
487#ifdef RT_NEED_NEW_AND_DELETE
488 RTMEM_IMPLEMENT_NEW_AND_DELETE();
489#endif
[99595]490 VBClX11DnDWrappedXEvent(const XEvent &a_rSrcEvent)
[79482]491 {
492 m_Event = a_rSrcEvent;
493 }
494
[99595]495 VBClX11DnDWrappedXEvent()
[79482]496 {
497 RT_ZERO(m_Event);
498 }
499
[99595]500 VBClX11DnDWrappedXEvent &operator=(const XEvent &a_rSrcEvent)
[79482]501 {
502 m_Event = a_rSrcEvent;
503 return *this;
504 }
505};
506
[55918]507/**
508 * Class for handling a single drag and drop operation, that is,
509 * one source and one target at a time.
510 *
511 * For now only one DragInstance will exits when the app is running.
512 */
[99595]513class VBClX11DnDInst
[42261]514{
515public:
[50724]516
[42261]517 enum State
518 {
[50724]519 Uninitialized = 0,
[42261]520 Initialized,
521 Dragging,
[55820]522 Dropped,
523 State_32BIT_Hack = 0x7fffffff
[42261]524 };
525
526 enum Mode
527 {
[50724]528 Unknown = 0,
[42261]529 HG,
[55820]530 GH,
531 Mode_32Bit_Hack = 0x7fffffff
[42261]532 };
533
[79482]534#ifdef RT_NEED_NEW_AND_DELETE
535 RTMEM_IMPLEMENT_NEW_AND_DELETE();
536#endif
[99595]537 VBClX11DnDInst(Display *pDisplay, VBClX11DnDSvc *pParent);
[50724]538
539public:
540
[74409]541 int init(uint32_t uScreenID);
[86871]542 int term(void);
543 void stop(void);
[50724]544 void reset(void);
[42261]545
[50724]546 /* X11 message processing. */
[51529]547 int onX11ClientMessage(const XEvent &e);
[56651]548 int onX11MotionNotify(const XEvent &e);
549 int onX11SelectionClear(const XEvent &e);
[50724]550 int onX11SelectionNotify(const XEvent &e);
[85922]551 int onX11SelectionRequest(const XEvent &evReq);
[50724]552 int onX11Event(const XEvent &e);
[56651]553 int waitForStatusChange(uint32_t enmState, RTMSINTERVAL uTimeoutMS = 30000);
[50724]554 bool waitForX11Msg(XEvent &evX, int iType, RTMSINTERVAL uTimeoutMS = 100);
555 bool waitForX11ClientMsg(XClientMessageEvent &evMsg, Atom aType, RTMSINTERVAL uTimeoutMS = 100);
556
[74472]557 /* Session handling. */
558 int checkForSessionChange(void);
559
560#ifdef VBOX_WITH_DRAG_AND_DROP_GH
561 /* Guest -> Host handling. */
562 int ghIsDnDPending(void);
563 int ghDropped(const RTCString &strFormat, VBOXDNDACTION dndActionRequested);
564#endif
565
[55918]566 /* Host -> Guest handling. */
[74439]567 int hgEnter(const RTCList<RTCString> &formats, VBOXDNDACTIONLIST dndListActionsAllowed);
[55918]568 int hgLeave(void);
[74439]569 int hgMove(uint32_t uPosX, uint32_t uPosY, VBOXDNDACTION dndActionDefault);
570 int hgDrop(uint32_t uPosX, uint32_t uPosY, VBOXDNDACTION dndActionDefault);
[85371]571 int hgDataReceive(PVBGLR3GUESTDNDMETADATA pMeta);
[42261]572
[50724]573 /* X11 helpers. */
[97739]574 int mouseCursorFakeMove(void);
575 int mouseCursorMove(int iPosX, int iPosY);
[55846]576 void mouseButtonSet(Window wndDest, int rx, int ry, int iButton, bool fPress);
[56651]577 int proxyWinShow(int *piRootX = NULL, int *piRootY = NULL) const;
[50734]578 int proxyWinHide(void);
[42261]579
[56651]580 /* X11 window helpers. */
581 char *wndX11GetNameA(Window wndThis) const;
582
583 /* Xdnd protocol helpers. */
[55820]584 void wndXDnDClearActionList(Window wndThis) const;
[55918]585 void wndXDnDClearFormatList(Window wndThis) const;
[55820]586 int wndXDnDGetActionList(Window wndThis, VBoxDnDAtomList &lstActions) const;
[55918]587 int wndXDnDGetFormatList(Window wndThis, VBoxDnDAtomList &lstTypes) const;
[55820]588 int wndXDnDSetActionList(Window wndThis, const VBoxDnDAtomList &lstActions) const;
[55918]589 int wndXDnDSetFormatList(Window wndThis, Atom atmProp, const VBoxDnDAtomList &lstFormats) const;
[42261]590
[56651]591 /* Atom / HGCM formatting helpers. */
[85921]592 int appendFormatsToList(const RTCList<RTCString> &lstFormats, VBoxDnDAtomList &lstAtoms) const;
593 int appendDataToList(const void *pvData, uint32_t cbData, VBoxDnDAtomList &lstAtoms) const;
[74439]594 static Atom toAtomAction(VBOXDNDACTION dndAction);
595 static int toAtomActions(VBOXDNDACTIONLIST dndActionList, VBoxDnDAtomList &lstAtoms);
[55918]596 static uint32_t toHGCMAction(Atom atom);
597 static uint32_t toHGCMActions(const VBoxDnDAtomList &actionsList);
[42261]598
[50724]599protected:
600
[55422]601 /** The instance's own DnD context. */
602 VBGLR3GUESTDNDCMDCTX m_dndCtx;
[55918]603 /** Pointer to service instance. */
[99595]604 VBClX11DnDSvc *m_pParent;
[55918]605 /** Pointer to X display operating on. */
[55422]606 Display *m_pDisplay;
[55918]607 /** X screen ID to operate on. */
[74409]608 int m_screenID;
[55918]609 /** Pointer to X screen operating on. */
[55422]610 Screen *m_pScreen;
[55918]611 /** Root window handle. */
[55422]612 Window m_wndRoot;
[56781]613 /** Proxy window. */
[99595]614 VBClX11DnDProxyWnd m_wndProxy;
[55918]615 /** Current source/target window handle. */
[55422]616 Window m_wndCur;
[97735]617 /** The XDnD protocol version the current source/target window is using.
618 * Set to 0 if not available / not set yet. */
619 uint8_t m_uXdndVer;
[97739]620 /** Last mouse X position (in pixels, absolute to root window).
621 * Set to -1 if not set yet. */
622 int m_lastMouseX;
623 /** Last mouse Y position (in pixels, absolute to root window).
624 * Set to -1 if not set yet. */
625 int m_lastMouseY;
[97826]626 /** List of default (Atom) formats required for X11 Xdnd handling.
627 * This list will be included by \a m_lstAtomFormats. */
628 VBoxDnDAtomList m_lstAtomFormatsX11;
[97734]629 /** List of (Atom) formats the current source/target window supports. */
[85921]630 VBoxDnDAtomList m_lstAtomFormats;
[97734]631 /** List of (Atom) actions the current source/target window supports. */
[85921]632 VBoxDnDAtomList m_lstAtomActions;
[56651]633 /** Buffer for answering the target window's selection request. */
634 void *m_pvSelReqData;
635 /** Size (in bytes) of selection request data buffer. */
636 uint32_t m_cbSelReqData;
[50724]637 /** Current operation mode. */
[56651]638 volatile uint32_t m_enmMode;
[50724]639 /** Current state of operation mode. */
[56651]640 volatile uint32_t m_enmState;
[50724]641 /** The instance's own X event queue. */
[99595]642 RTCMTList<VBClX11DnDWrappedXEvent> m_eventQueueList;
[97734]643 /** Critical section for providing serialized access to list event queue's contents. */
[55422]644 RTCRITSECT m_eventQueueCS;
[97734]645 /** Event for notifying this instance in case of a new event. */
[56651]646 RTSEMEVENT m_eventQueueEvent;
647 /** Critical section for data access. */
648 RTCRITSECT m_dataCS;
[51556]649 /** List of allowed formats. */
[55422]650 RTCList<RTCString> m_lstAllowedFormats;
[57283]651 /** Number of failed attempts by the host
652 * to query for an active drag and drop operation on the guest. */
653 uint16_t m_cFailedPendingAttempts;
[42261]654};
655
656
[85920]657/*********************************************************************************************************************************
658 * DragInstanc implementation. *
659 ********************************************************************************************************************************/
[42261]660
[99595]661VBClX11DnDInst::VBClX11DnDInst(Display *pDisplay, VBClX11DnDSvc *pParent)
[55422]662 : m_pParent(pParent)
663 , m_pDisplay(pDisplay)
664 , m_pScreen(0)
665 , m_wndRoot(0)
666 , m_wndCur(0)
[97735]667 , m_uXdndVer(0)
[56651]668 , m_pvSelReqData(NULL)
669 , m_cbSelReqData(0)
[55820]670 , m_enmMode(Unknown)
671 , m_enmState(Uninitialized)
[42261]672{
[97826]673 /* Append default targets we support.
674 * Note: The order is sorted by preference; be careful when changing this. */
675 m_lstAtomFormatsX11.append(xAtom(XA_TARGETS));
676 m_lstAtomFormatsX11.append(xAtom(XA_MULTIPLE));
677 /** @todo Support INC (incremental transfers). */
[42261]678}
679
[55918]680/**
[86871]681 * Stops this drag instance.
[55918]682 */
[99595]683void VBClX11DnDInst::stop(void)
[42261]684{
[56651]685 LogFlowFuncEnter();
686
[86871]687 int rc2 = VbglR3DnDDisconnect(&m_dndCtx);
688 AssertRC(rc2);
689
690 LogFlowFuncLeave();
691}
692
693/**
694 * Terminates (destroys) this drag instance.
695 *
696 * @return VBox status code.
697 */
[99595]698int VBClX11DnDInst::term(void)
[86871]699{
700 LogFlowFuncEnter();
701
[56781]702 if (m_wndProxy.hWnd != 0)
703 XDestroyWindow(m_pDisplay, m_wndProxy.hWnd);
[49891]704
[86871]705 int rc = VbglR3DnDDisconnect(&m_dndCtx);
706 AssertRCReturn(rc, rc);
[49891]707
[56651]708 if (m_pvSelReqData)
709 RTMemFree(m_pvSelReqData);
710
[86871]711 rc = RTSemEventDestroy(m_eventQueueEvent);
712 AssertRCReturn(rc, rc);
[56651]713
[86871]714 rc = RTCritSectDelete(&m_eventQueueCS);
715 AssertRCReturn(rc, rc);
[56651]716
[86871]717 rc = RTCritSectDelete(&m_dataCS);
718 AssertRCReturn(rc, rc);
719
720 LogFlowFuncLeaveRC(rc);
721 return rc;
[42261]722}
723
[55918]724/**
725 * Resets this drag instance.
726 */
[99595]727void VBClX11DnDInst::reset(void)
[42261]728{
[55707]729 LogFlowFuncEnter();
730
[42261]731 /* Hide the proxy win. */
[50724]732 proxyWinHide();
733
[56651]734 int rc2 = RTCritSectEnter(&m_dataCS);
735 if (RT_SUCCESS(rc2))
736 {
737 /* If we are currently the Xdnd selection owner, clear that. */
738 Window pWnd = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
[56781]739 if (pWnd == m_wndProxy.hWnd)
[56651]740 XSetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection), None, CurrentTime);
[50724]741
[56651]742 /* Clear any other DnD specific data on the proxy window. */
[56781]743 wndXDnDClearFormatList(m_wndProxy.hWnd);
744 wndXDnDClearActionList(m_wndProxy.hWnd);
[50724]745
[85921]746 m_lstAtomActions.clear();
747
[97826]748 /* First, clear the formats list and apply the X11-specific default formats,
749 * required for making Xdnd to work. */
[85921]750 m_lstAtomFormats.clear();
[97826]751 m_lstAtomFormats.append(m_lstAtomFormatsX11);
[85921]752
[97739]753 m_wndCur = 0;
754 m_uXdndVer = 0;
755 m_lastMouseX = -1;
756 m_lastMouseY = -1;
757 m_enmState = Initialized;
758 m_enmMode = Unknown;
[57283]759 m_cFailedPendingAttempts = 0;
[56651]760
761 /* Reset the selection request buffer. */
762 if (m_pvSelReqData)
763 {
764 RTMemFree(m_pvSelReqData);
765 m_pvSelReqData = NULL;
766
767 Assert(m_cbSelReqData);
768 m_cbSelReqData = 0;
769 }
770
[97740]771 rc2 = RTCritSectEnter(&m_eventQueueCS);
772 if (RT_SUCCESS(rc2))
773 {
774 m_eventQueueList.clear();
775
776 rc2 = RTCritSectLeave(&m_eventQueueCS);
777 AssertRC(rc2);
778 }
779
[56651]780 RTCritSectLeave(&m_dataCS);
781 }
[97734]782
783 LogFlowFuncLeave();
[42261]784}
785
[55918]786/**
787 * Initializes this drag instance.
788 *
789 * @return IPRT status code.
[74409]790 * @param uScreenID X' screen ID to use.
[55918]791 */
[99595]792int VBClX11DnDInst::init(uint32_t uScreenID)
[42261]793{
[60967]794 int rc = VbglR3DnDConnect(&m_dndCtx);
795 /* Note: Can return VINF_PERMISSION_DENIED if HGCM host service is not available. */
796 if (rc != VINF_SUCCESS)
797 return rc;
[49891]798
[97734]799 if (g_cVerbosity)
800 {
801 RTCString strBody = RTCStringFmt("Connected (screen %RU32, verbosity %u)", uScreenID, g_cVerbosity);
802 VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER, strBody.c_str());
803 }
804
[42261]805 do
806 {
[56651]807 rc = RTSemEventCreate(&m_eventQueueEvent);
[50724]808 if (RT_FAILURE(rc))
809 break;
810
811 rc = RTCritSectInit(&m_eventQueueCS);
812 if (RT_FAILURE(rc))
813 break;
814
[56651]815 rc = RTCritSectInit(&m_dataCS);
816 if (RT_FAILURE(rc))
817 break;
818
[49891]819 /*
820 * Enough screens configured in the x11 server?
821 */
[74409]822 if ((int)uScreenID > ScreenCount(m_pDisplay))
[42261]823 {
[49891]824 rc = VERR_INVALID_PARAMETER;
[42261]825 break;
826 }
[55820]827#if 0
[42261]828 /* Get the screen number from the x11 server. */
[74409]829 pDrag->screen = ScreenOfDisplay(m_pDisplay, uScreenID);
[55820]830 if (!pDrag->screen)
831 {
832 rc = VERR_GENERAL_FAILURE;
833 break;
834 }
835#endif
[74409]836 m_screenID = uScreenID;
[55820]837
[42261]838 /* Now query the corresponding root window of this screen. */
[74409]839 m_wndRoot = RootWindow(m_pDisplay, m_screenID);
[49891]840 if (!m_wndRoot)
[42261]841 {
842 rc = VERR_GENERAL_FAILURE;
843 break;
844 }
[49891]845
846 /*
847 * Create an invisible window which will act as proxy for the DnD
[42261]848 * operation. This window will be used for both the GH and HG
[49891]849 * direction.
850 */
[42261]851 XSetWindowAttributes attr;
852 RT_ZERO(attr);
[51529]853 attr.event_mask = EnterWindowMask | LeaveWindowMask
[50724]854 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
[55820]855 attr.override_redirect = True;
[50724]856 attr.do_not_propagate_mask = NoEventMask;
[97734]857
858 if (g_cVerbosity >= 3)
859 {
860 attr.background_pixel = XWhitePixel(m_pDisplay, m_screenID);
861 attr.border_pixel = XBlackPixel(m_pDisplay, m_screenID);
862 m_wndProxy.hWnd = XCreateWindow(m_pDisplay, m_wndRoot /* Parent */,
863 100, 100, /* Position */
864 100, 100, /* Width + height */
865 2, /* Border width */
866 CopyFromParent, /* Depth */
867 InputOutput, /* Class */
868 CopyFromParent, /* Visual */
869 CWBackPixel
870 | CWBorderPixel
871 | CWOverrideRedirect
872 | CWDontPropagate, /* Value mask */
873 &attr); /* Attributes for value mask */
874 }
875
876 m_wndProxy.hWnd = XCreateWindow(m_pDisplay, m_wndRoot /* Parent */,
877 0, 0, /* Position */
878 1, 1, /* Width + height */
879 0, /* Border width */
880 CopyFromParent, /* Depth */
881 InputOnly, /* Class */
882 CopyFromParent, /* Visual */
883 CWOverrideRedirect | CWDontPropagate, /* Value mask */
884 &attr); /* Attributes for value mask */
885
[56781]886 if (!m_wndProxy.hWnd)
[42261]887 {
[81040]888 VBClLogError("Error creating proxy window\n");
[42261]889 rc = VERR_GENERAL_FAILURE;
890 break;
891 }
[49891]892
[56781]893 rc = m_wndProxy.init(m_pDisplay);
894 if (RT_FAILURE(rc))
895 {
[81040]896 VBClLogError("Error initializing proxy window, rc=%Rrc\n", rc);
[56781]897 break;
898 }
899
[97734]900 if (g_cVerbosity >= 3) /* Make debug window visible. */
901 {
902 XFlush(m_pDisplay);
903 XMapWindow(m_pDisplay, m_wndProxy.hWnd);
904 XRaiseWindow(m_pDisplay, m_wndProxy.hWnd);
905 XFlush(m_pDisplay);
906 }
[50724]907
[97734]908 VBClLogInfo("Proxy window=%#x (debug mode: %RTbool), root window=%#x ...\n",
909 m_wndProxy.hWnd, RT_BOOL(g_cVerbosity >= 3), m_wndRoot);
910
[50724]911 /* Set the window's name for easier lookup. */
[56781]912 XStoreName(m_pDisplay, m_wndProxy.hWnd, "VBoxClientWndDnD");
[50724]913
[42261]914 /* Make the new window Xdnd aware. */
[85920]915 Atom atmVer = VBOX_XDND_VERSION;
[56781]916 XChangeProperty(m_pDisplay, m_wndProxy.hWnd, xAtom(XA_XdndAware), XA_ATOM, 32, PropModeReplace,
[85920]917 reinterpret_cast<unsigned char*>(&atmVer), 1);
[46377]918 } while (0);
[42261]919
[49891]920 if (RT_SUCCESS(rc))
[50724]921 {
[56651]922 reset();
[50724]923 }
924 else
[81040]925 VBClLogError("Initializing drag instance for screen %RU32 failed with rc=%Rrc\n", uScreenID, rc);
[42261]926
[49891]927 LogFlowFuncLeaveRC(rc);
[42261]928 return rc;
929}
930
[55918]931/**
932 * Callback handler for a generic client message from a window.
933 *
934 * @return IPRT status code.
935 * @param e X11 event to handle.
936 */
[99595]937int VBClX11DnDInst::onX11ClientMessage(const XEvent &e)
[50724]938{
939 AssertReturn(e.type == ClientMessage, VERR_INVALID_PARAMETER);
940
[56651]941 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
[55820]942 LogFlowThisFunc(("Event wnd=%#x, msg=%s\n", e.xclient.window, xAtomToString(e.xclient.message_type).c_str()));
943
[56651]944 int rc = VINF_SUCCESS;
[50724]945
[97734]946 char *pszWndCurName = wndX11GetNameA(m_wndCur);
947 AssertPtrReturn(pszWndCurName, VERR_NO_MEMORY);
948
[55820]949 switch (m_enmMode)
[50724]950 {
951 case HG:
952 {
[55918]953 /*
[55820]954 * Client messages are used to inform us about the status of a XdndAware
[55918]955 * window, in response of some events we send to them.
956 */
[97734]957
958 /* The target window informs us of the current Xdnd status. */
[85925]959 if (e.xclient.message_type == xAtom(XA_XdndStatus))
[50724]960 {
[97734]961 Window wndTgt = static_cast<Window>(e.xclient.data.l[XdndStatusWindow]);
[85923]962
[97734]963 char *pszWndTgtName = wndX11GetNameA(wndTgt);
964 AssertPtrBreakStmt(pszWndTgtName, VERR_NO_MEMORY);
965
[85923]966 /* Does the target accept the drop? */
[97735]967 bool const fAcceptDrop = RT_BOOL(e.xclient.data.l[XdndStatusFlags] & VBOX_XDND_STATUS_FLAG_ACCEPT);
[85923]968 /* Does the target want XdndPosition messages? */
[97735]969 bool const fWantsPosition = RT_BOOL(e.xclient.data.l[XdndStatusFlags] & VBOX_XDND_STATUS_FLAG_WANTS_POS);
[85923]970
[55918]971 /*
[55820]972 * The XdndStatus message tell us if the window will accept the DnD
[50724]973 * event and with which action. We immediately send this info down to
[55918]974 * the host as a response of a previous DnD message.
975 */
[85923]976 RTCString strActions = xAtomToString(e.xclient.data.l[XdndStatusAction]);
[50724]977
[97734]978 VBClLogInfo("Target window %#x ('%s')\n", wndTgt, pszWndTgtName);
979 VBClLogInfo(" - %s accept data (actions '%s')\n", fAcceptDrop ? "does" : "does not", strActions.c_str());
980 VBClLogInfo(" - %s want position messages\n", fWantsPosition ? "does" : "does not");
[56651]981
[97734]982 uint16_t const x = RT_HI_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgXY]);
983 uint16_t const y = RT_LO_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgXY]);
984 uint16_t const cx = RT_HI_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgWH]);
985 uint16_t const cy = RT_LO_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgWH]);
[50724]986
[85923]987 if (cx && cy)
988 {
989 VBClLogInfo("Target window %#x ('%s') reported dead area at %RU16,%RU16 (%RU16 x %RU16)\n",
[97734]990 wndTgt, pszWndTgtName, x, y, cx, cy);
[85923]991 /** @todo Save dead area and don't send XdndPosition messages anymore into it. */
992 }
993
[97734]994 if (m_wndCur == wndTgt)
[85923]995 {
996 VBOXDNDACTION dndAction = VBOX_DND_ACTION_IGNORE; /* Default is ignoring. */
997 /** @todo Compare this with the allowed actions. */
998 if (fAcceptDrop)
999 dndAction = toHGCMAction(static_cast<Atom>(e.xclient.data.l[XdndStatusAction]));
1000
1001 rc = VbglR3DnDHGSendAckOp(&m_dndCtx, dndAction);
1002 }
1003 else
[97734]1004 VBClLogInfo("Target window %#x ('%s') is not our current window, skipping\n", wndTgt, pszWndTgtName);
[85923]1005
[97734]1006 RTStrFree(pszWndTgtName);
[50724]1007 }
[97734]1008 /* The target window informs us that it finished the Xdnd operation and that we may free all data. */
[50724]1009 else if (e.xclient.message_type == xAtom(XA_XdndFinished))
1010 {
[85923]1011 Window wndTarget = static_cast<Window>(e.xclient.data.l[XdndFinishedWindow]);
[50724]1012
[97734]1013 char *pszWndTgtName = wndX11GetNameA(wndTarget);
1014 AssertPtrBreakStmt(pszWndTgtName, VERR_NO_MEMORY);
[85923]1015
[97735]1016 if (m_uXdndVer >= 5)
[97734]1017 {
1018 const bool fSucceeded = e.xclient.data.l[XdndFinishedFlags] & VBOX_XDND_FINISHED_FLAG_SUCCEEDED;
1019 #if 0 /** @todo Returns garbage -- investigate this! */
1020 //const char *pcszAction = fSucceeded ? xAtomToString(e.xclient.data.l[XdndFinishedAction]).c_str() : NULL;
1021 #endif
1022 VBClLogInfo("Target window %#x ('%s') has %s the data\n",
1023 wndTarget, pszWndTgtName, fSucceeded ? "accepted" : "rejected");
1024 }
1025 else /* Xdnd < version 5 did not have the XdndFinishedFlags / XdndFinishedAction properties. */
1026 VBClLogInfo("Target window %#x ('%s') has accepted the data\n", wndTarget, pszWndTgtName);
[56651]1027
[97734]1028 RTStrFree(pszWndTgtName);
[85923]1029
[56651]1030 reset();
[50724]1031 }
1032 else
1033 {
[85923]1034 LogFlowThisFunc(("Unhandled client message '%s'\n", xAtomToString(e.xclient.message_type).c_str()));
[50724]1035 rc = VERR_NOT_SUPPORTED;
1036 }
1037
1038 break;
1039 }
1040
[56651]1041 case Unknown: /* Mode not set (yet). */
[97734]1042 RT_FALL_THROUGH();
[50724]1043 case GH:
1044 {
[56651]1045 /*
1046 * This message marks the beginning of a new drag and drop
1047 * operation on the guest.
1048 */
1049 if (e.xclient.message_type == xAtom(XA_XdndEnter))
1050 {
1051 /*
1052 * Get the window which currently has the XA_XdndSelection
1053 * bit set.
1054 */
[97734]1055 Window wndSel = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
1056 char *pszWndSelName = wndX11GetNameA(wndSel);
1057 AssertPtrBreakStmt(pszWndSelName, VERR_NO_MEMORY);
[56651]1058
[56781]1059 mouseButtonSet(m_wndProxy.hWnd, -1, -1, 1, true /* fPress */);
[56651]1060
1061 /*
1062 * Update our state and the window handle to process.
1063 */
[97734]1064 rc = RTCritSectEnter(&m_dataCS);
1065 if (RT_SUCCESS(rc))
[56651]1066 {
[97735]1067 uint8_t const uXdndVer = (uint8_t)e.xclient.data.l[XdndEnterFlags] >> XdndEnterVersionRShift;
[97734]1068
[97735]1069 VBClLogInfo("Entered new source window %#x ('%s'), supports Xdnd version %u\n", wndSel, pszWndSelName, uXdndVer);
[56651]1070#ifdef DEBUG
1071 XWindowAttributes xwa;
1072 XGetWindowAttributes(m_pDisplay, m_wndCur, &xwa);
1073 LogFlowThisFunc(("wndCur=%#x, x=%d, y=%d, width=%d, height=%d\n", m_wndCur, xwa.x, xwa.y, xwa.width, xwa.height));
1074#endif
1075 /*
1076 * Retrieve supported formats.
1077 */
1078
1079 /* Check if the MIME types are in the message itself or if we need
1080 * to fetch the XdndTypeList property from the window. */
1081 bool fMoreTypes = e.xclient.data.l[XdndEnterFlags] & XdndEnterMoreTypesFlag;
1082 if (!fMoreTypes)
1083 {
1084 /* Only up to 3 format types supported. */
1085 /* Start with index 2 (first item). */
1086 for (int i = 2; i < 5; i++)
1087 {
1088 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(e.xclient.data.l[i]).c_str()));
[85921]1089 m_lstAtomFormats.append(e.xclient.data.l[i]);
[56651]1090 }
1091 }
1092 else
1093 {
1094 /* More than 3 format types supported. */
[97734]1095 rc = wndXDnDGetFormatList(wndSel, m_lstAtomFormats);
[56651]1096 }
1097
[97734]1098 if (RT_FAILURE(rc))
1099 {
1100 VBClLogError("Error retrieving supported formats, rc=%Rrc\n", rc);
1101 break;
1102 }
1103
[56651]1104 /*
1105 * Retrieve supported actions.
1106 */
[97735]1107 if (uXdndVer >= 2) /* More than one action allowed since protocol version 2. */
[56651]1108 {
[97734]1109 rc = wndXDnDGetActionList(wndSel, m_lstAtomActions);
[56651]1110 }
[97734]1111 else /* Only "copy" action allowed on legacy applications. */
1112 m_lstAtomActions.append(XA_XdndActionCopy);
[56651]1113
[97734]1114 if (RT_FAILURE(rc))
[56651]1115 {
[97734]1116 VBClLogError("Error retrieving supported actions, rc=%Rrc\n", rc);
1117 break;
[56651]1118 }
1119
[97734]1120 VBClLogInfo("Source window %#x ('%s')\n", wndSel, pszWndSelName);
1121 VBClLogInfo(" - supports the formats ");
1122 for (size_t i = 0; i < m_lstAtomFormats.size(); i++)
1123 {
1124 if (i > 0)
1125 VBClLogInfo(", ");
1126 VBClLogInfo("%s", gX11->xAtomToString(m_lstAtomFormats[i]).c_str());
1127 }
1128 VBClLogInfo("\n");
1129 VBClLogInfo(" - supports the actions ");
1130 for (size_t i = 0; i < m_lstAtomActions.size(); i++)
1131 {
1132 if (i > 0)
1133 VBClLogInfo(", ");
1134 VBClLogInfo("%s", gX11->xAtomToString(m_lstAtomActions[i]).c_str());
1135 }
1136 VBClLogInfo("\n");
1137
1138 AssertBreakStmt(wndSel == (Window)e.xclient.data.l[XdndEnterWindow],
1139 rc = VERR_INVALID_PARAMETER); /* Source window. */
1140
1141 m_wndCur = wndSel;
[97735]1142 m_uXdndVer = uXdndVer;
[97734]1143 m_enmMode = GH;
1144 m_enmState = Dragging;
1145
[56651]1146 RTCritSectLeave(&m_dataCS);
1147 }
[97734]1148
1149 RTStrFree(pszWndSelName);
[56651]1150 }
1151 else if ( e.xclient.message_type == xAtom(XA_XdndPosition)
1152 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndPositionWindow]))
1153 {
[57283]1154 if (m_enmState != Dragging) /* Wrong mode? Bail out. */
1155 {
1156 reset();
1157 break;
1158 }
[62883]1159#ifdef LOG_ENABLED
1160 int32_t iPos = e.xclient.data.l[XdndPositionXY];
[97735]1161 Atom atmAction = m_uXdndVer >= 2 /* Actions other than "copy" or only supported since protocol version 2. */
[56651]1162 ? e.xclient.data.l[XdndPositionAction] : xAtom(XA_XdndActionCopy);
[97734]1163 LogFlowThisFunc(("XA_XdndPosition: wndProxy=%#x, wndCur=%#x, x=%RI32, y=%RI32, strAction=%s\n",
[62883]1164 m_wndProxy.hWnd, m_wndCur, RT_HIWORD(iPos), RT_LOWORD(iPos),
[56651]1165 xAtomToString(atmAction).c_str()));
[62883]1166#endif
[56651]1167 bool fAcceptDrop = true;
1168
1169 /* Reply with a XdndStatus message to tell the source whether
1170 * the data can be dropped or not. */
1171 XClientMessageEvent m;
1172 RT_ZERO(m);
1173 m.type = ClientMessage;
1174 m.display = m_pDisplay;
1175 m.window = e.xclient.data.l[XdndPositionWindow];
1176 m.message_type = xAtom(XA_XdndStatus);
1177 m.format = 32;
[56781]1178 m.data.l[XdndStatusWindow] = m_wndProxy.hWnd;
[97735]1179 m.data.l[XdndStatusFlags] = fAcceptDrop ? VBOX_XDND_STATUS_FLAG_ACCEPT : VBOX_XDND_STATUS_FLAG_NONE; /* Whether to accept the drop or not. */
[56651]1180
[56781]1181 /* We don't want any new XA_XdndPosition messages while being
1182 * in our proxy window. */
1183 m.data.l[XdndStatusNoMsgXY] = RT_MAKE_U32(m_wndProxy.iY, m_wndProxy.iX);
1184 m.data.l[XdndStatusNoMsgWH] = RT_MAKE_U32(m_wndProxy.iHeight, m_wndProxy.iWidth);
1185
1186 /** @todo Handle default action! */
[74411]1187 m.data.l[XdndStatusAction] = fAcceptDrop ? toAtomAction(VBOX_DND_ACTION_COPY) : None;
[56781]1188
[56651]1189 int xRc = XSendEvent(m_pDisplay, e.xclient.data.l[XdndPositionWindow],
1190 False /* Propagate */, NoEventMask, reinterpret_cast<XEvent *>(&m));
1191 if (xRc == 0)
[97734]1192 VBClLogError("Error sending position status event to current window %#x ('%s'): %s\n",
1193 m_wndCur, pszWndCurName, gX11->xErrorToString(xRc).c_str());
[56651]1194 }
1195 else if ( e.xclient.message_type == xAtom(XA_XdndLeave)
1196 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndLeaveWindow]))
1197 {
1198 LogFlowThisFunc(("XA_XdndLeave\n"));
[81040]1199 VBClLogInfo("Guest to host transfer canceled by the guest source window\n");
[56651]1200
1201 /* Start over. */
1202 reset();
1203 }
1204 else if ( e.xclient.message_type == xAtom(XA_XdndDrop)
1205 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndDropWindow]))
1206 {
1207 LogFlowThisFunc(("XA_XdndDrop\n"));
1208
[57283]1209 if (m_enmState != Dropped) /* Wrong mode? Bail out. */
1210 {
1211 /* Can occur when dragging from guest->host, but then back in to the guest again. */
[81040]1212 VBClLogInfo("Could not drop on own proxy window\n"); /* Not fatal. */
[56781]1213
[57283]1214 /* Let the source know. */
[74411]1215 rc = m_wndProxy.sendFinished(m_wndCur, VBOX_DND_ACTION_IGNORE);
[57283]1216
1217 /* Start over. */
1218 reset();
1219 break;
1220 }
1221
1222 m_eventQueueList.append(e);
1223 rc = RTSemEventSignal(m_eventQueueEvent);
[56651]1224 }
[74409]1225 else /* Unhandled event, abort. */
[56651]1226 {
[81040]1227 VBClLogInfo("Unhandled event from wnd=%#x, msg=%s\n", e.xclient.window, xAtomToString(e.xclient.message_type).c_str());
[56651]1228
[56781]1229 /* Let the source know. */
[74411]1230 rc = m_wndProxy.sendFinished(m_wndCur, VBOX_DND_ACTION_IGNORE);
[56781]1231
1232 /* Start over. */
1233 reset();
[56651]1234 }
[50724]1235 break;
1236 }
[55918]1237
[50724]1238 default:
1239 {
[55820]1240 AssertMsgFailed(("Drag and drop mode not implemented: %RU32\n", m_enmMode));
1241 rc = VERR_NOT_IMPLEMENTED;
[50724]1242 break;
1243 }
1244 }
1245
[97734]1246 RTStrFree(pszWndCurName);
1247
[50724]1248 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1249 return rc;
1250}
1251
[99595]1252int VBClX11DnDInst::onX11MotionNotify(const XEvent &e)
[56651]1253{
[62883]1254 RT_NOREF1(e);
[56651]1255 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1256
1257 return VINF_SUCCESS;
1258}
1259
[55918]1260/**
[56651]1261 * Callback handler for being notified if some other window now
1262 * is the owner of the current selection.
1263 *
1264 * @return IPRT status code.
1265 * @param e X11 event to handle.
1266 *
1267 * @remark
1268 */
[99595]1269int VBClX11DnDInst::onX11SelectionClear(const XEvent &e)
[56651]1270{
[62883]1271 RT_NOREF1(e);
[56651]1272 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1273
1274 return VINF_SUCCESS;
1275}
1276
1277/**
[55918]1278 * Callback handler for a XDnD selection notify from a window. This is needed
1279 * to let the us know if a certain window has drag'n drop data to share with us,
1280 * e.g. our proxy window.
1281 *
1282 * @return IPRT status code.
1283 * @param e X11 event to handle.
1284 */
[99595]1285int VBClX11DnDInst::onX11SelectionNotify(const XEvent &e)
[50724]1286{
1287 AssertReturn(e.type == SelectionNotify, VERR_INVALID_PARAMETER);
1288
[56651]1289 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
[50724]1290
[55820]1291 int rc;
[50724]1292
[55820]1293 switch (m_enmMode)
[50724]1294 {
1295 case GH:
1296 {
[55820]1297 if (m_enmState == Dropped)
[50724]1298 {
[56651]1299 m_eventQueueList.append(e);
1300 rc = RTSemEventSignal(m_eventQueueEvent);
[50724]1301 }
[56651]1302 else
1303 rc = VERR_WRONG_ORDER;
[50724]1304 break;
1305 }
1306
1307 default:
1308 {
1309 LogFlowThisFunc(("Unhandled: wnd=%#x, msg=%s\n",
1310 e.xclient.data.l[0], xAtomToString(e.xclient.message_type).c_str()));
1311 rc = VERR_INVALID_STATE;
1312 break;
1313 }
1314 }
1315
1316 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1317 return rc;
1318}
1319
[55918]1320/**
1321 * Callback handler for a XDnD selection request from a window. This is needed
1322 * to retrieve the data required to complete the actual drag'n drop operation.
1323 *
1324 * @returns IPRT status code.
[85922]1325 * @param evReq X11 event to handle.
[55918]1326 */
[99595]1327int VBClX11DnDInst::onX11SelectionRequest(const XEvent &evReq)
[50724]1328{
[85920]1329 AssertReturn(evReq.type == SelectionRequest, VERR_INVALID_PARAMETER);
[50724]1330
[85920]1331 const XSelectionRequestEvent *pEvReq = &evReq.xselectionrequest;
1332
[97734]1333 char *pszWndSrcName = wndX11GetNameA(pEvReq->owner);
1334 AssertPtrReturn(pszWndSrcName, VERR_INVALID_POINTER);
1335 char *pszWndTgtName = wndX11GetNameA(pEvReq->requestor);
1336 AssertPtrReturn(pszWndTgtName, VERR_INVALID_POINTER);
1337
[56651]1338 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
[97734]1339 LogFlowThisFunc(("Event owner=%#x ('%s'), requestor=%#x ('%s'), selection=%s, target=%s, prop=%s, time=%u\n",
1340 pEvReq->owner, pszWndSrcName,
1341 pEvReq->requestor, pszWndTgtName,
[85920]1342 xAtomToString(pEvReq->selection).c_str(),
1343 xAtomToString(pEvReq->target).c_str(),
1344 xAtomToString(pEvReq->property).c_str(),
1345 pEvReq->time));
[97734]1346
1347 VBClLogInfo("Window '%s' is asking '%s' for '%s' / '%s'\n",
1348 pszWndTgtName, pszWndSrcName, xAtomToString(pEvReq->selection).c_str(), xAtomToString(pEvReq->property).c_str());
1349
1350 RTStrFree(pszWndSrcName);
1351 /* Note: pszWndTgtName will be free'd below. */
1352
[50724]1353 int rc;
1354
[55820]1355 switch (m_enmMode)
[50724]1356 {
1357 case HG:
1358 {
1359 rc = VINF_SUCCESS;
1360
1361 /*
[56651]1362 * Start by creating a refusal selection notify message.
1363 * That way we only need to care for the success case.
[50724]1364 */
1365
[85920]1366 XEvent evResp;
1367 RT_ZERO(evResp);
[56651]1368
[85920]1369 XSelectionEvent *pEvResp = &evResp.xselection;
[56651]1370
[85920]1371 pEvResp->type = SelectionNotify;
1372 pEvResp->display = pEvReq->display;
1373 pEvResp->requestor = pEvReq->requestor;
1374 pEvResp->selection = pEvReq->selection;
1375 pEvResp->target = pEvReq->target;
1376 pEvResp->property = None; /* "None" means refusal. */
1377 pEvResp->time = pEvReq->time;
1378
[97734]1379 if (g_cVerbosity)
1380 {
1381 VBClLogVerbose(1, "Supported formats by VBoxClient:\n");
1382 for (size_t i = 0; i < m_lstAtomFormats.size(); i++)
1383 VBClLogVerbose(1, "\t%s\n", xAtomToString(m_lstAtomFormats.at(i)).c_str());
1384 }
1385
[50724]1386 /* Is the requestor asking for the possible MIME types? */
[85920]1387 if (pEvReq->target == xAtom(XA_TARGETS))
[50724]1388 {
[97734]1389 VBClLogInfo("Target window %#x ('%s') asking for target list\n", pEvReq->requestor, pszWndTgtName);
[50724]1390
1391 /* If so, set the window property with the formats on the requestor
1392 * window. */
[85921]1393 rc = wndXDnDSetFormatList(pEvReq->requestor, pEvReq->property, m_lstAtomFormats);
[55918]1394 if (RT_SUCCESS(rc))
[85920]1395 pEvResp->property = pEvReq->property;
[50724]1396 }
1397 /* Is the requestor asking for a specific MIME type (we support)? */
[85921]1398 else if (m_lstAtomFormats.contains(pEvReq->target))
[50724]1399 {
[81040]1400 VBClLogInfo("Target window %#x ('%s') is asking for data as '%s'\n",
[97734]1401 pEvReq->requestor, pszWndTgtName, xAtomToString(pEvReq->target).c_str());
[50724]1402
[85927]1403#ifdef VBOX_WITH_DRAG_AND_DROP_PROMISES
1404# error "Implement me!"
1405#else
[56651]1406 /* Did we not drop our stuff to the guest yet? Bail out. */
[55820]1407 if (m_enmState != Dropped)
[50724]1408 {
[85920]1409 VBClLogError("Data not dropped by the host on the guest yet (client state %RU32, mode %RU32), refusing selection request by guest\n",
1410 m_enmState, m_enmMode);
[50724]1411 }
[56651]1412 /* Did we not store the requestor's initial selection request yet? Then do so now. */
[50724]1413 else
1414 {
[85927]1415#endif /* VBOX_WITH_DRAG_AND_DROP_PROMISES */
[56651]1416 /* Get the data format the requestor wants from us. */
[97734]1417 VBClLogInfo("Target window %#x ('%s') requested data from host as '%s', rc=%Rrc\n",
1418 pEvReq->requestor, pszWndTgtName, xAtomToString(pEvReq->target).c_str(), rc);
[50724]1419
[56651]1420 /* Make a copy of the MIME data to be passed back. The X server will be become
1421 * the new owner of that data, so no deletion needed. */
1422 /** @todo Do we need to do some more conversion here? XConvertSelection? */
[97734]1423 AssertMsgBreakStmt(m_pvSelReqData != NULL, ("Selection request data is NULL\n"), rc = VERR_INVALID_PARAMETER);
1424 AssertMsgBreakStmt(m_cbSelReqData > 0, ("Selection request data size is 0\n"), rc = VERR_INVALID_PARAMETER);
[50724]1425
[97734]1426 void const *pvData = RTMemDup(m_pvSelReqData, m_cbSelReqData);
1427 AssertMsgBreakStmt(pvData != NULL, ("Duplicating selection request failed\n"), rc = VERR_NO_MEMORY);
1428 uint32_t const cbData = m_cbSelReqData;
1429
[56651]1430 /* Always return the requested property. */
[85920]1431 evResp.xselection.property = pEvReq->property;
[55820]1432
[56651]1433 /* Note: Always seems to return BadRequest. Seems fine. */
[85920]1434 int xRc = XChangeProperty(pEvResp->display, pEvResp->requestor, pEvResp->property,
1435 pEvResp->target, 8, PropModeReplace,
[56651]1436 reinterpret_cast<const unsigned char*>(pvData), cbData);
1437
[97734]1438 LogFlowFunc(("Changing property '%s' (of type '%s') of window %#x ('%s'): %s\n",
[85920]1439 xAtomToString(pEvReq->property).c_str(),
1440 xAtomToString(pEvReq->target).c_str(),
[97734]1441 pEvReq->requestor, pszWndTgtName,
[56651]1442 gX11->xErrorToString(xRc).c_str()));
[81042]1443 RT_NOREF(xRc);
[85927]1444#ifndef VBOX_WITH_DRAG_AND_DROP_PROMISES
[50724]1445 }
[85927]1446#endif
[50724]1447 }
1448 /* Anything else. */
1449 else
1450 {
[81040]1451 VBClLogError("Refusing unknown command/format '%s' of wnd=%#x ('%s')\n",
[97734]1452 xAtomToString(pEvReq->target).c_str(), pEvReq->requestor, pszWndTgtName);
[56651]1453 rc = VERR_NOT_SUPPORTED;
[55820]1454 }
1455
[97734]1456 VBClLogVerbose(1, "Offering type '%s', property '%s' to window %#x ('%s') ...\n",
1457 xAtomToString(pEvReq->target).c_str(),
1458 xAtomToString(pEvReq->property).c_str(), pEvReq->requestor, pszWndTgtName);
[55820]1459
[85920]1460 int xRc = XSendEvent(pEvReq->display, pEvReq->requestor, True /* Propagate */, 0, &evResp);
[56651]1461 if (xRc == 0)
[97734]1462 VBClLogError("Error sending SelectionNotify(1) event to window %#x ('%s'): %s\n",
1463 pEvReq->requestor, pszWndTgtName, gX11->xErrorToString(xRc).c_str());
1464
[85920]1465 XFlush(pEvReq->display);
[50724]1466 break;
1467 }
1468
1469 default:
1470 rc = VERR_INVALID_STATE;
1471 break;
1472 }
1473
[97734]1474 RTStrFree(pszWndTgtName);
1475 pszWndTgtName = NULL;
1476
[50724]1477 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1478 return rc;
1479}
1480
[55918]1481/**
1482 * Handles X11 events, called by x11EventThread.
1483 *
1484 * @returns IPRT status code.
1485 * @param e X11 event to handle.
1486 */
[99595]1487int VBClX11DnDInst::onX11Event(const XEvent &e)
[50724]1488{
1489 int rc;
1490
1491 LogFlowThisFunc(("X11 event, type=%d\n", e.type));
1492 switch (e.type)
1493 {
[57283]1494 /*
1495 * This can happen if a guest->host drag operation
1496 * goes back from the host to the guest. This is not what
1497 * we want and thus resetting everything.
1498 */
[50734]1499 case ButtonPress:
[85920]1500 RT_FALL_THROUGH();
[57283]1501 case ButtonRelease:
[85920]1502 {
1503 VBClLogInfo("Mouse button %s\n", e.type == ButtonPress ? "pressed" : "released");
[50724]1504
[57283]1505 reset();
[85920]1506
1507 rc = VINF_SUCCESS;
[50724]1508 break;
[85920]1509 }
[50724]1510
[51529]1511 case ClientMessage:
1512 rc = onX11ClientMessage(e);
[50724]1513 break;
1514
1515 case SelectionClear:
[56651]1516 rc = onX11SelectionClear(e);
1517 break;
[50724]1518
[50734]1519 case SelectionNotify:
[51529]1520 rc = onX11SelectionNotify(e);
[50734]1521 break;
1522
[51529]1523 case SelectionRequest:
1524 rc = onX11SelectionRequest(e);
[50734]1525 break;
1526
[56651]1527 case MotionNotify:
1528 rc = onX11MotionNotify(e);
1529 break;
[50724]1530
1531 default:
1532 rc = VERR_NOT_IMPLEMENTED;
1533 break;
1534 }
1535
1536 LogFlowThisFunc(("rc=%Rrc\n", rc));
1537 return rc;
1538}
1539
[99595]1540int VBClX11DnDInst::waitForStatusChange(uint32_t enmState, RTMSINTERVAL uTimeoutMS /* = 30000 */)
[56651]1541{
1542 const uint64_t uiStart = RTTimeMilliTS();
1543 volatile uint32_t enmCurState;
1544
1545 int rc = VERR_TIMEOUT;
1546
1547 LogFlowFunc(("enmState=%RU32, uTimeoutMS=%RU32\n", enmState, uTimeoutMS));
1548
1549 do
1550 {
1551 enmCurState = ASMAtomicReadU32(&m_enmState);
1552 if (enmCurState == enmState)
1553 {
1554 rc = VINF_SUCCESS;
1555 break;
1556 }
1557 }
1558 while (RTTimeMilliTS() - uiStart < uTimeoutMS);
1559
1560 LogFlowThisFunc(("Returning %Rrc\n", rc));
1561 return rc;
1562}
1563
[50724]1564#ifdef VBOX_WITH_DRAG_AND_DROP_GH
[55918]1565/**
1566 * Waits for an X11 event of a specific type.
1567 *
1568 * @returns IPRT status code.
1569 * @param evX Reference where to store the event into.
1570 * @param iType Event type to wait for.
1571 * @param uTimeoutMS Timeout (in ms) to wait for the event.
1572 */
[99595]1573bool VBClX11DnDInst::waitForX11Msg(XEvent &evX, int iType, RTMSINTERVAL uTimeoutMS /* = 100 */)
[50724]1574{
[56651]1575 LogFlowThisFunc(("iType=%d, uTimeoutMS=%RU32, cEventQueue=%zu\n", iType, uTimeoutMS, m_eventQueueList.size()));
[50724]1576
1577 bool fFound = false;
[97735]1578 uint64_t const tsStartMs = RTTimeMilliTS();
[55707]1579
[50724]1580 do
1581 {
1582 /* Check if there is a client message in the queue. */
[56651]1583 for (size_t i = 0; i < m_eventQueueList.size(); i++)
[50724]1584 {
1585 int rc2 = RTCritSectEnter(&m_eventQueueCS);
1586 if (RT_SUCCESS(rc2))
1587 {
[79482]1588 XEvent e = m_eventQueueList.at(i).m_Event;
[50724]1589
1590 fFound = e.type == iType;
1591 if (fFound)
1592 {
[56651]1593 m_eventQueueList.removeAt(i);
[50724]1594 evX = e;
1595 }
1596
1597 rc2 = RTCritSectLeave(&m_eventQueueCS);
1598 AssertRC(rc2);
1599
1600 if (fFound)
1601 break;
1602 }
1603 }
1604
1605 if (fFound)
1606 break;
1607
[56651]1608 int rc2 = RTSemEventWait(m_eventQueueEvent, 25 /* ms */);
[50724]1609 if ( RT_FAILURE(rc2)
1610 && rc2 != VERR_TIMEOUT)
1611 {
1612 LogFlowFunc(("Waiting failed with rc=%Rrc\n", rc2));
1613 break;
1614 }
1615 }
[97735]1616 while (RTTimeMilliTS() - tsStartMs < uTimeoutMS);
[50724]1617
[97735]1618 LogFlowThisFunc(("Returning fFound=%RTbool, msRuntime=%RU64\n", fFound, RTTimeMilliTS() - tsStartMs));
[50724]1619 return fFound;
1620}
1621
[55918]1622/**
1623 * Waits for an X11 client message of a specific type.
1624 *
1625 * @returns IPRT status code.
1626 * @param evMsg Reference where to store the event into.
1627 * @param aType Event type to wait for.
1628 * @param uTimeoutMS Timeout (in ms) to wait for the event.
1629 */
[99595]1630bool VBClX11DnDInst::waitForX11ClientMsg(XClientMessageEvent &evMsg, Atom aType,
[56651]1631 RTMSINTERVAL uTimeoutMS /* = 100 */)
[50724]1632{
[51529]1633 LogFlowThisFunc(("aType=%s, uTimeoutMS=%RU32, cEventQueue=%zu\n",
[56651]1634 xAtomToString(aType).c_str(), uTimeoutMS, m_eventQueueList.size()));
[50724]1635
1636 bool fFound = false;
1637 const uint64_t uiStart = RTTimeMilliTS();
1638 do
1639 {
1640 /* Check if there is a client message in the queue. */
[56651]1641 for (size_t i = 0; i < m_eventQueueList.size(); i++)
[50724]1642 {
1643 int rc2 = RTCritSectEnter(&m_eventQueueCS);
1644 if (RT_SUCCESS(rc2))
1645 {
[79482]1646 XEvent e = m_eventQueueList.at(i).m_Event;
[56651]1647 if ( e.type == ClientMessage
1648 && e.xclient.message_type == aType)
[50724]1649 {
[56651]1650 m_eventQueueList.removeAt(i);
[50724]1651 evMsg = e.xclient;
1652
1653 fFound = true;
1654 }
1655
[56651]1656 if (e.type == ClientMessage)
1657 {
1658 LogFlowThisFunc(("Client message: Type=%ld (%s)\n",
1659 e.xclient.message_type, xAtomToString(e.xclient.message_type).c_str()));
1660 }
1661 else
1662 LogFlowThisFunc(("X message: Type=%d\n", e.type));
1663
[50724]1664 rc2 = RTCritSectLeave(&m_eventQueueCS);
1665 AssertRC(rc2);
1666
1667 if (fFound)
1668 break;
1669 }
1670 }
1671
1672 if (fFound)
1673 break;
1674
[56651]1675 int rc2 = RTSemEventWait(m_eventQueueEvent, 25 /* ms */);
[50724]1676 if ( RT_FAILURE(rc2)
1677 && rc2 != VERR_TIMEOUT)
1678 {
1679 LogFlowFunc(("Waiting failed with rc=%Rrc\n", rc2));
1680 break;
1681 }
1682 }
1683 while (RTTimeMilliTS() - uiStart < uTimeoutMS);
1684
[55820]1685 LogFlowThisFunc(("Returning fFound=%RTbool, msRuntime=%RU64\n", fFound, RTTimeMilliTS() - uiStart));
[50724]1686 return fFound;
1687}
1688#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
1689
[42261]1690/*
1691 * Host -> Guest
1692 */
1693
[55918]1694/**
1695 * Host -> Guest: Event signalling that the host's (mouse) cursor just entered the VM's (guest's) display
1696 * area.
1697 *
1698 * @returns IPRT status code.
1699 * @param lstFormats List of supported formats from the host.
[74439]1700 * @param dndListActionsAllowed (ORed) List of supported actions from the host.
[55918]1701 */
[99595]1702int VBClX11DnDInst::hgEnter(const RTCList<RTCString> &lstFormats, uint32_t dndListActionsAllowed)
[42261]1703{
[55820]1704 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1705
[55918]1706 if (m_enmMode != Unknown)
[55707]1707 return VERR_INVALID_STATE;
1708
[49891]1709 reset();
[42261]1710
[49891]1711#ifdef DEBUG
[74439]1712 LogFlowThisFunc(("dndListActionsAllowed=0x%x, lstFormats=%zu: ", dndListActionsAllowed, lstFormats.size()));
[55918]1713 for (size_t i = 0; i < lstFormats.size(); ++i)
1714 LogFlow(("'%s' ", lstFormats.at(i).c_str()));
[49891]1715 LogFlow(("\n"));
1716#endif
[42261]1717
[55820]1718 int rc;
[42261]1719
[55820]1720 do
1721 {
[74472]1722 /* Check if the VM session has changed and reconnect to the HGCM service if necessary. */
1723 rc = checkForSessionChange();
[85921]1724 AssertRCBreak(rc);
[74472]1725
[85921]1726 /* Append all actual (MIME) formats we support to the list.
1727 * These must come last, after the default Atoms above. */
1728 rc = appendFormatsToList(lstFormats, m_lstAtomFormats);
1729 AssertRCBreak(rc);
[42261]1730
[85921]1731 rc = wndXDnDSetFormatList(m_wndProxy.hWnd, xAtom(XA_XdndTypeList), m_lstAtomFormats);
1732 AssertRCBreak(rc);
[42261]1733
[55820]1734 /* Announce the possible actions. */
1735 VBoxDnDAtomList lstActions;
[74439]1736 rc = toAtomActions(dndListActionsAllowed, lstActions);
[85924]1737 AssertRCBreak(rc);
1738
[56781]1739 rc = wndXDnDSetActionList(m_wndProxy.hWnd, lstActions);
[85924]1740 AssertRCBreak(rc);
[42261]1741
[55820]1742 /* Set the DnD selection owner to our window. */
[56651]1743 /** @todo Don't use CurrentTime -- according to ICCCM section 2.1. */
[56781]1744 XSetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection), m_wndProxy.hWnd, CurrentTime);
[42261]1745
[97734]1746 if (g_cVerbosity)
1747 {
[97768]1748 RTCString strMsg("Enter: Host -> Guest\n");
1749 strMsg += RTCStringFmt("Allowed actions: ");
[97734]1750 for (size_t i = 0; i < lstActions.size(); i++)
1751 {
1752 if (i > 0)
[97768]1753 strMsg += ", ";
1754 strMsg += DnDActionToStr(toHGCMAction(lstActions.at(i)));
[97734]1755 }
[97768]1756 strMsg += " - Formats: ";
1757 for (size_t i = 0; i < lstFormats.size(); i++)
1758 {
1759 if (i > 0)
1760 strMsg += ", ";
1761 strMsg += lstFormats.at(i);
1762 }
[97734]1763
1764 VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER, strMsg.c_str());
1765 }
1766
[55820]1767 m_enmMode = HG;
1768 m_enmState = Dragging;
1769
1770 } while (0);
1771
1772 LogFlowFuncLeaveRC(rc);
1773 return rc;
[42261]1774}
1775
[55918]1776/**
1777 * Host -> Guest: Event signalling that the host's (mouse) cursor has left the VM's (guest's)
1778 * display area.
1779 */
[99595]1780int VBClX11DnDInst::hgLeave(void)
[55846]1781{
[97734]1782 if (g_cVerbosity)
1783 VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER, "Leave: Host -> Guest");
1784
[55918]1785 if (m_enmMode == HG) /* Only reset if in the right operation mode. */
[55846]1786 reset();
1787
1788 return VINF_SUCCESS;
1789}
1790
[55918]1791/**
1792 * Host -> Guest: Event signalling that the host's (mouse) cursor has been moved within the VM's
1793 * (guest's) display area.
1794 *
1795 * @returns IPRT status code.
[74409]1796 * @param uPosX Relative X position within the guest's display area.
1797 * @param uPosY Relative Y position within the guest's display area.
[74439]1798 * @param dndActionDefault Default action the host wants to perform on the guest
[55918]1799 * as soon as the operation successfully finishes.
1800 */
[99595]1801int VBClX11DnDInst::hgMove(uint32_t uPosX, uint32_t uPosY, VBOXDNDACTION dndActionDefault)
[42261]1802{
[55820]1803 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
[74459]1804 LogFlowThisFunc(("uPosX=%RU32, uPosY=%RU32, dndActionDefault=0x%x\n", uPosX, uPosY, dndActionDefault));
[42261]1805
[55820]1806 if ( m_enmMode != HG
1807 || m_enmState != Dragging)
[55459]1808 {
[42261]1809 return VERR_INVALID_STATE;
[55459]1810 }
[42261]1811
1812 int rc = VINF_SUCCESS;
[55707]1813 int xRc = Success;
[42261]1814
1815 /* Move the mouse cursor within the guest. */
[74409]1816 mouseCursorMove(uPosX, uPosY);
[42261]1817
[97734]1818 /* Search for the application window below the cursor. */
1819 Window wndBelowCursor = gX11->applicationWindowBelowCursor(m_wndRoot);
1820 char *pszWndBelowCursorName = wndX11GetNameA(wndBelowCursor);
1821 AssertPtrReturn(pszWndBelowCursorName, VERR_NO_MEMORY);
1822
[97735]1823 uint8_t uBelowCursorXdndVer = 0; /* 0 means the current window is _not_ XdndAware. */
[42261]1824
[97734]1825 if (wndBelowCursor != None)
[42261]1826 {
1827 /* Temp stuff for the XGetWindowProperty call. */
[85920]1828 Atom atmTmp;
[42261]1829 int fmt;
1830 unsigned long cItems, cbRemaining;
1831 unsigned char *pcData = NULL;
[49891]1832
[42261]1833 /* Query the XdndAware property from the window. We are interested in
1834 * the version and if it is XdndAware at all. */
[97734]1835 xRc = XGetWindowProperty(m_pDisplay, wndBelowCursor, xAtom(XA_XdndAware),
[49891]1836 0, 2, False, AnyPropertyType,
[85920]1837 &atmTmp, &fmt, &cItems, &cbRemaining, &pcData);
[56651]1838 if (xRc != Success)
1839 {
[97734]1840 VBClLogError("Error getting properties of cursor window=%#x: %s\n", wndBelowCursor, gX11->xErrorToString(xRc).c_str());
[56651]1841 }
[42261]1842 else
1843 {
[56651]1844 if (pcData == NULL || fmt != 32 || cItems != 1)
1845 {
1846 /** @todo Do we need to deal with this? */
[81040]1847 VBClLogError("Wrong window properties for window %#x: pcData=%#x, iFmt=%d, cItems=%ul\n",
[97734]1848 wndBelowCursor, pcData, fmt, cItems);
[56651]1849 }
[42261]1850 else
1851 {
[56651]1852 /* Get the current window's Xdnd version. */
[97735]1853 uBelowCursorXdndVer = (uint8_t)reinterpret_cast<long *>(pcData)[0];
[42261]1854 }
[50734]1855
[42261]1856 XFree(pcData);
1857 }
1858 }
1859
[97734]1860 char *pszWndCurName = wndX11GetNameA(m_wndCur);
1861 AssertPtrReturn(pszWndCurName, VERR_NO_MEMORY);
[56651]1862
[97735]1863 LogFlowThisFunc(("wndCursor=%x ('%s', Xdnd version %u), wndCur=%x ('%s', Xdnd version %u)\n",
1864 wndBelowCursor, pszWndBelowCursorName, uBelowCursorXdndVer, m_wndCur, pszWndCurName, m_uXdndVer));
[56651]1865
[97734]1866 if ( wndBelowCursor != m_wndCur
[97735]1867 && m_uXdndVer)
[42261]1868 {
[97735]1869 VBClLogInfo("Left old window %#x ('%s'), supported Xdnd version %u\n", m_wndCur, pszWndCurName, m_uXdndVer);
[42261]1870
[55820]1871 /* We left the current XdndAware window. Announce this to the current indow. */
[42261]1872 XClientMessageEvent m;
1873 RT_ZERO(m);
[56651]1874 m.type = ClientMessage;
1875 m.display = m_pDisplay;
1876 m.window = m_wndCur;
1877 m.message_type = xAtom(XA_XdndLeave);
1878 m.format = 32;
[56781]1879 m.data.l[XdndLeaveWindow] = m_wndProxy.hWnd;
[42261]1880
[55707]1881 xRc = XSendEvent(m_pDisplay, m_wndCur, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
[56651]1882 if (xRc == 0)
[97734]1883 VBClLogError("Error sending leave event to old window %#x: %s\n", m_wndCur, gX11->xErrorToString(xRc).c_str());
[56651]1884
1885 /* Reset our current window. */
[97735]1886 m_wndCur = 0;
1887 m_uXdndVer = 0;
[42261]1888 }
1889
[49891]1890 /*
[56651]1891 * Do we have a new Xdnd-aware window which now is under the cursor?
[49891]1892 */
[97734]1893 if ( wndBelowCursor != m_wndCur
[97735]1894 && uBelowCursorXdndVer)
[42261]1895 {
[97735]1896 VBClLogInfo("Entered new window %#x ('%s'), supports Xdnd version=%u\n",
1897 wndBelowCursor, pszWndBelowCursorName, uBelowCursorXdndVer);
[42261]1898
[49891]1899 /*
1900 * We enter a new window. Announce the XdndEnter event to the new
[42261]1901 * window. The first three mime types are attached to the event (the
1902 * others could be requested by the XdndTypeList property from the
[49891]1903 * window itself).
1904 */
[42261]1905 XClientMessageEvent m;
1906 RT_ZERO(m);
1907 m.type = ClientMessage;
1908 m.display = m_pDisplay;
[97734]1909 m.window = wndBelowCursor;
[42261]1910 m.message_type = xAtom(XA_XdndEnter);
1911 m.format = 32;
[56781]1912 m.data.l[XdndEnterWindow] = m_wndProxy.hWnd;
[56651]1913 m.data.l[XdndEnterFlags] = RT_MAKE_U32_FROM_U8(
1914 /* Bit 0 is set if the source supports more than three data types. */
[85921]1915 m_lstAtomFormats.size() > 3 ? RT_BIT(0) : 0,
[56651]1916 /* Reserved for future use. */
1917 0, 0,
1918 /* Protocol version to use. */
[97735]1919 RT_MIN(VBOX_XDND_VERSION, uBelowCursorXdndVer));
[85921]1920 m.data.l[XdndEnterType1] = m_lstAtomFormats.value(0, None); /* First data type to use. */
1921 m.data.l[XdndEnterType2] = m_lstAtomFormats.value(1, None); /* Second data type to use. */
1922 m.data.l[XdndEnterType3] = m_lstAtomFormats.value(2, None); /* Third data type to use. */
[42261]1923
[97734]1924 xRc = XSendEvent(m_pDisplay, wndBelowCursor, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
[56651]1925 if (xRc == 0)
[97734]1926 VBClLogError("Error sending enter event to window %#x: %s\n", wndBelowCursor, gX11->xErrorToString(xRc).c_str());
[42261]1927 }
1928
[97735]1929 if (uBelowCursorXdndVer)
[42261]1930 {
[97734]1931 Assert(wndBelowCursor != None);
[56651]1932
[97734]1933 Atom atmAction = toAtomAction(dndActionDefault);
1934 LogFlowThisFunc(("strAction=%s\n", xAtomToString(atmAction).c_str()));
[42261]1935
[97734]1936 VBClLogInfo("Sent position event (%RU32 x %RU32) to window %#x ('%s') with actions '%s'\n",
1937 uPosX, uPosY, wndBelowCursor, pszWndBelowCursorName, xAtomToString(atmAction).c_str());
1938
[49891]1939 /*
1940 * Send a XdndPosition event with the proposed action to the guest.
1941 */
[42261]1942 XClientMessageEvent m;
1943 RT_ZERO(m);
1944 m.type = ClientMessage;
1945 m.display = m_pDisplay;
[97734]1946 m.window = wndBelowCursor;
[42261]1947 m.message_type = xAtom(XA_XdndPosition);
1948 m.format = 32;
[56781]1949 m.data.l[XdndPositionWindow] = m_wndProxy.hWnd; /* X window ID of source window. */
[85920]1950 m.data.l[XdndPositionFlags] = 0; /* Reserved, set to 0. */
[74409]1951 m.data.l[XdndPositionXY] = RT_MAKE_U32(uPosY, uPosX); /* Cursor coordinates relative to the root window. */
[56651]1952 m.data.l[XdndPositionTimeStamp] = CurrentTime; /* Timestamp for retrieving data. */
[85920]1953 m.data.l[XdndPositionAction] = atmAction; /* Actions requested by the user. */
[42261]1954
[97734]1955 xRc = XSendEvent(m_pDisplay, wndBelowCursor, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
[56651]1956 if (xRc == 0)
[97734]1957 VBClLogError("Error sending position event to current window %#x: %s\n", wndBelowCursor, gX11->xErrorToString(xRc).c_str());
[42261]1958 }
[49891]1959
[97735]1960 if (uBelowCursorXdndVer == 0)
[49891]1961 {
[42261]1962 /* No window to process, so send a ignore ack event to the host. */
[74411]1963 rc = VbglR3DnDHGSendAckOp(&m_dndCtx, VBOX_DND_ACTION_IGNORE);
[49891]1964 }
[55820]1965 else
1966 {
[97734]1967 Assert(wndBelowCursor != None);
[56651]1968
[97735]1969 m_wndCur = wndBelowCursor;
1970 m_uXdndVer = uBelowCursorXdndVer;
[55820]1971 }
[42261]1972
[97734]1973 RTStrFree(pszWndBelowCursorName);
1974 RTStrFree(pszWndCurName);
1975
[49891]1976 LogFlowFuncLeaveRC(rc);
[42261]1977 return rc;
1978}
1979
[55918]1980/**
1981 * Host -> Guest: Event signalling that the host has dropped the data over the VM (guest) window.
1982 *
1983 * @returns IPRT status code.
[74409]1984 * @param uPosX Relative X position within the guest's display area.
1985 * @param uPosY Relative Y position within the guest's display area.
[74439]1986 * @param dndActionDefault Default action the host wants to perform on the guest
[56651]1987 * as soon as the operation successfully finishes.
[55918]1988 */
[99595]1989int VBClX11DnDInst::hgDrop(uint32_t uPosX, uint32_t uPosY, VBOXDNDACTION dndActionDefault)
[42261]1990{
[74439]1991 RT_NOREF3(uPosX, uPosY, dndActionDefault);
[74409]1992 LogFlowThisFunc(("wndCur=%RU32, wndProxy=%RU32, mode=%RU32, state=%RU32\n", m_wndCur, m_wndProxy.hWnd, m_enmMode, m_enmState));
[74459]1993 LogFlowThisFunc(("uPosX=%RU32, uPosY=%RU32, dndActionDefault=0x%x\n", uPosX, uPosY, dndActionDefault));
[62883]1994
[55820]1995 if ( m_enmMode != HG
1996 || m_enmState != Dragging)
[55707]1997 {
[42261]1998 return VERR_INVALID_STATE;
[55707]1999 }
[42261]2000
[56651]2001 /* Set the state accordingly. */
2002 m_enmState = Dropped;
[42261]2003
[55918]2004 /*
[56651]2005 * Ask the host to send the raw data, as we don't (yet) know which format
2006 * the guest exactly expects. As blocking in a SelectionRequest message turned
2007 * out to be very unreliable (e.g. with KDE apps) we request to start transferring
2008 * file/directory data (if any) here.
[55820]2009 */
[56651]2010 char szFormat[] = { "text/uri-list" };
[42261]2011
[58212]2012 int rc = VbglR3DnDHGSendReqData(&m_dndCtx, szFormat);
[81040]2013 VBClLogInfo("Drop event from host resulted in: %Rrc\n", rc);
[42261]2014
[97734]2015 if (g_cVerbosity)
2016 VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER, "Drop: Host -> Guest");
2017
[49891]2018 LogFlowFuncLeaveRC(rc);
[42261]2019 return rc;
2020}
2021
[55918]2022/**
[56651]2023 * Host -> Guest: Event signalling that the host has finished sending drag'n drop
2024 * data to the guest for further processing.
[55918]2025 *
2026 * @returns IPRT status code.
[85371]2027 * @param pMeta Pointer to meta data from host.
[55918]2028 */
[99595]2029int VBClX11DnDInst::hgDataReceive(PVBGLR3GUESTDNDMETADATA pMeta)
[42261]2030{
[74380]2031 LogFlowThisFunc(("enmMode=%RU32, enmState=%RU32\n", m_enmMode, m_enmState));
[85371]2032 LogFlowThisFunc(("enmMetaType=%RU32\n", pMeta->enmType));
[55820]2033
2034 if ( m_enmMode != HG
2035 || m_enmState != Dropped)
[55707]2036 {
[42261]2037 return VERR_INVALID_STATE;
[55707]2038 }
[42261]2039
[85371]2040 void *pvData = NULL;
2041 size_t cbData = 0;
2042
[85498]2043 int rc = VINF_SUCCESS; /* Shut up GCC. */
[85371]2044
2045 switch (pMeta->enmType)
[55707]2046 {
[85371]2047 case VBGLR3GUESTDNDMETADATATYPE_RAW:
2048 {
2049 AssertBreakStmt(pMeta->u.Raw.pvMeta != NULL, rc = VERR_INVALID_POINTER);
2050 pvData = pMeta->u.Raw.pvMeta;
2051 AssertBreakStmt(pMeta->u.Raw.cbMeta, rc = VERR_INVALID_PARAMETER);
2052 cbData = pMeta->u.Raw.cbMeta;
2053
2054 rc = VINF_SUCCESS;
2055 break;
2056 }
2057
2058 case VBGLR3GUESTDNDMETADATATYPE_URI_LIST:
2059 {
[85473]2060 const char *pcszRootPath = DnDTransferListGetRootPathAbs(&pMeta->u.URI.Transfer);
2061 AssertPtrBreakStmt(pcszRootPath, VERR_INVALID_POINTER);
[85371]2062
[85473]2063 VBClLogInfo("Transfer list root directory is '%s'\n", pcszRootPath);
2064
2065 /* Note: Use the URI format here, as X' DnD spec says so. */
2066 rc = DnDTransferListGetRootsEx(&pMeta->u.URI.Transfer, DNDTRANSFERLISTFMT_URI, pcszRootPath,
[85746]2067 DND_PATH_SEPARATOR_STR, (char **)&pvData, &cbData);
[85371]2068 break;
2069 }
2070
2071 default:
2072 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
2073 break;
[55707]2074 }
[42261]2075
[85371]2076 if (RT_FAILURE(rc))
2077 return rc;
[42261]2078
[49891]2079 /*
[56651]2080 * At this point all data needed (including sent files/directories) should
2081 * be on the guest, so proceed working on communicating with the target window.
[49891]2082 */
[85371]2083 VBClLogInfo("Received %RU32 bytes of meta data from host\n", cbData);
[42261]2084
[56651]2085 /* Destroy any old data. */
2086 if (m_pvSelReqData)
2087 {
2088 Assert(m_cbSelReqData);
[42261]2089
[56651]2090 RTMemFree(m_pvSelReqData); /** @todo RTMemRealloc? */
2091 m_cbSelReqData = 0;
2092 }
[42261]2093
[56651]2094 /** @todo Handle incremental transfers. */
[55820]2095
[56651]2096 /* Make a copy of the data. This data later then will be used to fill into
2097 * the selection request. */
2098 if (cbData)
2099 {
2100 m_pvSelReqData = RTMemAlloc(cbData);
2101 if (!m_pvSelReqData)
2102 return VERR_NO_MEMORY;
2103
2104 memcpy(m_pvSelReqData, pvData, cbData);
2105 m_cbSelReqData = cbData;
2106 }
2107
2108 /*
2109 * Send a drop event to the current window (target).
2110 * This window in turn then will raise a SelectionRequest message to our proxy window,
2111 * which we will handle in our onX11SelectionRequest handler.
2112 *
2113 * The SelectionRequest will tell us in which format the target wants the data from the host.
2114 */
2115 XClientMessageEvent m;
2116 RT_ZERO(m);
2117 m.type = ClientMessage;
2118 m.display = m_pDisplay;
2119 m.window = m_wndCur;
2120 m.message_type = xAtom(XA_XdndDrop);
2121 m.format = 32;
[56781]2122 m.data.l[XdndDropWindow] = m_wndProxy.hWnd; /* Source window. */
2123 m.data.l[XdndDropFlags] = 0; /* Reserved for future use. */
2124 m.data.l[XdndDropTimeStamp] = CurrentTime; /* Our DnD data does not rely on any timing, so just use the current time. */
[56651]2125
2126 int xRc = XSendEvent(m_pDisplay, m_wndCur, False /* Propagate */, NoEventMask, reinterpret_cast<XEvent*>(&m));
2127 if (xRc == 0)
[81040]2128 VBClLogError("Error sending XA_XdndDrop event to window=%#x: %s\n", m_wndCur, gX11->xErrorToString(xRc).c_str());
[56651]2129 XFlush(m_pDisplay);
2130
2131 LogFlowFuncLeaveRC(rc);
2132 return rc;
[42261]2133}
2134
[74472]2135/**
2136 * Checks if the VM session has changed (can happen when restoring the VM from a saved state)
2137 * and do a reconnect to the DnD HGCM service.
2138 *
2139 * @returns IPRT status code.
2140 */
[99595]2141int VBClX11DnDInst::checkForSessionChange(void)
[74472]2142{
2143 uint64_t uSessionID;
2144 int rc = VbglR3GetSessionId(&uSessionID);
2145 if ( RT_SUCCESS(rc)
2146 && uSessionID != m_dndCtx.uSessionID)
2147 {
2148 LogFlowThisFunc(("VM session has changed to %RU64\n", uSessionID));
2149
2150 rc = VbglR3DnDDisconnect(&m_dndCtx);
2151 AssertRC(rc);
2152
2153 rc = VbglR3DnDConnect(&m_dndCtx);
2154 AssertRC(rc);
2155 }
2156
2157 LogFlowFuncLeaveRC(rc);
2158 return rc;
2159}
2160
[42261]2161#ifdef VBOX_WITH_DRAG_AND_DROP_GH
[55918]2162/**
2163 * Guest -> Host: Event signalling that the host is asking whether there is a pending
2164 * drag event on the guest (to the host).
2165 *
2166 * @returns IPRT status code.
2167 */
[99595]2168int VBClX11DnDInst::ghIsDnDPending(void)
[42261]2169{
[55820]2170 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
[55707]2171
[56781]2172 int rc;
2173
[97827]2174 RTCString strFormats = DND_PATH_SEPARATOR_STR; /** @todo If empty, IOCTL fails with VERR_ACCESS_DENIED. */
[74439]2175 VBOXDNDACTION dndActionDefault = VBOX_DND_ACTION_IGNORE;
2176 VBOXDNDACTIONLIST dndActionList = VBOX_DND_ACTION_IGNORE;
[56781]2177
[56651]2178 /* Currently in wrong mode? Bail out. */
[55820]2179 if (m_enmMode == HG)
[74409]2180 {
[56781]2181 rc = VERR_INVALID_STATE;
[74409]2182 }
[56651]2183 /* Message already processed successfully? */
[56781]2184 else if ( m_enmMode == GH
2185 && ( m_enmState == Dragging
2186 || m_enmState == Dropped)
2187 )
[56651]2188 {
[57283]2189 /* No need to query for the source window again. */
2190 rc = VINF_SUCCESS;
[56651]2191 }
[56781]2192 else
2193 {
[74472]2194 /* Check if the VM session has changed and reconnect to the HGCM service if necessary. */
2195 rc = checkForSessionChange();
[60662]2196
[56781]2197 /* Determine the current window which currently has the XdndSelection set. */
[97734]2198 Window wndSel = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
2199 LogFlowThisFunc(("wndSel=%#x, wndProxy=%#x, wndCur=%#x\n", wndSel, m_wndProxy.hWnd, m_wndCur));
[56651]2200
[56781]2201 /* Is this another window which has a Xdnd selection and not our proxy window? */
[74472]2202 if ( RT_SUCCESS(rc)
[97734]2203 && wndSel
2204 && wndSel != m_wndCur)
[56781]2205 {
[97734]2206 char *pszWndSelName = wndX11GetNameA(wndSel);
2207 AssertPtrReturn(pszWndSelName, VERR_NO_MEMORY);
2208 VBClLogInfo("New guest source window %#x ('%s')\n", wndSel, pszWndSelName);
[56651]2209
[56781]2210 /* Start over. */
2211 reset();
[49891]2212
[56781]2213 /* Map the window on the current cursor position, which should provoke
2214 * an XdndEnter event. */
[57283]2215 rc = proxyWinShow();
[56781]2216 if (RT_SUCCESS(rc))
2217 {
2218 rc = mouseCursorFakeMove();
2219 if (RT_SUCCESS(rc))
2220 {
[57283]2221 bool fWaitFailed = false; /* Waiting for status changed failed? */
2222
[56781]2223 /* Wait until we're in "Dragging" state. */
[57283]2224 rc = waitForStatusChange(Dragging, 100 /* 100ms timeout */);
2225
2226 /*
2227 * Note: Don't wait too long here, as this mostly will make
2228 * the drag and drop experience on the host being laggy
2229 * and unresponsive.
2230 *
2231 * Instead, let the host query multiple times with 100ms
2232 * timeout each (see above) and only report an error if
2233 * the overall querying time has been exceeded.<
2234 */
2235 if (RT_SUCCESS(rc))
2236 {
2237 m_enmMode = GH;
2238 }
2239 else if (rc == VERR_TIMEOUT)
2240 {
2241 /** @todo Make m_cFailedPendingAttempts configurable. For slower window managers? */
2242 if (m_cFailedPendingAttempts++ > 50) /* Tolerate up to 5s total (100ms for each slot). */
2243 fWaitFailed = true;
2244 else
2245 rc = VINF_SUCCESS;
2246 }
2247 else if (RT_FAILURE(rc))
2248 fWaitFailed = true;
2249
2250 if (fWaitFailed)
2251 {
[81040]2252 VBClLogError("Error mapping proxy window to guest source window %#x ('%s'), rc=%Rrc\n",
[97734]2253 wndSel, pszWndSelName, rc);
[57283]2254
2255 /* Reset the counter in any case. */
2256 m_cFailedPendingAttempts = 0;
2257 }
[56781]2258 }
2259 }
[56651]2260
[97734]2261 RTStrFree(pszWndSelName);
[56651]2262 }
[74409]2263 else
[81040]2264 VBClLogInfo("No guest source window\n");
[56651]2265 }
[55820]2266
[56651]2267 /*
2268 * Acknowledge to the host in any case, regardless
2269 * if something failed here or not. Be responsive.
2270 */
[50724]2271
[56651]2272 int rc2 = RTCritSectEnter(&m_dataCS);
2273 if (RT_SUCCESS(rc2))
2274 {
[97826]2275 /* Filter out the default X11-specific formats (required for Xdnd, 'TARGET' / 'MULTIPLE');
2276 * those will not be supported by VirtualBox. */
2277 VBoxDnDAtomList const lstAtomFormatsFiltered = gX11->xAtomListFiltered(m_lstAtomFormats, m_lstAtomFormatsX11);
2278
2279 /* Anything left to report to the host? */
2280 if (lstAtomFormatsFiltered.size())
[56781]2281 {
[97826]2282 strFormats = gX11->xAtomListToString(lstAtomFormatsFiltered);
[74439]2283 dndActionDefault = VBOX_DND_ACTION_COPY; /** @todo Handle default action! */
2284 dndActionList = VBOX_DND_ACTION_COPY; /** @todo Ditto. */
[85921]2285 dndActionList |= toHGCMActions(m_lstAtomActions);
[56781]2286 }
[50724]2287
[56651]2288 RTCritSectLeave(&m_dataCS);
2289 }
[50724]2290
[97826]2291 if (g_cVerbosity)
2292 {
2293 char *pszActions = DnDActionListToStrA(dndActionList);
2294 AssertPtrReturn(pszActions, VERR_NO_MEMORY);
2295 VBClLogVerbose(1, "Reporting formats '%s' (actions '%s' / %#x, default action is '%s' (%#x)\n",
2296 strFormats.c_str(), pszActions, dndActionList, DnDActionToStr(dndActionDefault), dndActionDefault);
2297 RTStrFree(pszActions);
2298 }
2299
[74439]2300 rc2 = VbglR3DnDGHSendAckPending(&m_dndCtx, dndActionDefault, dndActionList,
[58212]2301 strFormats.c_str(), strFormats.length() + 1 /* Include termination */);
[74459]2302 LogFlowThisFunc(("uClientID=%RU32, dndActionDefault=0x%x, dndActionList=0x%x, strFormats=%s, rc=%Rrc\n",
[74439]2303 m_dndCtx.uClientID, dndActionDefault, dndActionList, strFormats.c_str(), rc2));
[56671]2304 if (RT_FAILURE(rc2))
2305 {
[97734]2306 switch (rc2)
2307 {
2308 case VERR_ACCESS_DENIED:
2309 {
2310 rc = VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER,
2311 "Drag and drop to the host either is not supported or disabled. "
2312 "Please enable Guest to Host or Bidirectional drag and drop mode "
2313 "or re-install the VirtualBox Guest Additions.");
2314 AssertRC(rc);
2315 break;
2316 }
2317
2318 default:
2319 break;
2320 }
2321
[81040]2322 VBClLogError("Error reporting pending drag and drop operation status to host: %Rrc\n", rc2);
[56671]2323 if (RT_SUCCESS(rc))
2324 rc = rc2;
2325 }
[42261]2326
[49891]2327 LogFlowFuncLeaveRC(rc);
[42261]2328 return rc;
2329}
2330
[55918]2331/**
2332 * Guest -> Host: Event signalling that the host has dropped the item(s) on the
2333 * host side.
2334 *
2335 * @returns IPRT status code.
2336 * @param strFormat Requested format to send to the host.
[74459]2337 * @param dndActionRequested Requested action to perform on the guest.
[55918]2338 */
[99595]2339int VBClX11DnDInst::ghDropped(const RTCString &strFormat, VBOXDNDACTION dndActionRequested)
[42261]2340{
[74459]2341 LogFlowThisFunc(("mode=%RU32, state=%RU32, strFormat=%s, dndActionRequested=0x%x\n",
2342 m_enmMode, m_enmState, strFormat.c_str(), dndActionRequested));
[50593]2343
[56651]2344 /* Currently in wrong mode? Bail out. */
2345 if ( m_enmMode == Unknown
2346 || m_enmMode == HG)
[55707]2347 {
2348 return VERR_INVALID_STATE;
2349 }
2350
[56651]2351 if ( m_enmMode == GH
2352 && m_enmState != Dragging)
2353 {
2354 return VERR_INVALID_STATE;
2355 }
2356
[42261]2357 int rc = VINF_SUCCESS;
2358
[55820]2359 m_enmState = Dropped;
[50724]2360
2361#ifdef DEBUG
2362 XWindowAttributes xwa;
2363 XGetWindowAttributes(m_pDisplay, m_wndCur, &xwa);
[74409]2364 LogFlowThisFunc(("wndProxy=%RU32, wndCur=%RU32, x=%d, y=%d, width=%d, height=%d\n",
[56781]2365 m_wndProxy.hWnd, m_wndCur, xwa.x, xwa.y, xwa.width, xwa.height));
[57283]2366
2367 Window wndSelection = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
2368 LogFlowThisFunc(("wndSelection=%#x\n", wndSelection));
[50724]2369#endif
2370
[57283]2371 /* We send a fake mouse move event to the current window, cause
[42261]2372 * this should have the grab. */
[57283]2373 mouseCursorFakeMove();
[50593]2374
[55918]2375 /**
[55707]2376 * The fake button release event above should lead to a XdndDrop event from the
[56651]2377 * source window. Because of showing our proxy window, other Xdnd events can
[50724]2378 * occur before, e.g. a XdndPosition event. We are not interested
[55918]2379 * in those, so just try to get the right one.
2380 */
[50593]2381
[50724]2382 XClientMessageEvent evDnDDrop;
[56651]2383 bool fDrop = waitForX11ClientMsg(evDnDDrop, xAtom(XA_XdndDrop), 5 * 1000 /* 5s timeout */);
[50724]2384 if (fDrop)
[42261]2385 {
[55820]2386 LogFlowThisFunc(("XA_XdndDrop\n"));
2387
[50724]2388 /* Request to convert the selection in the specific format and
2389 * place it to our proxy window as property. */
[56651]2390 Assert(evDnDDrop.message_type == xAtom(XA_XdndDrop));
2391
2392 Window wndSource = evDnDDrop.data.l[XdndDropWindow]; /* Source window which has sent the message. */
[50734]2393 Assert(wndSource == m_wndCur);
[50724]2394
[56651]2395 Atom aFormat = gX11->stringToxAtom(strFormat.c_str());
2396
2397 Time tsDrop;
[97735]2398 if (m_uXdndVer >= 1)
[56651]2399 tsDrop = evDnDDrop.data.l[XdndDropTimeStamp];
2400 else
2401 tsDrop = CurrentTime;
2402
[55707]2403 XConvertSelection(m_pDisplay, xAtom(XA_XdndSelection), aFormat, xAtom(XA_XdndSelection),
[56781]2404 m_wndProxy.hWnd, tsDrop);
[50724]2405
2406 /* Wait for the selection notify event. */
2407 XEvent evSelNotify;
2408 RT_ZERO(evSelNotify);
[56651]2409 if (waitForX11Msg(evSelNotify, SelectionNotify, 5 * 1000 /* 5s timeout */))
[42261]2410 {
[50734]2411 bool fCancel = false;
2412
[50724]2413 /* Make some paranoid checks. */
2414 if ( evSelNotify.xselection.type == SelectionNotify
2415 && evSelNotify.xselection.display == m_pDisplay
2416 && evSelNotify.xselection.selection == xAtom(XA_XdndSelection)
[56781]2417 && evSelNotify.xselection.requestor == m_wndProxy.hWnd
[50724]2418 && evSelNotify.xselection.target == aFormat)
[42261]2419 {
[50724]2420 LogFlowThisFunc(("Selection notfiy (from wnd=%#x)\n", m_wndCur));
[50593]2421
[50724]2422 Atom aPropType;
2423 int iPropFormat;
2424 unsigned long cItems, cbRemaining;
2425 unsigned char *pcData = NULL;
[56781]2426 int xRc = XGetWindowProperty(m_pDisplay, m_wndProxy.hWnd,
[55707]2427 xAtom(XA_XdndSelection) /* Property */,
2428 0 /* Offset */,
2429 VBOX_MAX_XPROPERTIES /* Length of 32-bit multiples */,
2430 True /* Delete property? */,
2431 AnyPropertyType, /* Property type */
2432 &aPropType, &iPropFormat, &cItems, &cbRemaining, &pcData);
[56651]2433 if (xRc != Success)
[81040]2434 VBClLogError("Error getting XA_XdndSelection property of proxy window=%#x: %s\n",
2435 m_wndProxy.hWnd, gX11->xErrorToString(xRc).c_str());
[50593]2436
[51529]2437 LogFlowThisFunc(("strType=%s, iPropFormat=%d, cItems=%RU32, cbRemaining=%RU32\n",
[50724]2438 gX11->xAtomToString(aPropType).c_str(), iPropFormat, cItems, cbRemaining));
[50593]2439
[50724]2440 if ( aPropType != None
2441 && pcData != NULL
2442 && iPropFormat >= 8
2443 && cItems > 0
2444 && cbRemaining == 0)
[42261]2445 {
[50724]2446 size_t cbData = cItems * (iPropFormat / 8);
2447 LogFlowThisFunc(("cbData=%zu\n", cbData));
[50593]2448
[50724]2449 /* For whatever reason some of the string MIME types are not
2450 * zero terminated. Check that and correct it when necessary,
2451 * because the guest side wants this in any case. */
[51556]2452 if ( m_lstAllowedFormats.contains(strFormat)
[50724]2453 && pcData[cbData - 1] != '\0')
[42261]2454 {
[50724]2455 unsigned char *pvDataTmp = static_cast<unsigned char*>(RTMemAlloc(cbData + 1));
2456 if (pvDataTmp)
[42261]2457 {
[50724]2458 memcpy(pvDataTmp, pcData, cbData);
2459 pvDataTmp[cbData++] = '\0';
[51529]2460
[55422]2461 rc = VbglR3DnDGHSendData(&m_dndCtx, strFormat.c_str(), pvDataTmp, cbData);
[50724]2462 RTMemFree(pvDataTmp);
[42261]2463 }
2464 else
[50724]2465 rc = VERR_NO_MEMORY;
2466 }
2467 else
2468 {
2469 /* Send the raw data to the host. */
[55422]2470 rc = VbglR3DnDGHSendData(&m_dndCtx, strFormat.c_str(), pcData, cbData);
[56781]2471 LogFlowThisFunc(("Sent strFormat=%s, rc=%Rrc\n", strFormat.c_str(), rc));
[50724]2472 }
[42261]2473
[50734]2474 if (RT_SUCCESS(rc))
2475 {
[74459]2476 rc = m_wndProxy.sendFinished(wndSource, dndActionRequested);
[50734]2477 }
2478 else
2479 fCancel = true;
[50724]2480 }
2481 else
2482 {
2483 if (aPropType == xAtom(XA_INCR))
2484 {
2485 /** @todo Support incremental transfers. */
[56651]2486 AssertMsgFailed(("Incremental transfers are not supported yet\n"));
2487
[81040]2488 VBClLogError("Incremental transfers are not supported yet\n");
[50724]2489 rc = VERR_NOT_IMPLEMENTED;
[42261]2490 }
2491 else
2492 {
[81040]2493 VBClLogError("Not supported data type: %s\n", gX11->xAtomToString(aPropType).c_str());
[55707]2494 rc = VERR_NOT_SUPPORTED;
[50724]2495 }
[50593]2496
[50734]2497 fCancel = true;
2498 }
2499
[51529]2500 if (fCancel)
[50734]2501 {
[81040]2502 VBClLogInfo("Cancelling dropping to host\n");
[50734]2503
[56651]2504 /* Cancel the operation -- inform the source window by
2505 * sending a XdndFinished message so that the source can toss the required data. */
[74411]2506 rc = m_wndProxy.sendFinished(wndSource, VBOX_DND_ACTION_IGNORE);
[50724]2507 }
[50593]2508
[50724]2509 /* Cleanup. */
2510 if (pcData)
2511 XFree(pcData);
[42261]2512 }
2513 else
[50724]2514 rc = VERR_INVALID_PARAMETER;
[42261]2515 }
2516 else
[50724]2517 rc = VERR_TIMEOUT;
[42261]2518 }
2519 else
2520 rc = VERR_TIMEOUT;
2521
[50593]2522 /* Inform the host on error. */
[42261]2523 if (RT_FAILURE(rc))
[50724]2524 {
[97748]2525 int rc2 = VbglR3DnDSendError(&m_dndCtx, rc);
[81042]2526 LogFlowThisFunc(("Sending error %Rrc to host resulted in %Rrc\n", rc, rc2)); RT_NOREF(rc2);
[56651]2527 /* This is not fatal for us, just ignore. */
[50724]2528 }
[42261]2529
2530 /* At this point, we have either successfully transfered any data or not.
[56651]2531 * So reset our internal state because we are done here for the current (ongoing)
2532 * drag and drop operation. */
[42261]2533 reset();
2534
[49891]2535 LogFlowFuncLeaveRC(rc);
[42261]2536 return rc;
2537}
2538#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
2539
2540/*
2541 * Helpers
2542 */
2543
[55918]2544/**
[56781]2545 * Fakes moving the mouse cursor to provoke various drag and drop
2546 * events such as entering a target window or moving within a
2547 * source window.
2548 *
2549 * Not the most elegant and probably correct function, but does
2550 * the work for now.
2551 *
2552 * @returns IPRT status code.
2553 */
[99595]2554int VBClX11DnDInst::mouseCursorFakeMove(void)
[56781]2555{
2556 int iScreenID = XDefaultScreen(m_pDisplay);
2557 /** @todo What about multiple screens? Test this! */
2558
2559 const int iScrX = XDisplayWidth(m_pDisplay, iScreenID);
2560 const int iScrY = XDisplayHeight(m_pDisplay, iScreenID);
2561
2562 int fx, fy, rx, ry;
2563 Window wndTemp, wndChild;
2564 int wx, wy; unsigned int mask;
2565 XQueryPointer(m_pDisplay, m_wndRoot, &wndTemp, &wndChild, &rx, &ry, &wx, &wy, &mask);
2566
2567 /*
2568 * Apply some simple clipping and change the position slightly.
2569 */
2570
2571 /* FakeX */
2572 if (rx == 0) fx = 1;
2573 else if (rx == iScrX) fx = iScrX - 1;
2574 else fx = rx + 1;
2575
2576 /* FakeY */
2577 if (ry == 0) fy = 1;
2578 else if (ry == iScrY) fy = iScrY - 1;
2579 else fy = ry + 1;
2580
2581 /*
2582 * Move the cursor to trigger the wanted events.
2583 */
2584 LogFlowThisFunc(("cursorRootX=%d, cursorRootY=%d\n", fx, fy));
2585 int rc = mouseCursorMove(fx, fy);
2586 if (RT_SUCCESS(rc))
2587 {
2588 /* Move the cursor back to its original position. */
2589 rc = mouseCursorMove(rx, ry);
2590 }
2591
2592 return rc;
2593}
2594
2595/**
[55918]2596 * Moves the mouse pointer to a specific position.
2597 *
2598 * @returns IPRT status code.
2599 * @param iPosX Absolute X coordinate.
2600 * @param iPosY Absolute Y coordinate.
2601 */
[99595]2602int VBClX11DnDInst::mouseCursorMove(int iPosX, int iPosY)
[42261]2603{
[97739]2604 int const iScreenID = XDefaultScreen(m_pDisplay);
[55846]2605 /** @todo What about multiple screens? Test this! */
2606
[97739]2607 int const iScreenWidth = XDisplayWidth (m_pDisplay, iScreenID);
2608 int const iScreenHeight = XDisplayHeight(m_pDisplay, iScreenID);
[55846]2609
[97739]2610 iPosX = RT_CLAMP(iPosX, 0, iScreenWidth);
2611 iPosY = RT_CLAMP(iPosY, 0, iScreenHeight);
[55846]2612
[97739]2613 /* Same mouse position as before? No need to do anything. */
2614 if ( m_lastMouseX == iPosX
2615 && m_lastMouseY == iPosY)
2616 {
2617 return VINF_SUCCESS;
2618 }
[50724]2619
[97739]2620 LogFlowThisFunc(("iPosX=%d, iPosY=%d, m_wndRoot=%#x\n", iPosX, iPosY, m_wndRoot));
2621
[42261]2622 /* Move the guest pointer to the DnD position, so we can find the window
2623 * below that position. */
[97739]2624 int xRc = XWarpPointer(m_pDisplay, None, m_wndRoot, 0, 0, 0, 0, iPosX, iPosY);
2625 if (xRc == Success)
2626 {
2627 XFlush(m_pDisplay);
2628
2629 m_lastMouseX = iPosX;
2630 m_lastMouseY = iPosY;
2631 }
2632 else
2633 VBClLogError("Moving mouse cursor failed: %s", gX11->xErrorToString(xRc).c_str());
2634
[42261]2635 return VINF_SUCCESS;
2636}
2637
[55918]2638/**
2639 * Sends a mouse button event to a specific window.
2640 *
2641 * @param wndDest Window to send the mouse button event to.
2642 * @param rx X coordinate relative to the root window's origin.
2643 * @param ry Y coordinate relative to the root window's origin.
2644 * @param iButton Mouse button to press/release.
2645 * @param fPress Whether to press or release the mouse button.
2646 */
[99595]2647void VBClX11DnDInst::mouseButtonSet(Window wndDest, int rx, int ry, int iButton, bool fPress)
[42261]2648{
[50724]2649 LogFlowThisFunc(("wndDest=%#x, rx=%d, ry=%d, iBtn=%d, fPress=%RTbool\n",
2650 wndDest, rx, ry, iButton, fPress));
2651
2652#ifdef VBOX_DND_WITH_XTEST
2653 /** @todo Make this check run only once. */
2654 int ev, er, ma, mi;
2655 if (XTestQueryExtension(m_pDisplay, &ev, &er, &ma, &mi))
2656 {
2657 LogFlowThisFunc(("XText extension available\n"));
2658
[55707]2659 int xRc = XTestFakeButtonEvent(m_pDisplay, 1, fPress ? True : False, CurrentTime);
[56651]2660 if (Rc == 0)
[81040]2661 VBClLogError("Error sending XTestFakeButtonEvent event: %s\n", gX11->xErrorToString(xRc).c_str());
[50724]2662 XFlush(m_pDisplay);
[42261]2663 }
[50724]2664 else
2665 {
2666#endif
[56651]2667 LogFlowThisFunc(("Note: XText extension not available or disabled\n"));
[50724]2668
[58945]2669 unsigned int mask = 0;
[57283]2670
[56651]2671 if ( rx == -1
2672 && ry == -1)
2673 {
[57283]2674 Window wndRoot, wndChild;
2675 int wx, wy;
2676 XQueryPointer(m_pDisplay, m_wndRoot, &wndRoot, &wndChild, &rx, &ry, &wx, &wy, &mask);
2677 LogFlowThisFunc(("Mouse pointer is at root x=%d, y=%d\n", rx, ry));
[56651]2678 }
2679
[50724]2680 XButtonEvent eBtn;
2681 RT_ZERO(eBtn);
2682
2683 eBtn.display = m_pDisplay;
2684 eBtn.root = m_wndRoot;
2685 eBtn.window = wndDest;
2686 eBtn.subwindow = None;
2687 eBtn.same_screen = True;
2688 eBtn.time = CurrentTime;
2689 eBtn.button = iButton;
[57283]2690 eBtn.state = mask | (iButton == 1 ? Button1MotionMask :
2691 iButton == 2 ? Button2MotionMask :
2692 iButton == 3 ? Button3MotionMask :
2693 iButton == 4 ? Button4MotionMask :
2694 iButton == 5 ? Button5MotionMask : 0);
[50724]2695 eBtn.type = fPress ? ButtonPress : ButtonRelease;
2696 eBtn.send_event = False;
2697 eBtn.x_root = rx;
2698 eBtn.y_root = ry;
2699
[56651]2700 XTranslateCoordinates(m_pDisplay, eBtn.root, eBtn.window, eBtn.x_root, eBtn.y_root, &eBtn.x, &eBtn.y, &eBtn.subwindow);
[57283]2701 LogFlowThisFunc(("state=0x%x, x=%d, y=%d\n", eBtn.state, eBtn.x, eBtn.y));
2702
[56651]2703 int xRc = XSendEvent(m_pDisplay, wndDest, True /* fPropagate */,
[57283]2704 ButtonPressMask,
[50724]2705 reinterpret_cast<XEvent*>(&eBtn));
[56651]2706 if (xRc == 0)
[81040]2707 VBClLogError("Error sending XButtonEvent event to window=%#x: %s\n", wndDest, gX11->xErrorToString(xRc).c_str());
[50724]2708
[57283]2709 XFlush(m_pDisplay);
2710
[50724]2711#ifdef VBOX_DND_WITH_XTEST
2712 }
2713#endif
[42261]2714}
2715
[55918]2716/**
2717 * Shows the (invisible) proxy window. The proxy window is needed for intercepting
2718 * drags from the host to the guest or from the guest to the host. It acts as a proxy
2719 * between the host and the actual (UI) element on the guest OS.
2720 *
2721 * To not make it miss any actions this window gets spawned across the entire guest
2722 * screen (think of an umbrella) to (hopefully) capture everything. A proxy window
2723 * which follows the cursor would be far too slow here.
2724 *
2725 * @returns IPRT status code.
2726 * @param piRootX X coordinate relative to the root window's origin. Optional.
2727 * @param piRootY Y coordinate relative to the root window's origin. Optional.
2728 */
[99595]2729int VBClX11DnDInst::proxyWinShow(int *piRootX /* = NULL */, int *piRootY /* = NULL */) const
[42261]2730{
[50724]2731 /* piRootX is optional. */
2732 /* piRootY is optional. */
2733
2734 LogFlowThisFuncEnter();
2735
[55846]2736 int rc = VINF_SUCCESS;
2737
[55918]2738#if 0
[56651]2739# ifdef VBOX_DND_WITH_XTEST
[55820]2740 XTestGrabControl(m_pDisplay, False);
[56651]2741# endif
[55820]2742#endif
2743
2744 /* Get the mouse pointer position and determine if we're on the same screen as the root window
[55846]2745 * and return the current child window beneath our mouse pointer, if any. */
[50724]2746 int iRootX, iRootY;
2747 int iChildX, iChildY;
2748 unsigned int iMask;
2749 Window wndRoot, wndChild;
[51529]2750 Bool fInRootWnd = XQueryPointer(m_pDisplay, m_wndRoot, &wndRoot, &wndChild,
[56651]2751 &iRootX, &iRootY, &iChildX, &iChildY, &iMask);
[55707]2752
[74409]2753 LogFlowThisFunc(("fInRootWnd=%RTbool, wndRoot=%RU32, wndChild=%RU32, iRootX=%d, iRootY=%d\n",
[81042]2754 RT_BOOL(fInRootWnd), wndRoot, wndChild, iRootX, iRootY)); RT_NOREF(fInRootWnd);
[50724]2755
2756 if (piRootX)
2757 *piRootX = iRootX;
2758 if (piRootY)
2759 *piRootY = iRootY;
2760
2761 XSynchronize(m_pDisplay, True /* Enable sync */);
2762
[55707]2763 /* Bring our proxy window into foreground. */
[56781]2764 XMapWindow(m_pDisplay, m_wndProxy.hWnd);
2765 XRaiseWindow(m_pDisplay, m_wndProxy.hWnd);
[50724]2766
[55820]2767 /* Spawn our proxy window over the entire screen, making it an easy drop target for the host's cursor. */
[56781]2768 LogFlowThisFunc(("Proxy window x=%d, y=%d, width=%d, height=%d\n",
2769 m_wndProxy.iX, m_wndProxy.iY, m_wndProxy.iWidth, m_wndProxy.iHeight));
2770 XMoveResizeWindow(m_pDisplay, m_wndProxy.hWnd, m_wndProxy.iX, m_wndProxy.iY, m_wndProxy.iWidth, m_wndProxy.iHeight);
[55707]2771
[56651]2772 XFlush(m_pDisplay);
[50724]2773
2774 XSynchronize(m_pDisplay, False /* Disable sync */);
2775
[55918]2776#if 0
[56651]2777# ifdef VBOX_DND_WITH_XTEST
[55820]2778 XTestGrabControl(m_pDisplay, True);
[56651]2779# endif
[55820]2780#endif
2781
[56651]2782 LogFlowFuncLeaveRC(rc);
[55846]2783 return rc;
[42261]2784}
2785
[55918]2786/**
2787 * Hides the (invisible) proxy window.
2788 */
[99595]2789int VBClX11DnDInst::proxyWinHide(void)
[42261]2790{
[50734]2791 LogFlowFuncEnter();
[50724]2792
[56781]2793 XUnmapWindow(m_pDisplay, m_wndProxy.hWnd);
[56651]2794 XFlush(m_pDisplay);
[50724]2795
2796 return VINF_SUCCESS; /** @todo Add error checking. */
[42261]2797}
2798
[55918]2799/**
[56651]2800 * Allocates the name (title) of an X window.
2801 * The returned pointer must be freed using RTStrFree().
2802 *
2803 * @returns Pointer to the allocated window name.
[97738]2804 * @retval NULL on allocation failure.
2805 * @retval "<No name>" if window name was not found / invalid window handle.
[56651]2806 * @param wndThis Window to retrieve name for.
2807 */
[99595]2808char *VBClX11DnDInst::wndX11GetNameA(Window wndThis) const
[56651]2809{
2810 char *pszName = NULL;
2811
2812 XTextProperty propName;
[97738]2813 if ( wndThis != None
2814 && XGetWMName(m_pDisplay, wndThis, &propName))
[56651]2815 {
2816 if (propName.value)
2817 pszName = RTStrDup((char *)propName.value); /** @todo UTF8? */
2818 XFree(propName.value);
2819 }
2820
2821 if (!pszName) /* No window name found? */
2822 pszName = RTStrDup("<No name>");
2823
2824 return pszName;
2825}
2826
2827/**
[55918]2828 * Clear a window's supported/accepted actions list.
2829 *
2830 * @param wndThis Window to clear the list for.
2831 */
[99595]2832void VBClX11DnDInst::wndXDnDClearActionList(Window wndThis) const
[42261]2833{
[55820]2834 XDeleteProperty(m_pDisplay, wndThis, xAtom(XA_XdndActionList));
2835}
[42261]2836
[55918]2837/**
2838 * Clear a window's supported/accepted formats list.
2839 *
2840 * @param wndThis Window to clear the list for.
2841 */
[99595]2842void VBClX11DnDInst::wndXDnDClearFormatList(Window wndThis) const
[55820]2843{
2844 XDeleteProperty(m_pDisplay, wndThis, xAtom(XA_XdndTypeList));
2845}
2846
[55918]2847/**
2848 * Retrieves a window's supported/accepted XDnD actions.
2849 *
2850 * @returns IPRT status code.
2851 * @param wndThis Window to retrieve the XDnD actions for.
2852 * @param lstActions Reference to VBoxDnDAtomList to store the action into.
2853 */
[99595]2854int VBClX11DnDInst::wndXDnDGetActionList(Window wndThis, VBoxDnDAtomList &lstActions) const
[55820]2855{
2856 Atom iActType = None;
2857 int iActFmt;
2858 unsigned long cItems, cbData;
2859 unsigned char *pcbData = NULL;
2860
2861 /* Fetch the possible list of actions, if this property is set. */
2862 int xRc = XGetWindowProperty(m_pDisplay, wndThis,
2863 xAtom(XA_XdndActionList),
2864 0, VBOX_MAX_XPROPERTIES,
2865 False, XA_ATOM, &iActType, &iActFmt, &cItems, &cbData, &pcbData);
2866 if (xRc != Success)
[42261]2867 {
[55918]2868 LogFlowThisFunc(("Error getting XA_XdndActionList atoms from window=%#x: %s\n",
[55820]2869 wndThis, gX11->xErrorToString(xRc).c_str()));
2870 return VERR_NOT_FOUND;
[42261]2871 }
[55820]2872
[56651]2873 LogFlowThisFunc(("wndThis=%#x, cItems=%RU32, pcbData=%p\n", wndThis, cItems, pcbData));
2874
2875 if (cItems > 0)
[55820]2876 {
[56651]2877 AssertPtr(pcbData);
[55820]2878 Atom *paData = reinterpret_cast<Atom *>(pcbData);
2879
2880 for (unsigned i = 0; i < RT_MIN(VBOX_MAX_XPROPERTIES, cItems); i++)
2881 {
[56651]2882 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(paData[i]).c_str()));
[55820]2883 lstActions.append(paData[i]);
2884 }
2885
2886 XFree(pcbData);
2887 }
2888
2889 return VINF_SUCCESS;
[42261]2890}
2891
[55918]2892/**
2893 * Retrieves a window's supported/accepted XDnD formats.
2894 *
2895 * @returns IPRT status code.
2896 * @param wndThis Window to retrieve the XDnD formats for.
2897 * @param lstTypes Reference to VBoxDnDAtomList to store the formats into.
2898 */
[99595]2899int VBClX11DnDInst::wndXDnDGetFormatList(Window wndThis, VBoxDnDAtomList &lstTypes) const
[42261]2900{
[55820]2901 Atom iActType = None;
2902 int iActFmt;
2903 unsigned long cItems, cbData;
2904 unsigned char *pcbData = NULL;
2905
2906 int xRc = XGetWindowProperty(m_pDisplay, wndThis,
2907 xAtom(XA_XdndTypeList),
2908 0, VBOX_MAX_XPROPERTIES,
2909 False, XA_ATOM, &iActType, &iActFmt, &cItems, &cbData, &pcbData);
2910 if (xRc != Success)
2911 {
[55918]2912 LogFlowThisFunc(("Error getting XA_XdndTypeList atoms from window=%#x: %s\n",
[55820]2913 wndThis, gX11->xErrorToString(xRc).c_str()));
2914 return VERR_NOT_FOUND;
2915 }
2916
[56651]2917 LogFlowThisFunc(("wndThis=%#x, cItems=%RU32, pcbData=%p\n", wndThis, cItems, pcbData));
2918
2919 if (cItems > 0)
[55820]2920 {
[56651]2921 AssertPtr(pcbData);
2922 Atom *paData = reinterpret_cast<Atom *>(pcbData);
[55820]2923
2924 for (unsigned i = 0; i < RT_MIN(VBOX_MAX_XPROPERTIES, cItems); i++)
2925 {
[56651]2926 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(paData[i]).c_str()));
[55820]2927 lstTypes.append(paData[i]);
2928 }
2929
2930 XFree(pcbData);
2931 }
2932
2933 return VINF_SUCCESS;
2934}
2935
[55918]2936/**
2937 * Sets (replaces) a window's XDnD accepted/allowed actions.
2938 *
2939 * @returns IPRT status code.
2940 * @param wndThis Window to set the format list for.
2941 * @param lstActions Reference to list of XDnD actions to set.
2942 */
[99595]2943int VBClX11DnDInst::wndXDnDSetActionList(Window wndThis, const VBoxDnDAtomList &lstActions) const
[55820]2944{
[50724]2945 if (lstActions.isEmpty())
[55820]2946 return VINF_SUCCESS;
[42261]2947
[51529]2948 XChangeProperty(m_pDisplay, wndThis,
2949 xAtom(XA_XdndActionList),
[50724]2950 XA_ATOM, 32, PropModeReplace,
[51529]2951 reinterpret_cast<const unsigned char*>(lstActions.raw()),
[50724]2952 lstActions.size());
[42261]2953
[55820]2954 return VINF_SUCCESS;
[42261]2955}
2956
[55918]2957/**
2958 * Sets (replaces) a window's XDnD accepted format list.
2959 *
2960 * @returns IPRT status code.
2961 * @param wndThis Window to set the format list for.
2962 * @param atmProp Property to set.
2963 * @param lstFormats Reference to list of XDnD formats to set.
2964 */
[99595]2965int VBClX11DnDInst::wndXDnDSetFormatList(Window wndThis, Atom atmProp, const VBoxDnDAtomList &lstFormats) const
[42261]2966{
[55820]2967 if (lstFormats.isEmpty())
[56651]2968 return VERR_INVALID_PARAMETER;
[42261]2969
2970 /* Add the property with the property data to the window. */
[55918]2971 XChangeProperty(m_pDisplay, wndThis, atmProp,
[50724]2972 XA_ATOM, 32, PropModeReplace,
[85920]2973 reinterpret_cast<const unsigned char*>(lstFormats.raw()),
2974 lstFormats.size());
[42261]2975
[55820]2976 return VINF_SUCCESS;
[42261]2977}
2978
[55918]2979/**
[85920]2980 * Appends a RTCString list to VBoxDnDAtomList list.
[55918]2981 *
2982 * @returns IPRT status code.
2983 * @param lstFormats Reference to RTCString list to convert.
2984 * @param lstAtoms Reference to VBoxDnDAtomList list to store results in.
2985 */
[99595]2986int VBClX11DnDInst::appendFormatsToList(const RTCList<RTCString> &lstFormats, VBoxDnDAtomList &lstAtoms) const
[55918]2987{
[50724]2988 for (size_t i = 0; i < lstFormats.size(); ++i)
[55820]2989 lstAtoms.append(XInternAtom(m_pDisplay, lstFormats.at(i).c_str(), False));
[42261]2990
[55820]2991 return VINF_SUCCESS;
[42261]2992}
2993
[55918]2994/**
[85920]2995 * Appends a raw-data string list to VBoxDnDAtomList list.
[55918]2996 *
2997 * @returns IPRT status code.
2998 * @param pvData Pointer to string data to convert.
2999 * @param cbData Size (in bytes) to convert.
3000 * @param lstAtoms Reference to VBoxDnDAtomList list to store results in.
3001 */
[99595]3002int VBClX11DnDInst::appendDataToList(const void *pvData, uint32_t cbData, VBoxDnDAtomList &lstAtoms) const
[42261]3003{
[62883]3004 RT_NOREF1(lstAtoms);
[55820]3005 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
3006 AssertReturn(cbData, VERR_INVALID_PARAMETER);
[50724]3007
[55820]3008 const char *pszStr = (char *)pvData;
[50724]3009 uint32_t cbStr = cbData;
[42261]3010
[55820]3011 int rc = VINF_SUCCESS;
3012
[55918]3013 VBoxDnDAtomList lstAtom;
[50724]3014 while (cbStr)
[42261]3015 {
[50724]3016 size_t cbSize = RTStrNLen(pszStr, cbStr);
3017
[42261]3018 /* Create a copy with max N chars, so that we are on the save side,
3019 * even if the data isn't zero terminated. */
[50724]3020 char *pszTmp = RTStrDupN(pszStr, cbSize);
[55820]3021 if (!pszTmp)
3022 {
3023 rc = VERR_NO_MEMORY;
3024 break;
3025 }
3026
[50724]3027 lstAtom.append(XInternAtom(m_pDisplay, pszTmp, False));
[42261]3028 RTStrFree(pszTmp);
[55820]3029
[50724]3030 pszStr += cbSize + 1;
3031 cbStr -= cbSize + 1;
[42261]3032 }
3033
[55820]3034 return rc;
[42261]3035}
3036
[55918]3037/**
3038 * Converts a HGCM-based drag'n drop action to a Atom-based drag'n drop action.
3039 *
3040 * @returns Converted Atom-based drag'n drop action.
[74439]3041 * @param dndAction HGCM drag'n drop actions to convert.
[55918]3042 */
[42261]3043/* static */
[99595]3044Atom VBClX11DnDInst::toAtomAction(VBOXDNDACTION dndAction)
[42261]3045{
[50724]3046 /* Ignore is None. */
[74439]3047 return (isDnDCopyAction(dndAction) ? xAtom(XA_XdndActionCopy) :
3048 isDnDMoveAction(dndAction) ? xAtom(XA_XdndActionMove) :
3049 isDnDLinkAction(dndAction) ? xAtom(XA_XdndActionLink) :
[42261]3050 None);
3051}
3052
[55918]3053/**
3054 * Converts HGCM-based drag'n drop actions to a VBoxDnDAtomList list.
3055 *
3056 * @returns IPRT status code.
[74439]3057 * @param dndActionList HGCM drag'n drop actions to convert.
[55918]3058 * @param lstAtoms Reference to VBoxDnDAtomList to store actions in.
3059 */
[42261]3060/* static */
[99595]3061int VBClX11DnDInst::toAtomActions(VBOXDNDACTIONLIST dndActionList, VBoxDnDAtomList &lstAtoms)
[42261]3062{
[74439]3063 if (hasDnDCopyAction(dndActionList))
[55820]3064 lstAtoms.append(xAtom(XA_XdndActionCopy));
[74439]3065 if (hasDnDMoveAction(dndActionList))
[55820]3066 lstAtoms.append(xAtom(XA_XdndActionMove));
[74439]3067 if (hasDnDLinkAction(dndActionList))
[55820]3068 lstAtoms.append(xAtom(XA_XdndActionLink));
[42261]3069
[55820]3070 return VINF_SUCCESS;
[42261]3071}
3072
[55918]3073/**
3074 * Converts an Atom-based drag'n drop action to a HGCM drag'n drop action.
3075 *
3076 * @returns HGCM drag'n drop action.
3077 * @param atom Atom-based drag'n drop action to convert.
3078 */
[42261]3079/* static */
[99595]3080uint32_t VBClX11DnDInst::toHGCMAction(Atom atom)
[42261]3081{
[74411]3082 uint32_t uAction = VBOX_DND_ACTION_IGNORE;
[50724]3083
[42261]3084 if (atom == xAtom(XA_XdndActionCopy))
[74411]3085 uAction = VBOX_DND_ACTION_COPY;
[42261]3086 else if (atom == xAtom(XA_XdndActionMove))
[74411]3087 uAction = VBOX_DND_ACTION_MOVE;
[42261]3088 else if (atom == xAtom(XA_XdndActionLink))
[74411]3089 uAction = VBOX_DND_ACTION_LINK;
[50724]3090
[42261]3091 return uAction;
3092}
3093
[55918]3094/**
3095 * Converts an VBoxDnDAtomList list to an HGCM action list.
3096 *
3097 * @returns ORed HGCM action list.
[65122]3098 * @param lstActions List of Atom-based actions to convert.
[55918]3099 */
[42261]3100/* static */
[99595]3101uint32_t VBClX11DnDInst::toHGCMActions(const VBoxDnDAtomList &lstActions)
[42261]3102{
[74411]3103 uint32_t uActions = VBOX_DND_ACTION_IGNORE;
[50724]3104
[56651]3105 for (size_t i = 0; i < lstActions.size(); i++)
[55918]3106 uActions |= toHGCMAction(lstActions.at(i));
[50724]3107
[42261]3108 return uActions;
3109}
3110
[85920]3111/*********************************************************************************************************************************
3112 * VBoxDnDProxyWnd implementation. *
3113 ********************************************************************************************************************************/
[56781]3114
[99595]3115VBClX11DnDProxyWnd::VBClX11DnDProxyWnd(void)
[56781]3116 : pDisp(NULL)
3117 , hWnd(0)
3118 , iX(0)
3119 , iY(0)
3120 , iWidth(0)
3121 , iHeight(0)
3122{
3123
3124}
3125
[99595]3126VBClX11DnDProxyWnd::~VBClX11DnDProxyWnd(void)
[56781]3127{
3128 destroy();
3129}
3130
[99595]3131int VBClX11DnDProxyWnd::init(Display *pDisplay)
[56781]3132{
3133 /** @todo What about multiple screens? Test this! */
3134 int iScreenID = XDefaultScreen(pDisplay);
3135
3136 iWidth = XDisplayWidth(pDisplay, iScreenID);
3137 iHeight = XDisplayHeight(pDisplay, iScreenID);
3138 pDisp = pDisplay;
3139
3140 return VINF_SUCCESS;
3141}
3142
[99595]3143void VBClX11DnDProxyWnd::destroy(void)
[56781]3144{
3145
3146}
3147
[99595]3148int VBClX11DnDProxyWnd::sendFinished(Window hWndSource, VBOXDNDACTION dndAction)
[56781]3149{
3150 /* Was the drop accepted by the host? That is, anything than ignoring. */
[74439]3151 bool fDropAccepted = dndAction > VBOX_DND_ACTION_IGNORE;
[56781]3152
[74459]3153 LogFlowFunc(("dndAction=0x%x\n", dndAction));
[57283]3154
[56781]3155 /* Confirm the result of the transfer to the target window. */
3156 XClientMessageEvent m;
3157 RT_ZERO(m);
3158 m.type = ClientMessage;
3159 m.display = pDisp;
3160 m.window = hWnd;
3161 m.message_type = xAtom(XA_XdndFinished);
3162 m.format = 32;
[74439]3163 m.data.l[XdndFinishedWindow] = hWnd; /* Target window. */
3164 m.data.l[XdndFinishedFlags] = fDropAccepted ? RT_BIT(0) : 0; /* Was the drop accepted? */
[99595]3165 m.data.l[XdndFinishedAction] = fDropAccepted ? VBClX11DnDInst::toAtomAction(dndAction) : None; /* Action used on accept. */
[56781]3166
3167 int xRc = XSendEvent(pDisp, hWndSource, True, NoEventMask, reinterpret_cast<XEvent*>(&m));
3168 if (xRc == 0)
3169 {
[97734]3170 VBClLogError("Error sending finished event to source window=%#x: %s\n",
[81040]3171 hWndSource, gX11->xErrorToString(xRc).c_str());
[56781]3172
3173 return VERR_GENERAL_FAILURE; /** @todo Fudge. */
3174 }
3175
3176 return VINF_SUCCESS;
3177}
3178
[85920]3179/*********************************************************************************************************************************
3180 * DragAndDropService implementation. *
3181 ********************************************************************************************************************************/
[46377]3182
[86871]3183/** @copydoc VBCLSERVICE::pfnInit */
[99595]3184int VBClX11DnDSvc::init(void)
[60981]3185{
3186 LogFlowFuncEnter();
3187
3188 /* Connect to the x11 server. */
3189 m_pDisplay = XOpenDisplay(NULL);
3190 if (!m_pDisplay)
3191 {
[81040]3192 VBClLogFatalError("Unable to connect to X server -- running in a terminal session?\n");
[60981]3193 return VERR_NOT_FOUND;
3194 }
3195
[99595]3196 VBClX11DnDXHelpers *pHelpers = VBClX11DnDXHelpers::getInstance(m_pDisplay);
[60981]3197 if (!pHelpers)
3198 return VERR_NO_MEMORY;
3199
[81028]3200 int rc;
3201
[60981]3202 do
3203 {
3204 rc = RTSemEventCreate(&m_hEventSem);
[85566]3205 AssertRCBreak(rc);
[60981]3206
3207 rc = RTCritSectInit(&m_eventQueueCS);
[85566]3208 AssertRCBreak(rc);
[60981]3209
[85566]3210 rc = VbglR3DnDConnect(&m_dndCtx);
3211 AssertRCBreak(rc);
3212
[60981]3213 /* Event thread for events coming from the HGCM device. */
3214 rc = RTThreadCreate(&m_hHGCMThread, hgcmEventThread, this,
3215 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE, "dndHGCM");
[85566]3216 AssertRCBreak(rc);
[60981]3217
[86871]3218 rc = RTThreadUserWait(m_hHGCMThread, RT_MS_30SEC);
[85566]3219 AssertRCBreak(rc);
[60981]3220
[85566]3221 if (ASMAtomicReadBool(&m_fStop))
[60981]3222 break;
3223
3224 /* Event thread for events coming from the x11 system. */
3225 rc = RTThreadCreate(&m_hX11Thread, x11EventThread, this,
3226 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE, "dndX11");
[85566]3227 AssertRCBreak(rc);
[60981]3228
[86871]3229 rc = RTThreadUserWait(m_hX11Thread, RT_MS_30SEC);
[85566]3230 AssertRCBreak(rc);
[60981]3231
[85566]3232 if (ASMAtomicReadBool(&m_fStop))
[60981]3233 break;
3234
3235 } while (0);
3236
[85566]3237 if (m_fStop)
[60981]3238 rc = VERR_GENERAL_FAILURE; /** @todo Fudge! */
3239
3240 if (RT_FAILURE(rc))
[81040]3241 VBClLogError("Failed to initialize, rc=%Rrc\n", rc);
[60981]3242
3243 LogFlowFuncLeaveRC(rc);
3244 return rc;
3245}
3246
[86871]3247/** @copydoc VBCLSERVICE::pfnWorker */
[99595]3248int VBClX11DnDSvc::worker(bool volatile *pfShutdown)
[42261]3249{
[50724]3250 int rc;
[42261]3251 do
3252 {
[99595]3253 m_pCurDnD = new VBClX11DnDInst(m_pDisplay, this);
[50265]3254 if (!m_pCurDnD)
[49891]3255 {
3256 rc = VERR_NO_MEMORY;
3257 break;
3258 }
[50724]3259
[42261]3260 /* Note: For multiple screen support in VBox it is not necessary to use
3261 * another screen number than zero. Maybe in the future it will become
3262 * necessary if VBox supports multiple X11 screens. */
[60967]3263 rc = m_pCurDnD->init(0 /* uScreenID */);
3264 /* Note: Can return VINF_PERMISSION_DENIED if HGCM host service is not available. */
3265 if (rc != VINF_SUCCESS)
3266 {
3267 if (RT_FAILURE(rc))
[81040]3268 VBClLogError("Unable to connect to drag and drop service, rc=%Rrc\n", rc);
[86871]3269 else if (rc == VINF_PERMISSION_DENIED) /* No error, DnD might be just disabled. */
3270 VBClLogInfo("Not available on host, terminating\n");
[49891]3271 break;
[60967]3272 }
[49891]3273
[86871]3274 /* Let the main thread know that it can continue spawning services. */
3275 RTThreadUserSignal(RTThreadSelf());
[50724]3276
3277 /* Enter the main event processing loop. */
[42261]3278 do
3279 {
[99595]3280 VBCLDNDEVENT e;
[42261]3281 RT_ZERO(e);
[50724]3282
[97740]3283 LogFlowFunc(("Waiting for new events ...\n"));
[50724]3284 rc = RTSemEventWait(m_hEventSem, RT_INDEFINITE_WAIT);
[51529]3285 if (RT_FAILURE(rc))
[50724]3286 break;
3287
[97740]3288 size_t cEvents = 0;
[50724]3289
[97740]3290 int rc2 = RTCritSectEnter(&m_eventQueueCS);
3291 if (RT_SUCCESS(rc2))
3292 {
3293 cEvents = m_eventQueue.size();
[50724]3294
[97740]3295 rc2 = RTCritSectLeave(&m_eventQueueCS);
3296 AssertRC(rc2);
3297 }
3298
3299 while (cEvents)
[42261]3300 {
[97740]3301 rc2 = RTCritSectEnter(&m_eventQueueCS);
3302 if (RT_SUCCESS(rc2))
3303 {
3304 if (m_eventQueue.isEmpty())
3305 {
3306 rc2 = RTCritSectLeave(&m_eventQueueCS);
3307 AssertRC(rc2);
3308 break;
3309 }
[74380]3310
[97740]3311 e = m_eventQueue.first();
3312 m_eventQueue.removeFirst();
3313
3314 rc2 = RTCritSectLeave(&m_eventQueueCS);
3315 AssertRC(rc2);
3316 }
3317
[99595]3318 if (e.enmType == VBCLDNDEVENT::DnDEventType_HGCM)
[42261]3319 {
[97740]3320 PVBGLR3DNDEVENT pVbglR3Event = e.hgcm;
3321 AssertPtrBreak(pVbglR3Event);
3322
3323 LogFlowThisFunc(("HGCM event enmType=%RU32\n", pVbglR3Event->enmType));
3324 switch (pVbglR3Event->enmType)
[42261]3325 {
[97740]3326 case VBGLR3DNDEVENTTYPE_HG_ENTER:
[42261]3327 {
[97740]3328 if (pVbglR3Event->u.HG_Enter.cbFormats)
3329 {
3330 RTCList<RTCString> lstFormats =
[97827]3331 RTCString(pVbglR3Event->u.HG_Enter.pszFormats, pVbglR3Event->u.HG_Enter.cbFormats - 1).split(DND_PATH_SEPARATOR_STR);
[97740]3332 rc = m_pCurDnD->hgEnter(lstFormats, pVbglR3Event->u.HG_Enter.dndLstActionsAllowed);
3333 if (RT_FAILURE(rc))
3334 break;
3335 /* Enter is always followed by a move event. */
3336 }
3337 else
3338 {
3339 AssertMsgFailed(("cbFormats is 0\n"));
3340 rc = VERR_INVALID_PARAMETER;
[74380]3341 break;
[97740]3342 }
3343
3344 /* Note: After HOST_DND_FN_HG_EVT_ENTER there immediately is a move
3345 * event, so fall through is intentional here. */
3346 RT_FALL_THROUGH();
[42261]3347 }
[97740]3348
3349 case VBGLR3DNDEVENTTYPE_HG_MOVE:
[55820]3350 {
[97740]3351 rc = m_pCurDnD->hgMove(pVbglR3Event->u.HG_Move.uXpos, pVbglR3Event->u.HG_Move.uYpos,
3352 pVbglR3Event->u.HG_Move.dndActionDefault);
[42261]3353 break;
[55820]3354 }
[74380]3355
[97740]3356 case VBGLR3DNDEVENTTYPE_HG_LEAVE:
3357 {
3358 rc = m_pCurDnD->hgLeave();
3359 break;
3360 }
[74380]3361
[97740]3362 case VBGLR3DNDEVENTTYPE_HG_DROP:
3363 {
3364 rc = m_pCurDnD->hgDrop(pVbglR3Event->u.HG_Drop.uXpos, pVbglR3Event->u.HG_Drop.uYpos,
3365 pVbglR3Event->u.HG_Drop.dndActionDefault);
3366 break;
3367 }
[74380]3368
[97740]3369 /* Note: VbglR3DnDRecvNextMsg() will return HOST_DND_FN_HG_SND_DATA_HDR when
3370 * the host has finished copying over all the data to the guest.
3371 *
3372 * The actual data transfer (and message processing for it) will be done
3373 * internally by VbglR3DnDRecvNextMsg() to not duplicate any code for different
3374 * platforms.
3375 *
3376 * The data header now will contain all the (meta) data the guest needs in
3377 * order to complete the DnD operation. */
3378 case VBGLR3DNDEVENTTYPE_HG_RECEIVE:
3379 {
3380 rc = m_pCurDnD->hgDataReceive(&pVbglR3Event->u.HG_Received.Meta);
3381 break;
3382 }
[74380]3383
[97764]3384 case VBGLR3DNDEVENTTYPE_CANCEL:
[97740]3385 {
[97764]3386 m_pCurDnD->reset();
[97740]3387 break;
3388 }
[74380]3389
[97740]3390#ifdef VBOX_WITH_DRAG_AND_DROP_GH
3391 case VBGLR3DNDEVENTTYPE_GH_ERROR:
3392 {
3393 m_pCurDnD->reset();
3394 break;
3395 }
[74380]3396
[97740]3397 case VBGLR3DNDEVENTTYPE_GH_REQ_PENDING:
3398 {
3399 rc = m_pCurDnD->ghIsDnDPending();
3400 break;
3401 }
[74380]3402
[97740]3403 case VBGLR3DNDEVENTTYPE_GH_DROP:
3404 {
3405 rc = m_pCurDnD->ghDropped(pVbglR3Event->u.GH_Drop.pszFormat, pVbglR3Event->u.GH_Drop.dndActionRequested);
3406 break;
3407 }
3408#endif
3409 case VBGLR3DNDEVENTTYPE_QUIT:
3410 {
3411 rc = VINF_SUCCESS;
3412 break;
3413 }
3414
3415 default:
3416 {
3417 VBClLogError("Received unsupported message type %RU32\n", pVbglR3Event->enmType);
3418 rc = VERR_NOT_SUPPORTED;
3419 break;
3420 }
[74380]3421 }
3422
[97740]3423 LogFlowFunc(("Message %RU32 processed with %Rrc\n", pVbglR3Event->enmType, rc));
3424 if (RT_FAILURE(rc))
[74380]3425 {
[97740]3426 /* Tell the user. */
3427 VBClLogError("Processing message %RU32 failed with %Rrc\n", pVbglR3Event->enmType, rc);
[74380]3428
[97740]3429 /* If anything went wrong, do a reset and start over. */
3430 reset();
[42261]3431 }
[86871]3432
[97740]3433 const bool fQuit = pVbglR3Event->enmType == VBGLR3DNDEVENTTYPE_QUIT;
3434
3435 VbglR3DnDEventFree(e.hgcm);
3436 e.hgcm = NULL;
3437
3438 if (fQuit)
[50724]3439 break;
[42261]3440 }
[99595]3441 else if (e.enmType == VBCLDNDEVENT::DnDEventType_X11)
[55820]3442 {
[97740]3443 LogFlowThisFunc(("X11 event (type %#x)\n", e.x11.type));
3444 m_pCurDnD->onX11Event(e.x11);
[55820]3445 }
[97740]3446 else
3447 AssertMsgFailed(("Unknown event queue type %RU32\n", e.enmType));
[55820]3448
[97740]3449 --cEvents;
[86871]3450
[97740]3451 } /* for */
[86871]3452
[55820]3453 /*
3454 * Make sure that any X11 requests have actually been sent to the
[50643]3455 * server, since we are waiting for responses using poll() on
[55918]3456 * another thread which will not automatically trigger flushing.
3457 */
[50639]3458 XFlush(m_pDisplay);
[50724]3459
[86871]3460 if (m_fStop)
3461 break;
[50724]3462
[86871]3463 } while (!ASMAtomicReadBool(pfShutdown));
[60967]3464
[46377]3465 } while (0);
[42261]3466
[60981]3467 if (m_pCurDnD)
3468 {
3469 delete m_pCurDnD;
3470 m_pCurDnD = NULL;
3471 }
3472
3473 LogFlowFuncLeaveRC(rc);
[42261]3474 return rc;
3475}
3476
[97737]3477/**
3478 * Resets the DnD service' data.
3479 */
[99595]3480void VBClX11DnDSvc::reset(void)
[97737]3481{
3482 LogFlowFuncEnter();
3483
3484 if (m_pCurDnD)
3485 m_pCurDnD->reset();
3486
3487 /*
3488 * Clear the event queue.
3489 */
3490 int rc2 = RTCritSectEnter(&m_eventQueueCS);
3491 if (RT_SUCCESS(rc2))
3492 {
3493 for (size_t i = 0; i < m_eventQueue.size(); i++)
3494 {
3495 switch (m_eventQueue[i].enmType)
3496 {
[99595]3497 case VBCLDNDEVENT::DnDEventType_HGCM:
[97737]3498 {
3499 VbglR3DnDEventFree(m_eventQueue[i].hgcm);
3500 break;
3501 }
3502
3503 default:
3504 break;
3505 }
3506
3507 }
3508
3509 m_eventQueue.clear();
3510
3511 rc2 = RTCritSectLeave(&m_eventQueueCS);
3512 AssertRC(rc2);
3513 }
3514
3515 LogFlowFuncLeave();
3516}
3517
[86871]3518/** @copydoc VBCLSERVICE::pfnStop */
[99595]3519void VBClX11DnDSvc::stop(void)
[42261]3520{
[60981]3521 LogFlowFuncEnter();
[55820]3522
[85566]3523 /* Set stop flag first. */
3524 ASMAtomicXchgBool(&m_fStop, true);
[61654]3525
[86871]3526 /* First, disconnect any instances. */
3527 if (m_pCurDnD)
3528 m_pCurDnD->stop();
3529
3530 /* Second, disconnect the service's DnD connection. */
[85566]3531 VbglR3DnDDisconnect(&m_dndCtx);
3532
[86871]3533 LogFlowFuncLeave();
3534}
3535
3536/** @copydoc VBCLSERVICE::pfnTerm */
[99595]3537int VBClX11DnDSvc::term(void)
[86871]3538{
3539 int rc = VINF_SUCCESS;
3540
[60981]3541 /*
3542 * Wait for threads to terminate.
3543 */
[86871]3544 int rcThread;
3545
3546 if (m_hX11Thread != NIL_RTTHREAD)
[56760]3547 {
[86871]3548 VBClLogVerbose(2, "Terminating X11 thread ...\n");
[85566]3549
[86871]3550 int rc2 = RTThreadWait(m_hX11Thread, RT_MS_30SEC, &rcThread);
[60981]3551 if (RT_SUCCESS(rc2))
3552 rc2 = rcThread;
3553
3554 if (RT_FAILURE(rc2))
[86871]3555 VBClLogError("Error waiting for X11 thread to terminate: %Rrc\n", rc2);
3556
3557 if (RT_SUCCESS(rc))
3558 rc = rc2;
3559
3560 m_hX11Thread = NIL_RTTHREAD;
3561
3562 VBClLogVerbose(2, "X11 thread terminated\n");
[56760]3563 }
[42261]3564
[86871]3565 if (m_hHGCMThread != NIL_RTTHREAD)
[42261]3566 {
[86871]3567 VBClLogVerbose(2, "Terminating HGCM thread ...\n");
[85566]3568
[86871]3569 int rc2 = RTThreadWait(m_hHGCMThread, RT_MS_30SEC, &rcThread);
[60981]3570 if (RT_SUCCESS(rc2))
3571 rc2 = rcThread;
[50724]3572
[60981]3573 if (RT_FAILURE(rc2))
[86871]3574 VBClLogError("Error waiting for HGCM thread to terminate: %Rrc\n", rc2);
3575
3576 if (RT_SUCCESS(rc))
3577 rc = rc2;
3578
3579 m_hHGCMThread = NIL_RTTHREAD;
3580
3581 VBClLogVerbose(2, "HGCM thread terminated\n");
[60981]3582 }
[50724]3583
[97737]3584 reset();
3585
[86871]3586 if (m_pCurDnD)
3587 {
3588 delete m_pCurDnD;
3589 m_pCurDnD = NULL;
3590 }
[50724]3591
[99595]3592 VBClX11DnDXHelpers::destroyInstance();
[42261]3593
[86871]3594 return rc;
[42261]3595}
3596
[55918]3597/**
3598 * Static callback function for HGCM message processing thread. An internal
3599 * message queue will be filled which then will be processed by the according
3600 * drag'n drop instance.
3601 *
3602 * @returns IPRT status code.
3603 * @param hThread Thread handle to use.
3604 * @param pvUser Pointer to DragAndDropService instance to use.
3605 */
[42261]3606/* static */
[99595]3607DECLCALLBACK(int) VBClX11DnDSvc::hgcmEventThread(RTTHREAD hThread, void *pvUser)
[42261]3608{
3609 AssertPtrReturn(pvUser, VERR_INVALID_PARAMETER);
[99595]3610 VBClX11DnDSvc *pThis = static_cast<VBClX11DnDSvc*>(pvUser);
[49891]3611
[60981]3612 /* Let the service instance know in any case. */
[85566]3613 int rc = RTThreadUserSignal(hThread);
3614 AssertRCReturn(rc, rc);
[60981]3615
[86871]3616 VBClLogVerbose(2, "HGCM thread started\n");
3617
[50265]3618 /* Number of invalid messages skipped in a row. */
3619 int cMsgSkippedInvalid = 0;
[99595]3620 VBCLDNDEVENT e;
[50265]3621
[42261]3622 do
3623 {
3624 RT_ZERO(e);
[99595]3625 e.enmType = VBCLDNDEVENT::DnDEventType_HGCM;
[50724]3626
3627 /* Wait for new events. */
[85566]3628 rc = VbglR3DnDEventGetNext(&pThis->m_dndCtx, &e.hgcm);
[74472]3629 if (RT_SUCCESS(rc))
[42261]3630 {
[50265]3631 cMsgSkippedInvalid = 0; /* Reset skipped messages count. */
[50724]3632
[97740]3633 int rc2 = RTCritSectEnter(&pThis->m_eventQueueCS);
3634 if (RT_SUCCESS(rc2))
3635 {
3636 VBClLogVerbose(2, "Received new HGCM message (type %#x)\n", e.hgcm->enmType);
3637
3638 pThis->m_eventQueue.append(e);
3639
3640 rc2 = RTCritSectLeave(&pThis->m_eventQueueCS);
3641 AssertRC(rc2);
3642 }
3643
[46377]3644 rc = RTSemEventSignal(pThis->m_hEventSem);
[42261]3645 if (RT_FAILURE(rc))
[50724]3646 break;
[42261]3647 }
[50265]3648 else
3649 {
[86871]3650 VBClLogError("Processing next message failed with rc=%Rrc\n", rc);
[55422]3651
[86871]3652 /* Old(er) hosts either are broken regarding DnD support or otherwise
3653 * don't support the stuff we do on the guest side, so make sure we
3654 * don't process invalid messages forever. */
3655
3656 if (cMsgSkippedInvalid++ > 32)
[50265]3657 {
[86871]3658 VBClLogError("Too many invalid/skipped messages from host, exiting ...\n");
3659 break;
[50265]3660 }
3661 }
3662
[85566]3663 } while (!ASMAtomicReadBool(&pThis->m_fStop));
[42261]3664
[86871]3665 VBClLogVerbose(2, "HGCM thread ended\n");
3666
[50724]3667 LogFlowFuncLeaveRC(rc);
3668 return rc;
[42261]3669}
3670
[55918]3671/**
3672 * Static callback function for X11 message processing thread. All X11 messages
3673 * will be directly routed to the according drag'n drop instance.
3674 *
3675 * @returns IPRT status code.
3676 * @param hThread Thread handle to use.
3677 * @param pvUser Pointer to DragAndDropService instance to use.
3678 */
[42261]3679/* static */
[99595]3680DECLCALLBACK(int) VBClX11DnDSvc::x11EventThread(RTTHREAD hThread, void *pvUser)
[42261]3681{
3682 AssertPtrReturn(pvUser, VERR_INVALID_PARAMETER);
[99595]3683 VBClX11DnDSvc *pThis = static_cast<VBClX11DnDSvc*>(pvUser);
[50724]3684 AssertPtr(pThis);
3685
3686 int rc = VINF_SUCCESS;
3687
[60981]3688 /* Note: Nothing to initialize here (yet). */
3689
3690 /* Let the service instance know in any case. */
3691 int rc2 = RTThreadUserSignal(hThread);
3692 AssertRC(rc2);
3693
[86871]3694 VBClLogVerbose(2, "X11 thread started\n");
3695
[99595]3696 VBCLDNDEVENT e;
[97740]3697 RT_ZERO(e);
[99595]3698 e.enmType = VBCLDNDEVENT::DnDEventType_X11;
[97740]3699
[42261]3700 do
3701 {
[51529]3702 /*
[50724]3703 * Wait for new events. We can't use XIfEvent here, cause this locks
[42261]3704 * the window connection with a mutex and if no X11 events occurs this
[50724]3705 * blocks any other calls we made to X11. So instead check for new
3706 * events and if there are not any new one, sleep for a certain amount
[51529]3707 * of time.
3708 */
[97740]3709 unsigned cNewEvents = 0;
3710 unsigned cQueued = XEventsQueued(pThis->m_pDisplay, QueuedAfterFlush);
3711 while (cQueued)
[42261]3712 {
[50724]3713 /* XNextEvent will block until a new X event becomes available. */
[46377]3714 XNextEvent(pThis->m_pDisplay, &e.x11);
[51529]3715 {
[97740]3716 rc2 = RTCritSectEnter(&pThis->m_eventQueueCS);
3717 if (RT_SUCCESS(rc2))
3718 {
3719 LogFlowFunc(("Added new X11 event, type=%d\n", e.x11.type));
[50724]3720
[97740]3721 pThis->m_eventQueue.append(e);
3722 cNewEvents++;
3723
3724 rc2 = RTCritSectLeave(&pThis->m_eventQueueCS);
3725 AssertRC(rc2);
3726 }
[42261]3727 }
[97740]3728
3729 cQueued--;
[42261]3730 }
3731
[97740]3732 if (cNewEvents)
3733 {
3734 rc = RTSemEventSignal(pThis->m_hEventSem);
3735 if (RT_FAILURE(rc))
3736 break;
3737
3738 continue;
3739 }
3740
3741 /* No new events; wait a bit. */
3742 RTThreadSleep(25 /* ms */);
3743
[85566]3744 } while (!ASMAtomicReadBool(&pThis->m_fStop));
[50639]3745
[86871]3746 VBClLogVerbose(2, "X11 thread ended\n");
3747
[50724]3748 LogFlowFuncLeaveRC(rc);
3749 return rc;
[42261]3750}
[81052]3751
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use