VirtualBox

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

Last change on this file since 97739 was 97739, checked in by vboxsync, 2 years ago

DnD/VBoxClient: Save the (fake) mouse move coordinates in DragInstance::mouseCursorMove() to not send the same coordinates again to a target window + flush the display afterwards.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette