VirtualBox

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

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

DnD/VBoxClient: Revamped the X11/HGCM event handling so that it can handle more than one event per signalling the event. Also, don't clear the event queue implicitly in DragInstance::proxyWinHide(), to avoid any (unwanted) side effects (use DragInstance::reset() for that).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 131.5 KB
Line 
1/* $Id: draganddrop.cpp 97740 2022-12-05 09:00:05Z 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 /* Reset the selection request buffer. */
824 if (m_pvSelReqData)
825 {
826 RTMemFree(m_pvSelReqData);
827 m_pvSelReqData = NULL;
828
829 Assert(m_cbSelReqData);
830 m_cbSelReqData = 0;
831 }
832
833 rc2 = RTCritSectEnter(&m_eventQueueCS);
834 if (RT_SUCCESS(rc2))
835 {
836 m_eventQueueList.clear();
837
838 rc2 = RTCritSectLeave(&m_eventQueueCS);
839 AssertRC(rc2);
840 }
841
842 RTCritSectLeave(&m_dataCS);
843 }
844
845 LogFlowFuncLeave();
846}
847
848/**
849 * Initializes this drag instance.
850 *
851 * @return IPRT status code.
852 * @param uScreenID X' screen ID to use.
853 */
854int DragInstance::init(uint32_t uScreenID)
855{
856 int rc = VbglR3DnDConnect(&m_dndCtx);
857 /* Note: Can return VINF_PERMISSION_DENIED if HGCM host service is not available. */
858 if (rc != VINF_SUCCESS)
859 return rc;
860
861 if (g_cVerbosity)
862 {
863 RTCString strBody = RTCStringFmt("Connected (screen %RU32, verbosity %u)", uScreenID, g_cVerbosity);
864 VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER, strBody.c_str());
865 }
866
867 do
868 {
869 rc = RTSemEventCreate(&m_eventQueueEvent);
870 if (RT_FAILURE(rc))
871 break;
872
873 rc = RTCritSectInit(&m_eventQueueCS);
874 if (RT_FAILURE(rc))
875 break;
876
877 rc = RTCritSectInit(&m_dataCS);
878 if (RT_FAILURE(rc))
879 break;
880
881 /*
882 * Enough screens configured in the x11 server?
883 */
884 if ((int)uScreenID > ScreenCount(m_pDisplay))
885 {
886 rc = VERR_INVALID_PARAMETER;
887 break;
888 }
889#if 0
890 /* Get the screen number from the x11 server. */
891 pDrag->screen = ScreenOfDisplay(m_pDisplay, uScreenID);
892 if (!pDrag->screen)
893 {
894 rc = VERR_GENERAL_FAILURE;
895 break;
896 }
897#endif
898 m_screenID = uScreenID;
899
900 /* Now query the corresponding root window of this screen. */
901 m_wndRoot = RootWindow(m_pDisplay, m_screenID);
902 if (!m_wndRoot)
903 {
904 rc = VERR_GENERAL_FAILURE;
905 break;
906 }
907
908 /*
909 * Create an invisible window which will act as proxy for the DnD
910 * operation. This window will be used for both the GH and HG
911 * direction.
912 */
913 XSetWindowAttributes attr;
914 RT_ZERO(attr);
915 attr.event_mask = EnterWindowMask | LeaveWindowMask
916 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
917 attr.override_redirect = True;
918 attr.do_not_propagate_mask = NoEventMask;
919
920 if (g_cVerbosity >= 3)
921 {
922 attr.background_pixel = XWhitePixel(m_pDisplay, m_screenID);
923 attr.border_pixel = XBlackPixel(m_pDisplay, m_screenID);
924 m_wndProxy.hWnd = XCreateWindow(m_pDisplay, m_wndRoot /* Parent */,
925 100, 100, /* Position */
926 100, 100, /* Width + height */
927 2, /* Border width */
928 CopyFromParent, /* Depth */
929 InputOutput, /* Class */
930 CopyFromParent, /* Visual */
931 CWBackPixel
932 | CWBorderPixel
933 | CWOverrideRedirect
934 | CWDontPropagate, /* Value mask */
935 &attr); /* Attributes for value mask */
936 }
937
938 m_wndProxy.hWnd = XCreateWindow(m_pDisplay, m_wndRoot /* Parent */,
939 0, 0, /* Position */
940 1, 1, /* Width + height */
941 0, /* Border width */
942 CopyFromParent, /* Depth */
943 InputOnly, /* Class */
944 CopyFromParent, /* Visual */
945 CWOverrideRedirect | CWDontPropagate, /* Value mask */
946 &attr); /* Attributes for value mask */
947
948 if (!m_wndProxy.hWnd)
949 {
950 VBClLogError("Error creating proxy window\n");
951 rc = VERR_GENERAL_FAILURE;
952 break;
953 }
954
955 rc = m_wndProxy.init(m_pDisplay);
956 if (RT_FAILURE(rc))
957 {
958 VBClLogError("Error initializing proxy window, rc=%Rrc\n", rc);
959 break;
960 }
961
962 if (g_cVerbosity >= 3) /* Make debug window visible. */
963 {
964 XFlush(m_pDisplay);
965 XMapWindow(m_pDisplay, m_wndProxy.hWnd);
966 XRaiseWindow(m_pDisplay, m_wndProxy.hWnd);
967 XFlush(m_pDisplay);
968 }
969
970 VBClLogInfo("Proxy window=%#x (debug mode: %RTbool), root window=%#x ...\n",
971 m_wndProxy.hWnd, RT_BOOL(g_cVerbosity >= 3), m_wndRoot);
972
973 /* Set the window's name for easier lookup. */
974 XStoreName(m_pDisplay, m_wndProxy.hWnd, "VBoxClientWndDnD");
975
976 /* Make the new window Xdnd aware. */
977 Atom atmVer = VBOX_XDND_VERSION;
978 XChangeProperty(m_pDisplay, m_wndProxy.hWnd, xAtom(XA_XdndAware), XA_ATOM, 32, PropModeReplace,
979 reinterpret_cast<unsigned char*>(&atmVer), 1);
980 } while (0);
981
982 if (RT_SUCCESS(rc))
983 {
984 reset();
985 }
986 else
987 VBClLogError("Initializing drag instance for screen %RU32 failed with rc=%Rrc\n", uScreenID, rc);
988
989 LogFlowFuncLeaveRC(rc);
990 return rc;
991}
992
993/**
994 * Callback handler for a generic client message from a window.
995 *
996 * @return IPRT status code.
997 * @param e X11 event to handle.
998 */
999int DragInstance::onX11ClientMessage(const XEvent &e)
1000{
1001 AssertReturn(e.type == ClientMessage, VERR_INVALID_PARAMETER);
1002
1003 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1004 LogFlowThisFunc(("Event wnd=%#x, msg=%s\n", e.xclient.window, xAtomToString(e.xclient.message_type).c_str()));
1005
1006 int rc = VINF_SUCCESS;
1007
1008 char *pszWndCurName = wndX11GetNameA(m_wndCur);
1009 AssertPtrReturn(pszWndCurName, VERR_NO_MEMORY);
1010
1011 switch (m_enmMode)
1012 {
1013 case HG:
1014 {
1015 /*
1016 * Client messages are used to inform us about the status of a XdndAware
1017 * window, in response of some events we send to them.
1018 */
1019
1020 /* The target window informs us of the current Xdnd status. */
1021 if (e.xclient.message_type == xAtom(XA_XdndStatus))
1022 {
1023 Window wndTgt = static_cast<Window>(e.xclient.data.l[XdndStatusWindow]);
1024
1025 char *pszWndTgtName = wndX11GetNameA(wndTgt);
1026 AssertPtrBreakStmt(pszWndTgtName, VERR_NO_MEMORY);
1027
1028 /* Does the target accept the drop? */
1029 bool const fAcceptDrop = RT_BOOL(e.xclient.data.l[XdndStatusFlags] & VBOX_XDND_STATUS_FLAG_ACCEPT);
1030 /* Does the target want XdndPosition messages? */
1031 bool const fWantsPosition = RT_BOOL(e.xclient.data.l[XdndStatusFlags] & VBOX_XDND_STATUS_FLAG_WANTS_POS);
1032
1033 /*
1034 * The XdndStatus message tell us if the window will accept the DnD
1035 * event and with which action. We immediately send this info down to
1036 * the host as a response of a previous DnD message.
1037 */
1038 RTCString strActions = xAtomToString(e.xclient.data.l[XdndStatusAction]);
1039
1040 VBClLogInfo("Target window %#x ('%s')\n", wndTgt, pszWndTgtName);
1041 VBClLogInfo(" - %s accept data (actions '%s')\n", fAcceptDrop ? "does" : "does not", strActions.c_str());
1042 VBClLogInfo(" - %s want position messages\n", fWantsPosition ? "does" : "does not");
1043
1044 uint16_t const x = RT_HI_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgXY]);
1045 uint16_t const y = RT_LO_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgXY]);
1046 uint16_t const cx = RT_HI_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgWH]);
1047 uint16_t const cy = RT_LO_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgWH]);
1048
1049 if (cx && cy)
1050 {
1051 VBClLogInfo("Target window %#x ('%s') reported dead area at %RU16,%RU16 (%RU16 x %RU16)\n",
1052 wndTgt, pszWndTgtName, x, y, cx, cy);
1053 /** @todo Save dead area and don't send XdndPosition messages anymore into it. */
1054 }
1055
1056 if (m_wndCur == wndTgt)
1057 {
1058 VBOXDNDACTION dndAction = VBOX_DND_ACTION_IGNORE; /* Default is ignoring. */
1059 /** @todo Compare this with the allowed actions. */
1060 if (fAcceptDrop)
1061 dndAction = toHGCMAction(static_cast<Atom>(e.xclient.data.l[XdndStatusAction]));
1062
1063 rc = VbglR3DnDHGSendAckOp(&m_dndCtx, dndAction);
1064 }
1065 else
1066 VBClLogInfo("Target window %#x ('%s') is not our current window, skipping\n", wndTgt, pszWndTgtName);
1067
1068 RTStrFree(pszWndTgtName);
1069 }
1070 /* The target window informs us that it finished the Xdnd operation and that we may free all data. */
1071 else if (e.xclient.message_type == xAtom(XA_XdndFinished))
1072 {
1073 Window wndTarget = static_cast<Window>(e.xclient.data.l[XdndFinishedWindow]);
1074
1075 char *pszWndTgtName = wndX11GetNameA(wndTarget);
1076 AssertPtrBreakStmt(pszWndTgtName, VERR_NO_MEMORY);
1077
1078 if (m_uXdndVer >= 5)
1079 {
1080 const bool fSucceeded = e.xclient.data.l[XdndFinishedFlags] & VBOX_XDND_FINISHED_FLAG_SUCCEEDED;
1081 #if 0 /** @todo Returns garbage -- investigate this! */
1082 //const char *pcszAction = fSucceeded ? xAtomToString(e.xclient.data.l[XdndFinishedAction]).c_str() : NULL;
1083 #endif
1084 VBClLogInfo("Target window %#x ('%s') has %s the data\n",
1085 wndTarget, pszWndTgtName, fSucceeded ? "accepted" : "rejected");
1086 }
1087 else /* Xdnd < version 5 did not have the XdndFinishedFlags / XdndFinishedAction properties. */
1088 VBClLogInfo("Target window %#x ('%s') has accepted the data\n", wndTarget, pszWndTgtName);
1089
1090 RTStrFree(pszWndTgtName);
1091
1092 reset();
1093 }
1094 else
1095 {
1096 LogFlowThisFunc(("Unhandled client message '%s'\n", xAtomToString(e.xclient.message_type).c_str()));
1097 rc = VERR_NOT_SUPPORTED;
1098 }
1099
1100 break;
1101 }
1102
1103 case Unknown: /* Mode not set (yet). */
1104 RT_FALL_THROUGH();
1105 case GH:
1106 {
1107 /*
1108 * This message marks the beginning of a new drag and drop
1109 * operation on the guest.
1110 */
1111 if (e.xclient.message_type == xAtom(XA_XdndEnter))
1112 {
1113 /*
1114 * Get the window which currently has the XA_XdndSelection
1115 * bit set.
1116 */
1117 Window wndSel = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
1118 char *pszWndSelName = wndX11GetNameA(wndSel);
1119 AssertPtrBreakStmt(pszWndSelName, VERR_NO_MEMORY);
1120
1121 mouseButtonSet(m_wndProxy.hWnd, -1, -1, 1, true /* fPress */);
1122
1123 /*
1124 * Update our state and the window handle to process.
1125 */
1126 rc = RTCritSectEnter(&m_dataCS);
1127 if (RT_SUCCESS(rc))
1128 {
1129 uint8_t const uXdndVer = (uint8_t)e.xclient.data.l[XdndEnterFlags] >> XdndEnterVersionRShift;
1130
1131 VBClLogInfo("Entered new source window %#x ('%s'), supports Xdnd version %u\n", wndSel, pszWndSelName, uXdndVer);
1132#ifdef DEBUG
1133 XWindowAttributes xwa;
1134 XGetWindowAttributes(m_pDisplay, m_wndCur, &xwa);
1135 LogFlowThisFunc(("wndCur=%#x, x=%d, y=%d, width=%d, height=%d\n", m_wndCur, xwa.x, xwa.y, xwa.width, xwa.height));
1136#endif
1137 /*
1138 * Retrieve supported formats.
1139 */
1140
1141 /* Check if the MIME types are in the message itself or if we need
1142 * to fetch the XdndTypeList property from the window. */
1143 bool fMoreTypes = e.xclient.data.l[XdndEnterFlags] & XdndEnterMoreTypesFlag;
1144 if (!fMoreTypes)
1145 {
1146 /* Only up to 3 format types supported. */
1147 /* Start with index 2 (first item). */
1148 for (int i = 2; i < 5; i++)
1149 {
1150 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(e.xclient.data.l[i]).c_str()));
1151 m_lstAtomFormats.append(e.xclient.data.l[i]);
1152 }
1153 }
1154 else
1155 {
1156 /* More than 3 format types supported. */
1157 rc = wndXDnDGetFormatList(wndSel, m_lstAtomFormats);
1158 }
1159
1160 if (RT_FAILURE(rc))
1161 {
1162 VBClLogError("Error retrieving supported formats, rc=%Rrc\n", rc);
1163 break;
1164 }
1165
1166 /*
1167 * Retrieve supported actions.
1168 */
1169 if (uXdndVer >= 2) /* More than one action allowed since protocol version 2. */
1170 {
1171 rc = wndXDnDGetActionList(wndSel, m_lstAtomActions);
1172 }
1173 else /* Only "copy" action allowed on legacy applications. */
1174 m_lstAtomActions.append(XA_XdndActionCopy);
1175
1176 if (RT_FAILURE(rc))
1177 {
1178 VBClLogError("Error retrieving supported actions, rc=%Rrc\n", rc);
1179 break;
1180 }
1181
1182 VBClLogInfo("Source window %#x ('%s')\n", wndSel, pszWndSelName);
1183 VBClLogInfo(" - supports the formats ");
1184 for (size_t i = 0; i < m_lstAtomFormats.size(); i++)
1185 {
1186 if (i > 0)
1187 VBClLogInfo(", ");
1188 VBClLogInfo("%s", gX11->xAtomToString(m_lstAtomFormats[i]).c_str());
1189 }
1190 VBClLogInfo("\n");
1191 VBClLogInfo(" - supports the actions ");
1192 for (size_t i = 0; i < m_lstAtomActions.size(); i++)
1193 {
1194 if (i > 0)
1195 VBClLogInfo(", ");
1196 VBClLogInfo("%s", gX11->xAtomToString(m_lstAtomActions[i]).c_str());
1197 }
1198 VBClLogInfo("\n");
1199
1200 AssertBreakStmt(wndSel == (Window)e.xclient.data.l[XdndEnterWindow],
1201 rc = VERR_INVALID_PARAMETER); /* Source window. */
1202
1203 m_wndCur = wndSel;
1204 m_uXdndVer = uXdndVer;
1205 m_enmMode = GH;
1206 m_enmState = Dragging;
1207
1208 RTCritSectLeave(&m_dataCS);
1209 }
1210
1211 RTStrFree(pszWndSelName);
1212 }
1213 else if ( e.xclient.message_type == xAtom(XA_XdndPosition)
1214 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndPositionWindow]))
1215 {
1216 if (m_enmState != Dragging) /* Wrong mode? Bail out. */
1217 {
1218 reset();
1219 break;
1220 }
1221#ifdef LOG_ENABLED
1222 int32_t iPos = e.xclient.data.l[XdndPositionXY];
1223 Atom atmAction = m_uXdndVer >= 2 /* Actions other than "copy" or only supported since protocol version 2. */
1224 ? e.xclient.data.l[XdndPositionAction] : xAtom(XA_XdndActionCopy);
1225 LogFlowThisFunc(("XA_XdndPosition: wndProxy=%#x, wndCur=%#x, x=%RI32, y=%RI32, strAction=%s\n",
1226 m_wndProxy.hWnd, m_wndCur, RT_HIWORD(iPos), RT_LOWORD(iPos),
1227 xAtomToString(atmAction).c_str()));
1228#endif
1229 bool fAcceptDrop = true;
1230
1231 /* Reply with a XdndStatus message to tell the source whether
1232 * the data can be dropped or not. */
1233 XClientMessageEvent m;
1234 RT_ZERO(m);
1235 m.type = ClientMessage;
1236 m.display = m_pDisplay;
1237 m.window = e.xclient.data.l[XdndPositionWindow];
1238 m.message_type = xAtom(XA_XdndStatus);
1239 m.format = 32;
1240 m.data.l[XdndStatusWindow] = m_wndProxy.hWnd;
1241 m.data.l[XdndStatusFlags] = fAcceptDrop ? VBOX_XDND_STATUS_FLAG_ACCEPT : VBOX_XDND_STATUS_FLAG_NONE; /* Whether to accept the drop or not. */
1242
1243 /* We don't want any new XA_XdndPosition messages while being
1244 * in our proxy window. */
1245 m.data.l[XdndStatusNoMsgXY] = RT_MAKE_U32(m_wndProxy.iY, m_wndProxy.iX);
1246 m.data.l[XdndStatusNoMsgWH] = RT_MAKE_U32(m_wndProxy.iHeight, m_wndProxy.iWidth);
1247
1248 /** @todo Handle default action! */
1249 m.data.l[XdndStatusAction] = fAcceptDrop ? toAtomAction(VBOX_DND_ACTION_COPY) : None;
1250
1251 int xRc = XSendEvent(m_pDisplay, e.xclient.data.l[XdndPositionWindow],
1252 False /* Propagate */, NoEventMask, reinterpret_cast<XEvent *>(&m));
1253 if (xRc == 0)
1254 VBClLogError("Error sending position status event to current window %#x ('%s'): %s\n",
1255 m_wndCur, pszWndCurName, gX11->xErrorToString(xRc).c_str());
1256 }
1257 else if ( e.xclient.message_type == xAtom(XA_XdndLeave)
1258 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndLeaveWindow]))
1259 {
1260 LogFlowThisFunc(("XA_XdndLeave\n"));
1261 VBClLogInfo("Guest to host transfer canceled by the guest source window\n");
1262
1263 /* Start over. */
1264 reset();
1265 }
1266 else if ( e.xclient.message_type == xAtom(XA_XdndDrop)
1267 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndDropWindow]))
1268 {
1269 LogFlowThisFunc(("XA_XdndDrop\n"));
1270
1271 if (m_enmState != Dropped) /* Wrong mode? Bail out. */
1272 {
1273 /* Can occur when dragging from guest->host, but then back in to the guest again. */
1274 VBClLogInfo("Could not drop on own proxy window\n"); /* Not fatal. */
1275
1276 /* Let the source know. */
1277 rc = m_wndProxy.sendFinished(m_wndCur, VBOX_DND_ACTION_IGNORE);
1278
1279 /* Start over. */
1280 reset();
1281 break;
1282 }
1283
1284 m_eventQueueList.append(e);
1285 rc = RTSemEventSignal(m_eventQueueEvent);
1286 }
1287 else /* Unhandled event, abort. */
1288 {
1289 VBClLogInfo("Unhandled event from wnd=%#x, msg=%s\n", e.xclient.window, xAtomToString(e.xclient.message_type).c_str());
1290
1291 /* Let the source know. */
1292 rc = m_wndProxy.sendFinished(m_wndCur, VBOX_DND_ACTION_IGNORE);
1293
1294 /* Start over. */
1295 reset();
1296 }
1297 break;
1298 }
1299
1300 default:
1301 {
1302 AssertMsgFailed(("Drag and drop mode not implemented: %RU32\n", m_enmMode));
1303 rc = VERR_NOT_IMPLEMENTED;
1304 break;
1305 }
1306 }
1307
1308 RTStrFree(pszWndCurName);
1309
1310 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1311 return rc;
1312}
1313
1314int DragInstance::onX11MotionNotify(const XEvent &e)
1315{
1316 RT_NOREF1(e);
1317 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1318
1319 return VINF_SUCCESS;
1320}
1321
1322/**
1323 * Callback handler for being notified if some other window now
1324 * is the owner of the current selection.
1325 *
1326 * @return IPRT status code.
1327 * @param e X11 event to handle.
1328 *
1329 * @remark
1330 */
1331int DragInstance::onX11SelectionClear(const XEvent &e)
1332{
1333 RT_NOREF1(e);
1334 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1335
1336 return VINF_SUCCESS;
1337}
1338
1339/**
1340 * Callback handler for a XDnD selection notify from a window. This is needed
1341 * to let the us know if a certain window has drag'n drop data to share with us,
1342 * e.g. our proxy window.
1343 *
1344 * @return IPRT status code.
1345 * @param e X11 event to handle.
1346 */
1347int DragInstance::onX11SelectionNotify(const XEvent &e)
1348{
1349 AssertReturn(e.type == SelectionNotify, VERR_INVALID_PARAMETER);
1350
1351 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1352
1353 int rc;
1354
1355 switch (m_enmMode)
1356 {
1357 case GH:
1358 {
1359 if (m_enmState == Dropped)
1360 {
1361 m_eventQueueList.append(e);
1362 rc = RTSemEventSignal(m_eventQueueEvent);
1363 }
1364 else
1365 rc = VERR_WRONG_ORDER;
1366 break;
1367 }
1368
1369 default:
1370 {
1371 LogFlowThisFunc(("Unhandled: wnd=%#x, msg=%s\n",
1372 e.xclient.data.l[0], xAtomToString(e.xclient.message_type).c_str()));
1373 rc = VERR_INVALID_STATE;
1374 break;
1375 }
1376 }
1377
1378 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1379 return rc;
1380}
1381
1382/**
1383 * Callback handler for a XDnD selection request from a window. This is needed
1384 * to retrieve the data required to complete the actual drag'n drop operation.
1385 *
1386 * @returns IPRT status code.
1387 * @param evReq X11 event to handle.
1388 */
1389int DragInstance::onX11SelectionRequest(const XEvent &evReq)
1390{
1391 AssertReturn(evReq.type == SelectionRequest, VERR_INVALID_PARAMETER);
1392
1393 const XSelectionRequestEvent *pEvReq = &evReq.xselectionrequest;
1394
1395 char *pszWndSrcName = wndX11GetNameA(pEvReq->owner);
1396 AssertPtrReturn(pszWndSrcName, VERR_INVALID_POINTER);
1397 char *pszWndTgtName = wndX11GetNameA(pEvReq->requestor);
1398 AssertPtrReturn(pszWndTgtName, VERR_INVALID_POINTER);
1399
1400 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1401 LogFlowThisFunc(("Event owner=%#x ('%s'), requestor=%#x ('%s'), selection=%s, target=%s, prop=%s, time=%u\n",
1402 pEvReq->owner, pszWndSrcName,
1403 pEvReq->requestor, pszWndTgtName,
1404 xAtomToString(pEvReq->selection).c_str(),
1405 xAtomToString(pEvReq->target).c_str(),
1406 xAtomToString(pEvReq->property).c_str(),
1407 pEvReq->time));
1408
1409 VBClLogInfo("Window '%s' is asking '%s' for '%s' / '%s'\n",
1410 pszWndTgtName, pszWndSrcName, xAtomToString(pEvReq->selection).c_str(), xAtomToString(pEvReq->property).c_str());
1411
1412 RTStrFree(pszWndSrcName);
1413 /* Note: pszWndTgtName will be free'd below. */
1414
1415 int rc;
1416
1417 switch (m_enmMode)
1418 {
1419 case HG:
1420 {
1421 rc = VINF_SUCCESS;
1422
1423 /*
1424 * Start by creating a refusal selection notify message.
1425 * That way we only need to care for the success case.
1426 */
1427
1428 XEvent evResp;
1429 RT_ZERO(evResp);
1430
1431 XSelectionEvent *pEvResp = &evResp.xselection;
1432
1433 pEvResp->type = SelectionNotify;
1434 pEvResp->display = pEvReq->display;
1435 pEvResp->requestor = pEvReq->requestor;
1436 pEvResp->selection = pEvReq->selection;
1437 pEvResp->target = pEvReq->target;
1438 pEvResp->property = None; /* "None" means refusal. */
1439 pEvResp->time = pEvReq->time;
1440
1441 if (g_cVerbosity)
1442 {
1443 VBClLogVerbose(1, "Supported formats by VBoxClient:\n");
1444 for (size_t i = 0; i < m_lstAtomFormats.size(); i++)
1445 VBClLogVerbose(1, "\t%s\n", xAtomToString(m_lstAtomFormats.at(i)).c_str());
1446 }
1447
1448 /* Is the requestor asking for the possible MIME types? */
1449 if (pEvReq->target == xAtom(XA_TARGETS))
1450 {
1451 VBClLogInfo("Target window %#x ('%s') asking for target list\n", pEvReq->requestor, pszWndTgtName);
1452
1453 /* If so, set the window property with the formats on the requestor
1454 * window. */
1455 rc = wndXDnDSetFormatList(pEvReq->requestor, pEvReq->property, m_lstAtomFormats);
1456 if (RT_SUCCESS(rc))
1457 pEvResp->property = pEvReq->property;
1458 }
1459 /* Is the requestor asking for a specific MIME type (we support)? */
1460 else if (m_lstAtomFormats.contains(pEvReq->target))
1461 {
1462 VBClLogInfo("Target window %#x ('%s') is asking for data as '%s'\n",
1463 pEvReq->requestor, pszWndTgtName, xAtomToString(pEvReq->target).c_str());
1464
1465#ifdef VBOX_WITH_DRAG_AND_DROP_PROMISES
1466# error "Implement me!"
1467#else
1468 /* Did we not drop our stuff to the guest yet? Bail out. */
1469 if (m_enmState != Dropped)
1470 {
1471 VBClLogError("Data not dropped by the host on the guest yet (client state %RU32, mode %RU32), refusing selection request by guest\n",
1472 m_enmState, m_enmMode);
1473 }
1474 /* Did we not store the requestor's initial selection request yet? Then do so now. */
1475 else
1476 {
1477#endif /* VBOX_WITH_DRAG_AND_DROP_PROMISES */
1478 /* Get the data format the requestor wants from us. */
1479 VBClLogInfo("Target window %#x ('%s') requested data from host as '%s', rc=%Rrc\n",
1480 pEvReq->requestor, pszWndTgtName, xAtomToString(pEvReq->target).c_str(), rc);
1481
1482 /* Make a copy of the MIME data to be passed back. The X server will be become
1483 * the new owner of that data, so no deletion needed. */
1484 /** @todo Do we need to do some more conversion here? XConvertSelection? */
1485 AssertMsgBreakStmt(m_pvSelReqData != NULL, ("Selection request data is NULL\n"), rc = VERR_INVALID_PARAMETER);
1486 AssertMsgBreakStmt(m_cbSelReqData > 0, ("Selection request data size is 0\n"), rc = VERR_INVALID_PARAMETER);
1487
1488 void const *pvData = RTMemDup(m_pvSelReqData, m_cbSelReqData);
1489 AssertMsgBreakStmt(pvData != NULL, ("Duplicating selection request failed\n"), rc = VERR_NO_MEMORY);
1490 uint32_t const cbData = m_cbSelReqData;
1491
1492 /* Always return the requested property. */
1493 evResp.xselection.property = pEvReq->property;
1494
1495 /* Note: Always seems to return BadRequest. Seems fine. */
1496 int xRc = XChangeProperty(pEvResp->display, pEvResp->requestor, pEvResp->property,
1497 pEvResp->target, 8, PropModeReplace,
1498 reinterpret_cast<const unsigned char*>(pvData), cbData);
1499
1500 LogFlowFunc(("Changing property '%s' (of type '%s') of window %#x ('%s'): %s\n",
1501 xAtomToString(pEvReq->property).c_str(),
1502 xAtomToString(pEvReq->target).c_str(),
1503 pEvReq->requestor, pszWndTgtName,
1504 gX11->xErrorToString(xRc).c_str()));
1505 RT_NOREF(xRc);
1506#ifndef VBOX_WITH_DRAG_AND_DROP_PROMISES
1507 }
1508#endif
1509 }
1510 /* Anything else. */
1511 else
1512 {
1513 VBClLogError("Refusing unknown command/format '%s' of wnd=%#x ('%s')\n",
1514 xAtomToString(pEvReq->target).c_str(), pEvReq->requestor, pszWndTgtName);
1515 rc = VERR_NOT_SUPPORTED;
1516 }
1517
1518 VBClLogVerbose(1, "Offering type '%s', property '%s' to window %#x ('%s') ...\n",
1519 xAtomToString(pEvReq->target).c_str(),
1520 xAtomToString(pEvReq->property).c_str(), pEvReq->requestor, pszWndTgtName);
1521
1522 int xRc = XSendEvent(pEvReq->display, pEvReq->requestor, True /* Propagate */, 0, &evResp);
1523 if (xRc == 0)
1524 VBClLogError("Error sending SelectionNotify(1) event to window %#x ('%s'): %s\n",
1525 pEvReq->requestor, pszWndTgtName, gX11->xErrorToString(xRc).c_str());
1526
1527 XFlush(pEvReq->display);
1528 break;
1529 }
1530
1531 default:
1532 rc = VERR_INVALID_STATE;
1533 break;
1534 }
1535
1536 RTStrFree(pszWndTgtName);
1537 pszWndTgtName = NULL;
1538
1539 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1540 return rc;
1541}
1542
1543/**
1544 * Handles X11 events, called by x11EventThread.
1545 *
1546 * @returns IPRT status code.
1547 * @param e X11 event to handle.
1548 */
1549int DragInstance::onX11Event(const XEvent &e)
1550{
1551 int rc;
1552
1553 LogFlowThisFunc(("X11 event, type=%d\n", e.type));
1554 switch (e.type)
1555 {
1556 /*
1557 * This can happen if a guest->host drag operation
1558 * goes back from the host to the guest. This is not what
1559 * we want and thus resetting everything.
1560 */
1561 case ButtonPress:
1562 RT_FALL_THROUGH();
1563 case ButtonRelease:
1564 {
1565 VBClLogInfo("Mouse button %s\n", e.type == ButtonPress ? "pressed" : "released");
1566
1567 reset();
1568
1569 rc = VINF_SUCCESS;
1570 break;
1571 }
1572
1573 case ClientMessage:
1574 rc = onX11ClientMessage(e);
1575 break;
1576
1577 case SelectionClear:
1578 rc = onX11SelectionClear(e);
1579 break;
1580
1581 case SelectionNotify:
1582 rc = onX11SelectionNotify(e);
1583 break;
1584
1585 case SelectionRequest:
1586 rc = onX11SelectionRequest(e);
1587 break;
1588
1589 case MotionNotify:
1590 rc = onX11MotionNotify(e);
1591 break;
1592
1593 default:
1594 rc = VERR_NOT_IMPLEMENTED;
1595 break;
1596 }
1597
1598 LogFlowThisFunc(("rc=%Rrc\n", rc));
1599 return rc;
1600}
1601
1602int DragInstance::waitForStatusChange(uint32_t enmState, RTMSINTERVAL uTimeoutMS /* = 30000 */)
1603{
1604 const uint64_t uiStart = RTTimeMilliTS();
1605 volatile uint32_t enmCurState;
1606
1607 int rc = VERR_TIMEOUT;
1608
1609 LogFlowFunc(("enmState=%RU32, uTimeoutMS=%RU32\n", enmState, uTimeoutMS));
1610
1611 do
1612 {
1613 enmCurState = ASMAtomicReadU32(&m_enmState);
1614 if (enmCurState == enmState)
1615 {
1616 rc = VINF_SUCCESS;
1617 break;
1618 }
1619 }
1620 while (RTTimeMilliTS() - uiStart < uTimeoutMS);
1621
1622 LogFlowThisFunc(("Returning %Rrc\n", rc));
1623 return rc;
1624}
1625
1626#ifdef VBOX_WITH_DRAG_AND_DROP_GH
1627/**
1628 * Waits for an X11 event of a specific type.
1629 *
1630 * @returns IPRT status code.
1631 * @param evX Reference where to store the event into.
1632 * @param iType Event type to wait for.
1633 * @param uTimeoutMS Timeout (in ms) to wait for the event.
1634 */
1635bool DragInstance::waitForX11Msg(XEvent &evX, int iType, RTMSINTERVAL uTimeoutMS /* = 100 */)
1636{
1637 LogFlowThisFunc(("iType=%d, uTimeoutMS=%RU32, cEventQueue=%zu\n", iType, uTimeoutMS, m_eventQueueList.size()));
1638
1639 bool fFound = false;
1640 uint64_t const tsStartMs = RTTimeMilliTS();
1641
1642 do
1643 {
1644 /* Check if there is a client message in the queue. */
1645 for (size_t i = 0; i < m_eventQueueList.size(); i++)
1646 {
1647 int rc2 = RTCritSectEnter(&m_eventQueueCS);
1648 if (RT_SUCCESS(rc2))
1649 {
1650 XEvent e = m_eventQueueList.at(i).m_Event;
1651
1652 fFound = e.type == iType;
1653 if (fFound)
1654 {
1655 m_eventQueueList.removeAt(i);
1656 evX = e;
1657 }
1658
1659 rc2 = RTCritSectLeave(&m_eventQueueCS);
1660 AssertRC(rc2);
1661
1662 if (fFound)
1663 break;
1664 }
1665 }
1666
1667 if (fFound)
1668 break;
1669
1670 int rc2 = RTSemEventWait(m_eventQueueEvent, 25 /* ms */);
1671 if ( RT_FAILURE(rc2)
1672 && rc2 != VERR_TIMEOUT)
1673 {
1674 LogFlowFunc(("Waiting failed with rc=%Rrc\n", rc2));
1675 break;
1676 }
1677 }
1678 while (RTTimeMilliTS() - tsStartMs < uTimeoutMS);
1679
1680 LogFlowThisFunc(("Returning fFound=%RTbool, msRuntime=%RU64\n", fFound, RTTimeMilliTS() - tsStartMs));
1681 return fFound;
1682}
1683
1684/**
1685 * Waits for an X11 client message of a specific type.
1686 *
1687 * @returns IPRT status code.
1688 * @param evMsg Reference where to store the event into.
1689 * @param aType Event type to wait for.
1690 * @param uTimeoutMS Timeout (in ms) to wait for the event.
1691 */
1692bool DragInstance::waitForX11ClientMsg(XClientMessageEvent &evMsg, Atom aType,
1693 RTMSINTERVAL uTimeoutMS /* = 100 */)
1694{
1695 LogFlowThisFunc(("aType=%s, uTimeoutMS=%RU32, cEventQueue=%zu\n",
1696 xAtomToString(aType).c_str(), uTimeoutMS, m_eventQueueList.size()));
1697
1698 bool fFound = false;
1699 const uint64_t uiStart = RTTimeMilliTS();
1700 do
1701 {
1702 /* Check if there is a client message in the queue. */
1703 for (size_t i = 0; i < m_eventQueueList.size(); i++)
1704 {
1705 int rc2 = RTCritSectEnter(&m_eventQueueCS);
1706 if (RT_SUCCESS(rc2))
1707 {
1708 XEvent e = m_eventQueueList.at(i).m_Event;
1709 if ( e.type == ClientMessage
1710 && e.xclient.message_type == aType)
1711 {
1712 m_eventQueueList.removeAt(i);
1713 evMsg = e.xclient;
1714
1715 fFound = true;
1716 }
1717
1718 if (e.type == ClientMessage)
1719 {
1720 LogFlowThisFunc(("Client message: Type=%ld (%s)\n",
1721 e.xclient.message_type, xAtomToString(e.xclient.message_type).c_str()));
1722 }
1723 else
1724 LogFlowThisFunc(("X message: Type=%d\n", e.type));
1725
1726 rc2 = RTCritSectLeave(&m_eventQueueCS);
1727 AssertRC(rc2);
1728
1729 if (fFound)
1730 break;
1731 }
1732 }
1733
1734 if (fFound)
1735 break;
1736
1737 int rc2 = RTSemEventWait(m_eventQueueEvent, 25 /* ms */);
1738 if ( RT_FAILURE(rc2)
1739 && rc2 != VERR_TIMEOUT)
1740 {
1741 LogFlowFunc(("Waiting failed with rc=%Rrc\n", rc2));
1742 break;
1743 }
1744 }
1745 while (RTTimeMilliTS() - uiStart < uTimeoutMS);
1746
1747 LogFlowThisFunc(("Returning fFound=%RTbool, msRuntime=%RU64\n", fFound, RTTimeMilliTS() - uiStart));
1748 return fFound;
1749}
1750#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
1751
1752/*
1753 * Host -> Guest
1754 */
1755
1756/**
1757 * Host -> Guest: Event signalling that the host's (mouse) cursor just entered the VM's (guest's) display
1758 * area.
1759 *
1760 * @returns IPRT status code.
1761 * @param lstFormats List of supported formats from the host.
1762 * @param dndListActionsAllowed (ORed) List of supported actions from the host.
1763 */
1764int DragInstance::hgEnter(const RTCList<RTCString> &lstFormats, uint32_t dndListActionsAllowed)
1765{
1766 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1767
1768 if (m_enmMode != Unknown)
1769 return VERR_INVALID_STATE;
1770
1771 reset();
1772
1773#ifdef DEBUG
1774 LogFlowThisFunc(("dndListActionsAllowed=0x%x, lstFormats=%zu: ", dndListActionsAllowed, lstFormats.size()));
1775 for (size_t i = 0; i < lstFormats.size(); ++i)
1776 LogFlow(("'%s' ", lstFormats.at(i).c_str()));
1777 LogFlow(("\n"));
1778#endif
1779
1780 int rc;
1781
1782 do
1783 {
1784 /* Check if the VM session has changed and reconnect to the HGCM service if necessary. */
1785 rc = checkForSessionChange();
1786 AssertRCBreak(rc);
1787
1788 /* Append all actual (MIME) formats we support to the list.
1789 * These must come last, after the default Atoms above. */
1790 rc = appendFormatsToList(lstFormats, m_lstAtomFormats);
1791 AssertRCBreak(rc);
1792
1793 rc = wndXDnDSetFormatList(m_wndProxy.hWnd, xAtom(XA_XdndTypeList), m_lstAtomFormats);
1794 AssertRCBreak(rc);
1795
1796 /* Announce the possible actions. */
1797 VBoxDnDAtomList lstActions;
1798 rc = toAtomActions(dndListActionsAllowed, lstActions);
1799 AssertRCBreak(rc);
1800
1801 rc = wndXDnDSetActionList(m_wndProxy.hWnd, lstActions);
1802 AssertRCBreak(rc);
1803
1804 /* Set the DnD selection owner to our window. */
1805 /** @todo Don't use CurrentTime -- according to ICCCM section 2.1. */
1806 XSetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection), m_wndProxy.hWnd, CurrentTime);
1807
1808 if (g_cVerbosity)
1809 {
1810 RTCString strMsg("Enter: Host -> Guest\n\n");
1811 strMsg += RTCStringFmt("Allowed actions: %#x\n", dndListActionsAllowed);
1812 strMsg += "Formats:\n";
1813 for (size_t i = 0; i < lstActions.size(); i++)
1814 {
1815 if (i > 0)
1816 strMsg += "\n";
1817 strMsg += lstActions.at(i);
1818 }
1819
1820 VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER, strMsg.c_str());
1821 }
1822
1823 m_enmMode = HG;
1824 m_enmState = Dragging;
1825
1826 } while (0);
1827
1828 LogFlowFuncLeaveRC(rc);
1829 return rc;
1830}
1831
1832/**
1833 * Host -> Guest: Event signalling that the host's (mouse) cursor has left the VM's (guest's)
1834 * display area.
1835 */
1836int DragInstance::hgLeave(void)
1837{
1838 if (g_cVerbosity)
1839 VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER, "Leave: Host -> Guest");
1840
1841 if (m_enmMode == HG) /* Only reset if in the right operation mode. */
1842 reset();
1843
1844 return VINF_SUCCESS;
1845}
1846
1847/**
1848 * Host -> Guest: Event signalling that the host's (mouse) cursor has been moved within the VM's
1849 * (guest's) display area.
1850 *
1851 * @returns IPRT status code.
1852 * @param uPosX Relative X position within the guest's display area.
1853 * @param uPosY Relative Y position within the guest's display area.
1854 * @param dndActionDefault Default action the host wants to perform on the guest
1855 * as soon as the operation successfully finishes.
1856 */
1857int DragInstance::hgMove(uint32_t uPosX, uint32_t uPosY, VBOXDNDACTION dndActionDefault)
1858{
1859 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1860 LogFlowThisFunc(("uPosX=%RU32, uPosY=%RU32, dndActionDefault=0x%x\n", uPosX, uPosY, dndActionDefault));
1861
1862 if ( m_enmMode != HG
1863 || m_enmState != Dragging)
1864 {
1865 return VERR_INVALID_STATE;
1866 }
1867
1868 int rc = VINF_SUCCESS;
1869 int xRc = Success;
1870
1871 /* Move the mouse cursor within the guest. */
1872 mouseCursorMove(uPosX, uPosY);
1873
1874 /* Search for the application window below the cursor. */
1875 Window wndBelowCursor = gX11->applicationWindowBelowCursor(m_wndRoot);
1876 char *pszWndBelowCursorName = wndX11GetNameA(wndBelowCursor);
1877 AssertPtrReturn(pszWndBelowCursorName, VERR_NO_MEMORY);
1878
1879 uint8_t uBelowCursorXdndVer = 0; /* 0 means the current window is _not_ XdndAware. */
1880
1881 if (wndBelowCursor != None)
1882 {
1883 /* Temp stuff for the XGetWindowProperty call. */
1884 Atom atmTmp;
1885 int fmt;
1886 unsigned long cItems, cbRemaining;
1887 unsigned char *pcData = NULL;
1888
1889 /* Query the XdndAware property from the window. We are interested in
1890 * the version and if it is XdndAware at all. */
1891 xRc = XGetWindowProperty(m_pDisplay, wndBelowCursor, xAtom(XA_XdndAware),
1892 0, 2, False, AnyPropertyType,
1893 &atmTmp, &fmt, &cItems, &cbRemaining, &pcData);
1894 if (xRc != Success)
1895 {
1896 VBClLogError("Error getting properties of cursor window=%#x: %s\n", wndBelowCursor, gX11->xErrorToString(xRc).c_str());
1897 }
1898 else
1899 {
1900 if (pcData == NULL || fmt != 32 || cItems != 1)
1901 {
1902 /** @todo Do we need to deal with this? */
1903 VBClLogError("Wrong window properties for window %#x: pcData=%#x, iFmt=%d, cItems=%ul\n",
1904 wndBelowCursor, pcData, fmt, cItems);
1905 }
1906 else
1907 {
1908 /* Get the current window's Xdnd version. */
1909 uBelowCursorXdndVer = (uint8_t)reinterpret_cast<long *>(pcData)[0];
1910 }
1911
1912 XFree(pcData);
1913 }
1914 }
1915
1916 char *pszWndCurName = wndX11GetNameA(m_wndCur);
1917 AssertPtrReturn(pszWndCurName, VERR_NO_MEMORY);
1918
1919 LogFlowThisFunc(("wndCursor=%x ('%s', Xdnd version %u), wndCur=%x ('%s', Xdnd version %u)\n",
1920 wndBelowCursor, pszWndBelowCursorName, uBelowCursorXdndVer, m_wndCur, pszWndCurName, m_uXdndVer));
1921
1922 if ( wndBelowCursor != m_wndCur
1923 && m_uXdndVer)
1924 {
1925 VBClLogInfo("Left old window %#x ('%s'), supported Xdnd version %u\n", m_wndCur, pszWndCurName, m_uXdndVer);
1926
1927 /* We left the current XdndAware window. Announce this to the current indow. */
1928 XClientMessageEvent m;
1929 RT_ZERO(m);
1930 m.type = ClientMessage;
1931 m.display = m_pDisplay;
1932 m.window = m_wndCur;
1933 m.message_type = xAtom(XA_XdndLeave);
1934 m.format = 32;
1935 m.data.l[XdndLeaveWindow] = m_wndProxy.hWnd;
1936
1937 xRc = XSendEvent(m_pDisplay, m_wndCur, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
1938 if (xRc == 0)
1939 VBClLogError("Error sending leave event to old window %#x: %s\n", m_wndCur, gX11->xErrorToString(xRc).c_str());
1940
1941 /* Reset our current window. */
1942 m_wndCur = 0;
1943 m_uXdndVer = 0;
1944 }
1945
1946 /*
1947 * Do we have a new Xdnd-aware window which now is under the cursor?
1948 */
1949 if ( wndBelowCursor != m_wndCur
1950 && uBelowCursorXdndVer)
1951 {
1952 VBClLogInfo("Entered new window %#x ('%s'), supports Xdnd version=%u\n",
1953 wndBelowCursor, pszWndBelowCursorName, uBelowCursorXdndVer);
1954
1955 /*
1956 * We enter a new window. Announce the XdndEnter event to the new
1957 * window. The first three mime types are attached to the event (the
1958 * others could be requested by the XdndTypeList property from the
1959 * window itself).
1960 */
1961 XClientMessageEvent m;
1962 RT_ZERO(m);
1963 m.type = ClientMessage;
1964 m.display = m_pDisplay;
1965 m.window = wndBelowCursor;
1966 m.message_type = xAtom(XA_XdndEnter);
1967 m.format = 32;
1968 m.data.l[XdndEnterWindow] = m_wndProxy.hWnd;
1969 m.data.l[XdndEnterFlags] = RT_MAKE_U32_FROM_U8(
1970 /* Bit 0 is set if the source supports more than three data types. */
1971 m_lstAtomFormats.size() > 3 ? RT_BIT(0) : 0,
1972 /* Reserved for future use. */
1973 0, 0,
1974 /* Protocol version to use. */
1975 RT_MIN(VBOX_XDND_VERSION, uBelowCursorXdndVer));
1976 m.data.l[XdndEnterType1] = m_lstAtomFormats.value(0, None); /* First data type to use. */
1977 m.data.l[XdndEnterType2] = m_lstAtomFormats.value(1, None); /* Second data type to use. */
1978 m.data.l[XdndEnterType3] = m_lstAtomFormats.value(2, None); /* Third data type to use. */
1979
1980 xRc = XSendEvent(m_pDisplay, wndBelowCursor, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
1981 if (xRc == 0)
1982 VBClLogError("Error sending enter event to window %#x: %s\n", wndBelowCursor, gX11->xErrorToString(xRc).c_str());
1983 }
1984
1985 if (uBelowCursorXdndVer)
1986 {
1987 Assert(wndBelowCursor != None);
1988
1989 Atom atmAction = toAtomAction(dndActionDefault);
1990 LogFlowThisFunc(("strAction=%s\n", xAtomToString(atmAction).c_str()));
1991
1992 VBClLogInfo("Sent position event (%RU32 x %RU32) to window %#x ('%s') with actions '%s'\n",
1993 uPosX, uPosY, wndBelowCursor, pszWndBelowCursorName, xAtomToString(atmAction).c_str());
1994
1995 /*
1996 * Send a XdndPosition event with the proposed action to the guest.
1997 */
1998 XClientMessageEvent m;
1999 RT_ZERO(m);
2000 m.type = ClientMessage;
2001 m.display = m_pDisplay;
2002 m.window = wndBelowCursor;
2003 m.message_type = xAtom(XA_XdndPosition);
2004 m.format = 32;
2005 m.data.l[XdndPositionWindow] = m_wndProxy.hWnd; /* X window ID of source window. */
2006 m.data.l[XdndPositionFlags] = 0; /* Reserved, set to 0. */
2007 m.data.l[XdndPositionXY] = RT_MAKE_U32(uPosY, uPosX); /* Cursor coordinates relative to the root window. */
2008 m.data.l[XdndPositionTimeStamp] = CurrentTime; /* Timestamp for retrieving data. */
2009 m.data.l[XdndPositionAction] = atmAction; /* Actions requested by the user. */
2010
2011 xRc = XSendEvent(m_pDisplay, wndBelowCursor, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
2012 if (xRc == 0)
2013 VBClLogError("Error sending position event to current window %#x: %s\n", wndBelowCursor, gX11->xErrorToString(xRc).c_str());
2014 }
2015
2016 if (uBelowCursorXdndVer == 0)
2017 {
2018 /* No window to process, so send a ignore ack event to the host. */
2019 rc = VbglR3DnDHGSendAckOp(&m_dndCtx, VBOX_DND_ACTION_IGNORE);
2020 }
2021 else
2022 {
2023 Assert(wndBelowCursor != None);
2024
2025 m_wndCur = wndBelowCursor;
2026 m_uXdndVer = uBelowCursorXdndVer;
2027 }
2028
2029 RTStrFree(pszWndBelowCursorName);
2030 RTStrFree(pszWndCurName);
2031
2032 LogFlowFuncLeaveRC(rc);
2033 return rc;
2034}
2035
2036/**
2037 * Host -> Guest: Event signalling that the host has dropped the data over the VM (guest) window.
2038 *
2039 * @returns IPRT status code.
2040 * @param uPosX Relative X position within the guest's display area.
2041 * @param uPosY Relative Y position within the guest's display area.
2042 * @param dndActionDefault Default action the host wants to perform on the guest
2043 * as soon as the operation successfully finishes.
2044 */
2045int DragInstance::hgDrop(uint32_t uPosX, uint32_t uPosY, VBOXDNDACTION dndActionDefault)
2046{
2047 RT_NOREF3(uPosX, uPosY, dndActionDefault);
2048 LogFlowThisFunc(("wndCur=%RU32, wndProxy=%RU32, mode=%RU32, state=%RU32\n", m_wndCur, m_wndProxy.hWnd, m_enmMode, m_enmState));
2049 LogFlowThisFunc(("uPosX=%RU32, uPosY=%RU32, dndActionDefault=0x%x\n", uPosX, uPosY, dndActionDefault));
2050
2051 if ( m_enmMode != HG
2052 || m_enmState != Dragging)
2053 {
2054 return VERR_INVALID_STATE;
2055 }
2056
2057 /* Set the state accordingly. */
2058 m_enmState = Dropped;
2059
2060 /*
2061 * Ask the host to send the raw data, as we don't (yet) know which format
2062 * the guest exactly expects. As blocking in a SelectionRequest message turned
2063 * out to be very unreliable (e.g. with KDE apps) we request to start transferring
2064 * file/directory data (if any) here.
2065 */
2066 char szFormat[] = { "text/uri-list" };
2067
2068 int rc = VbglR3DnDHGSendReqData(&m_dndCtx, szFormat);
2069 VBClLogInfo("Drop event from host resulted in: %Rrc\n", rc);
2070
2071 if (g_cVerbosity)
2072 VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER, "Drop: Host -> Guest");
2073
2074 LogFlowFuncLeaveRC(rc);
2075 return rc;
2076}
2077
2078/**
2079 * Host -> Guest: Event signalling that the host has finished sending drag'n drop
2080 * data to the guest for further processing.
2081 *
2082 * @returns IPRT status code.
2083 * @param pMeta Pointer to meta data from host.
2084 */
2085int DragInstance::hgDataReceive(PVBGLR3GUESTDNDMETADATA pMeta)
2086{
2087 LogFlowThisFunc(("enmMode=%RU32, enmState=%RU32\n", m_enmMode, m_enmState));
2088 LogFlowThisFunc(("enmMetaType=%RU32\n", pMeta->enmType));
2089
2090 if ( m_enmMode != HG
2091 || m_enmState != Dropped)
2092 {
2093 return VERR_INVALID_STATE;
2094 }
2095
2096 void *pvData = NULL;
2097 size_t cbData = 0;
2098
2099 int rc = VINF_SUCCESS; /* Shut up GCC. */
2100
2101 switch (pMeta->enmType)
2102 {
2103 case VBGLR3GUESTDNDMETADATATYPE_RAW:
2104 {
2105 AssertBreakStmt(pMeta->u.Raw.pvMeta != NULL, rc = VERR_INVALID_POINTER);
2106 pvData = pMeta->u.Raw.pvMeta;
2107 AssertBreakStmt(pMeta->u.Raw.cbMeta, rc = VERR_INVALID_PARAMETER);
2108 cbData = pMeta->u.Raw.cbMeta;
2109
2110 rc = VINF_SUCCESS;
2111 break;
2112 }
2113
2114 case VBGLR3GUESTDNDMETADATATYPE_URI_LIST:
2115 {
2116 const char *pcszRootPath = DnDTransferListGetRootPathAbs(&pMeta->u.URI.Transfer);
2117 AssertPtrBreakStmt(pcszRootPath, VERR_INVALID_POINTER);
2118
2119 VBClLogInfo("Transfer list root directory is '%s'\n", pcszRootPath);
2120
2121 /* Note: Use the URI format here, as X' DnD spec says so. */
2122 rc = DnDTransferListGetRootsEx(&pMeta->u.URI.Transfer, DNDTRANSFERLISTFMT_URI, pcszRootPath,
2123 DND_PATH_SEPARATOR_STR, (char **)&pvData, &cbData);
2124 break;
2125 }
2126
2127 default:
2128 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
2129 break;
2130 }
2131
2132 if (RT_FAILURE(rc))
2133 return rc;
2134
2135 /*
2136 * At this point all data needed (including sent files/directories) should
2137 * be on the guest, so proceed working on communicating with the target window.
2138 */
2139 VBClLogInfo("Received %RU32 bytes of meta data from host\n", cbData);
2140
2141 /* Destroy any old data. */
2142 if (m_pvSelReqData)
2143 {
2144 Assert(m_cbSelReqData);
2145
2146 RTMemFree(m_pvSelReqData); /** @todo RTMemRealloc? */
2147 m_cbSelReqData = 0;
2148 }
2149
2150 /** @todo Handle incremental transfers. */
2151
2152 /* Make a copy of the data. This data later then will be used to fill into
2153 * the selection request. */
2154 if (cbData)
2155 {
2156 m_pvSelReqData = RTMemAlloc(cbData);
2157 if (!m_pvSelReqData)
2158 return VERR_NO_MEMORY;
2159
2160 memcpy(m_pvSelReqData, pvData, cbData);
2161 m_cbSelReqData = cbData;
2162 }
2163
2164 /*
2165 * Send a drop event to the current window (target).
2166 * This window in turn then will raise a SelectionRequest message to our proxy window,
2167 * which we will handle in our onX11SelectionRequest handler.
2168 *
2169 * The SelectionRequest will tell us in which format the target wants the data from the host.
2170 */
2171 XClientMessageEvent m;
2172 RT_ZERO(m);
2173 m.type = ClientMessage;
2174 m.display = m_pDisplay;
2175 m.window = m_wndCur;
2176 m.message_type = xAtom(XA_XdndDrop);
2177 m.format = 32;
2178 m.data.l[XdndDropWindow] = m_wndProxy.hWnd; /* Source window. */
2179 m.data.l[XdndDropFlags] = 0; /* Reserved for future use. */
2180 m.data.l[XdndDropTimeStamp] = CurrentTime; /* Our DnD data does not rely on any timing, so just use the current time. */
2181
2182 int xRc = XSendEvent(m_pDisplay, m_wndCur, False /* Propagate */, NoEventMask, reinterpret_cast<XEvent*>(&m));
2183 if (xRc == 0)
2184 VBClLogError("Error sending XA_XdndDrop event to window=%#x: %s\n", m_wndCur, gX11->xErrorToString(xRc).c_str());
2185 XFlush(m_pDisplay);
2186
2187 LogFlowFuncLeaveRC(rc);
2188 return rc;
2189}
2190
2191/**
2192 * Checks if the VM session has changed (can happen when restoring the VM from a saved state)
2193 * and do a reconnect to the DnD HGCM service.
2194 *
2195 * @returns IPRT status code.
2196 */
2197int DragInstance::checkForSessionChange(void)
2198{
2199 uint64_t uSessionID;
2200 int rc = VbglR3GetSessionId(&uSessionID);
2201 if ( RT_SUCCESS(rc)
2202 && uSessionID != m_dndCtx.uSessionID)
2203 {
2204 LogFlowThisFunc(("VM session has changed to %RU64\n", uSessionID));
2205
2206 rc = VbglR3DnDDisconnect(&m_dndCtx);
2207 AssertRC(rc);
2208
2209 rc = VbglR3DnDConnect(&m_dndCtx);
2210 AssertRC(rc);
2211 }
2212
2213 LogFlowFuncLeaveRC(rc);
2214 return rc;
2215}
2216
2217#ifdef VBOX_WITH_DRAG_AND_DROP_GH
2218/**
2219 * Guest -> Host: Event signalling that the host is asking whether there is a pending
2220 * drag event on the guest (to the host).
2221 *
2222 * @returns IPRT status code.
2223 */
2224int DragInstance::ghIsDnDPending(void)
2225{
2226 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
2227
2228 int rc;
2229
2230 RTCString strFormats = "\r\n"; /** @todo If empty, IOCTL fails with VERR_ACCESS_DENIED. */
2231 VBOXDNDACTION dndActionDefault = VBOX_DND_ACTION_IGNORE;
2232 VBOXDNDACTIONLIST dndActionList = VBOX_DND_ACTION_IGNORE;
2233
2234 /* Currently in wrong mode? Bail out. */
2235 if (m_enmMode == HG)
2236 {
2237 rc = VERR_INVALID_STATE;
2238 }
2239 /* Message already processed successfully? */
2240 else if ( m_enmMode == GH
2241 && ( m_enmState == Dragging
2242 || m_enmState == Dropped)
2243 )
2244 {
2245 /* No need to query for the source window again. */
2246 rc = VINF_SUCCESS;
2247 }
2248 else
2249 {
2250 /* Check if the VM session has changed and reconnect to the HGCM service if necessary. */
2251 rc = checkForSessionChange();
2252
2253 /* Determine the current window which currently has the XdndSelection set. */
2254 Window wndSel = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
2255 LogFlowThisFunc(("wndSel=%#x, wndProxy=%#x, wndCur=%#x\n", wndSel, m_wndProxy.hWnd, m_wndCur));
2256
2257 /* Is this another window which has a Xdnd selection and not our proxy window? */
2258 if ( RT_SUCCESS(rc)
2259 && wndSel
2260 && wndSel != m_wndCur)
2261 {
2262 char *pszWndSelName = wndX11GetNameA(wndSel);
2263 AssertPtrReturn(pszWndSelName, VERR_NO_MEMORY);
2264 VBClLogInfo("New guest source window %#x ('%s')\n", wndSel, pszWndSelName);
2265
2266 /* Start over. */
2267 reset();
2268
2269 /* Map the window on the current cursor position, which should provoke
2270 * an XdndEnter event. */
2271 rc = proxyWinShow();
2272 if (RT_SUCCESS(rc))
2273 {
2274 rc = mouseCursorFakeMove();
2275 if (RT_SUCCESS(rc))
2276 {
2277 bool fWaitFailed = false; /* Waiting for status changed failed? */
2278
2279 /* Wait until we're in "Dragging" state. */
2280 rc = waitForStatusChange(Dragging, 100 /* 100ms timeout */);
2281
2282 /*
2283 * Note: Don't wait too long here, as this mostly will make
2284 * the drag and drop experience on the host being laggy
2285 * and unresponsive.
2286 *
2287 * Instead, let the host query multiple times with 100ms
2288 * timeout each (see above) and only report an error if
2289 * the overall querying time has been exceeded.<
2290 */
2291 if (RT_SUCCESS(rc))
2292 {
2293 m_enmMode = GH;
2294 }
2295 else if (rc == VERR_TIMEOUT)
2296 {
2297 /** @todo Make m_cFailedPendingAttempts configurable. For slower window managers? */
2298 if (m_cFailedPendingAttempts++ > 50) /* Tolerate up to 5s total (100ms for each slot). */
2299 fWaitFailed = true;
2300 else
2301 rc = VINF_SUCCESS;
2302 }
2303 else if (RT_FAILURE(rc))
2304 fWaitFailed = true;
2305
2306 if (fWaitFailed)
2307 {
2308 VBClLogError("Error mapping proxy window to guest source window %#x ('%s'), rc=%Rrc\n",
2309 wndSel, pszWndSelName, rc);
2310
2311 /* Reset the counter in any case. */
2312 m_cFailedPendingAttempts = 0;
2313 }
2314 }
2315 }
2316
2317 RTStrFree(pszWndSelName);
2318 }
2319 else
2320 VBClLogInfo("No guest source window\n");
2321 }
2322
2323 /*
2324 * Acknowledge to the host in any case, regardless
2325 * if something failed here or not. Be responsive.
2326 */
2327
2328 int rc2 = RTCritSectEnter(&m_dataCS);
2329 if (RT_SUCCESS(rc2))
2330 {
2331 RTCString strFormatsCur = gX11->xAtomListToString(m_lstAtomFormats);
2332 if (!strFormatsCur.isEmpty())
2333 {
2334 strFormats = strFormatsCur;
2335 dndActionDefault = VBOX_DND_ACTION_COPY; /** @todo Handle default action! */
2336 dndActionList = VBOX_DND_ACTION_COPY; /** @todo Ditto. */
2337 dndActionList |= toHGCMActions(m_lstAtomActions);
2338 }
2339
2340 RTCritSectLeave(&m_dataCS);
2341 }
2342
2343 rc2 = VbglR3DnDGHSendAckPending(&m_dndCtx, dndActionDefault, dndActionList,
2344 strFormats.c_str(), strFormats.length() + 1 /* Include termination */);
2345 LogFlowThisFunc(("uClientID=%RU32, dndActionDefault=0x%x, dndActionList=0x%x, strFormats=%s, rc=%Rrc\n",
2346 m_dndCtx.uClientID, dndActionDefault, dndActionList, strFormats.c_str(), rc2));
2347 if (RT_FAILURE(rc2))
2348 {
2349 switch (rc2)
2350 {
2351 case VERR_ACCESS_DENIED:
2352 {
2353 rc = VBClShowNotify(VBOX_DND_SHOWNOTIFY_HEADER,
2354 "Drag and drop to the host either is not supported or disabled. "
2355 "Please enable Guest to Host or Bidirectional drag and drop mode "
2356 "or re-install the VirtualBox Guest Additions.");
2357 AssertRC(rc);
2358 break;
2359 }
2360
2361 default:
2362 break;
2363 }
2364
2365 VBClLogError("Error reporting pending drag and drop operation status to host: %Rrc\n", rc2);
2366 if (RT_SUCCESS(rc))
2367 rc = rc2;
2368 }
2369
2370 LogFlowFuncLeaveRC(rc);
2371 return rc;
2372}
2373
2374/**
2375 * Guest -> Host: Event signalling that the host has dropped the item(s) on the
2376 * host side.
2377 *
2378 * @returns IPRT status code.
2379 * @param strFormat Requested format to send to the host.
2380 * @param dndActionRequested Requested action to perform on the guest.
2381 */
2382int DragInstance::ghDropped(const RTCString &strFormat, VBOXDNDACTION dndActionRequested)
2383{
2384 LogFlowThisFunc(("mode=%RU32, state=%RU32, strFormat=%s, dndActionRequested=0x%x\n",
2385 m_enmMode, m_enmState, strFormat.c_str(), dndActionRequested));
2386
2387 /* Currently in wrong mode? Bail out. */
2388 if ( m_enmMode == Unknown
2389 || m_enmMode == HG)
2390 {
2391 return VERR_INVALID_STATE;
2392 }
2393
2394 if ( m_enmMode == GH
2395 && m_enmState != Dragging)
2396 {
2397 return VERR_INVALID_STATE;
2398 }
2399
2400 int rc = VINF_SUCCESS;
2401
2402 m_enmState = Dropped;
2403
2404#ifdef DEBUG
2405 XWindowAttributes xwa;
2406 XGetWindowAttributes(m_pDisplay, m_wndCur, &xwa);
2407 LogFlowThisFunc(("wndProxy=%RU32, wndCur=%RU32, x=%d, y=%d, width=%d, height=%d\n",
2408 m_wndProxy.hWnd, m_wndCur, xwa.x, xwa.y, xwa.width, xwa.height));
2409
2410 Window wndSelection = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
2411 LogFlowThisFunc(("wndSelection=%#x\n", wndSelection));
2412#endif
2413
2414 /* We send a fake mouse move event to the current window, cause
2415 * this should have the grab. */
2416 mouseCursorFakeMove();
2417
2418 /**
2419 * The fake button release event above should lead to a XdndDrop event from the
2420 * source window. Because of showing our proxy window, other Xdnd events can
2421 * occur before, e.g. a XdndPosition event. We are not interested
2422 * in those, so just try to get the right one.
2423 */
2424
2425 XClientMessageEvent evDnDDrop;
2426 bool fDrop = waitForX11ClientMsg(evDnDDrop, xAtom(XA_XdndDrop), 5 * 1000 /* 5s timeout */);
2427 if (fDrop)
2428 {
2429 LogFlowThisFunc(("XA_XdndDrop\n"));
2430
2431 /* Request to convert the selection in the specific format and
2432 * place it to our proxy window as property. */
2433 Assert(evDnDDrop.message_type == xAtom(XA_XdndDrop));
2434
2435 Window wndSource = evDnDDrop.data.l[XdndDropWindow]; /* Source window which has sent the message. */
2436 Assert(wndSource == m_wndCur);
2437
2438 Atom aFormat = gX11->stringToxAtom(strFormat.c_str());
2439
2440 Time tsDrop;
2441 if (m_uXdndVer >= 1)
2442 tsDrop = evDnDDrop.data.l[XdndDropTimeStamp];
2443 else
2444 tsDrop = CurrentTime;
2445
2446 XConvertSelection(m_pDisplay, xAtom(XA_XdndSelection), aFormat, xAtom(XA_XdndSelection),
2447 m_wndProxy.hWnd, tsDrop);
2448
2449 /* Wait for the selection notify event. */
2450 XEvent evSelNotify;
2451 RT_ZERO(evSelNotify);
2452 if (waitForX11Msg(evSelNotify, SelectionNotify, 5 * 1000 /* 5s timeout */))
2453 {
2454 bool fCancel = false;
2455
2456 /* Make some paranoid checks. */
2457 if ( evSelNotify.xselection.type == SelectionNotify
2458 && evSelNotify.xselection.display == m_pDisplay
2459 && evSelNotify.xselection.selection == xAtom(XA_XdndSelection)
2460 && evSelNotify.xselection.requestor == m_wndProxy.hWnd
2461 && evSelNotify.xselection.target == aFormat)
2462 {
2463 LogFlowThisFunc(("Selection notfiy (from wnd=%#x)\n", m_wndCur));
2464
2465 Atom aPropType;
2466 int iPropFormat;
2467 unsigned long cItems, cbRemaining;
2468 unsigned char *pcData = NULL;
2469 int xRc = XGetWindowProperty(m_pDisplay, m_wndProxy.hWnd,
2470 xAtom(XA_XdndSelection) /* Property */,
2471 0 /* Offset */,
2472 VBOX_MAX_XPROPERTIES /* Length of 32-bit multiples */,
2473 True /* Delete property? */,
2474 AnyPropertyType, /* Property type */
2475 &aPropType, &iPropFormat, &cItems, &cbRemaining, &pcData);
2476 if (xRc != Success)
2477 VBClLogError("Error getting XA_XdndSelection property of proxy window=%#x: %s\n",
2478 m_wndProxy.hWnd, gX11->xErrorToString(xRc).c_str());
2479
2480 LogFlowThisFunc(("strType=%s, iPropFormat=%d, cItems=%RU32, cbRemaining=%RU32\n",
2481 gX11->xAtomToString(aPropType).c_str(), iPropFormat, cItems, cbRemaining));
2482
2483 if ( aPropType != None
2484 && pcData != NULL
2485 && iPropFormat >= 8
2486 && cItems > 0
2487 && cbRemaining == 0)
2488 {
2489 size_t cbData = cItems * (iPropFormat / 8);
2490 LogFlowThisFunc(("cbData=%zu\n", cbData));
2491
2492 /* For whatever reason some of the string MIME types are not
2493 * zero terminated. Check that and correct it when necessary,
2494 * because the guest side wants this in any case. */
2495 if ( m_lstAllowedFormats.contains(strFormat)
2496 && pcData[cbData - 1] != '\0')
2497 {
2498 unsigned char *pvDataTmp = static_cast<unsigned char*>(RTMemAlloc(cbData + 1));
2499 if (pvDataTmp)
2500 {
2501 memcpy(pvDataTmp, pcData, cbData);
2502 pvDataTmp[cbData++] = '\0';
2503
2504 rc = VbglR3DnDGHSendData(&m_dndCtx, strFormat.c_str(), pvDataTmp, cbData);
2505 RTMemFree(pvDataTmp);
2506 }
2507 else
2508 rc = VERR_NO_MEMORY;
2509 }
2510 else
2511 {
2512 /* Send the raw data to the host. */
2513 rc = VbglR3DnDGHSendData(&m_dndCtx, strFormat.c_str(), pcData, cbData);
2514 LogFlowThisFunc(("Sent strFormat=%s, rc=%Rrc\n", strFormat.c_str(), rc));
2515 }
2516
2517 if (RT_SUCCESS(rc))
2518 {
2519 rc = m_wndProxy.sendFinished(wndSource, dndActionRequested);
2520 }
2521 else
2522 fCancel = true;
2523 }
2524 else
2525 {
2526 if (aPropType == xAtom(XA_INCR))
2527 {
2528 /** @todo Support incremental transfers. */
2529 AssertMsgFailed(("Incremental transfers are not supported yet\n"));
2530
2531 VBClLogError("Incremental transfers are not supported yet\n");
2532 rc = VERR_NOT_IMPLEMENTED;
2533 }
2534 else
2535 {
2536 VBClLogError("Not supported data type: %s\n", gX11->xAtomToString(aPropType).c_str());
2537 rc = VERR_NOT_SUPPORTED;
2538 }
2539
2540 fCancel = true;
2541 }
2542
2543 if (fCancel)
2544 {
2545 VBClLogInfo("Cancelling dropping to host\n");
2546
2547 /* Cancel the operation -- inform the source window by
2548 * sending a XdndFinished message so that the source can toss the required data. */
2549 rc = m_wndProxy.sendFinished(wndSource, VBOX_DND_ACTION_IGNORE);
2550 }
2551
2552 /* Cleanup. */
2553 if (pcData)
2554 XFree(pcData);
2555 }
2556 else
2557 rc = VERR_INVALID_PARAMETER;
2558 }
2559 else
2560 rc = VERR_TIMEOUT;
2561 }
2562 else
2563 rc = VERR_TIMEOUT;
2564
2565 /* Inform the host on error. */
2566 if (RT_FAILURE(rc))
2567 {
2568 int rc2 = VbglR3DnDGHSendError(&m_dndCtx, rc);
2569 LogFlowThisFunc(("Sending error %Rrc to host resulted in %Rrc\n", rc, rc2)); RT_NOREF(rc2);
2570 /* This is not fatal for us, just ignore. */
2571 }
2572
2573 /* At this point, we have either successfully transfered any data or not.
2574 * So reset our internal state because we are done here for the current (ongoing)
2575 * drag and drop operation. */
2576 reset();
2577
2578 LogFlowFuncLeaveRC(rc);
2579 return rc;
2580}
2581#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
2582
2583/*
2584 * Helpers
2585 */
2586
2587/**
2588 * Fakes moving the mouse cursor to provoke various drag and drop
2589 * events such as entering a target window or moving within a
2590 * source window.
2591 *
2592 * Not the most elegant and probably correct function, but does
2593 * the work for now.
2594 *
2595 * @returns IPRT status code.
2596 */
2597int DragInstance::mouseCursorFakeMove(void)
2598{
2599 int iScreenID = XDefaultScreen(m_pDisplay);
2600 /** @todo What about multiple screens? Test this! */
2601
2602 const int iScrX = XDisplayWidth(m_pDisplay, iScreenID);
2603 const int iScrY = XDisplayHeight(m_pDisplay, iScreenID);
2604
2605 int fx, fy, rx, ry;
2606 Window wndTemp, wndChild;
2607 int wx, wy; unsigned int mask;
2608 XQueryPointer(m_pDisplay, m_wndRoot, &wndTemp, &wndChild, &rx, &ry, &wx, &wy, &mask);
2609
2610 /*
2611 * Apply some simple clipping and change the position slightly.
2612 */
2613
2614 /* FakeX */
2615 if (rx == 0) fx = 1;
2616 else if (rx == iScrX) fx = iScrX - 1;
2617 else fx = rx + 1;
2618
2619 /* FakeY */
2620 if (ry == 0) fy = 1;
2621 else if (ry == iScrY) fy = iScrY - 1;
2622 else fy = ry + 1;
2623
2624 /*
2625 * Move the cursor to trigger the wanted events.
2626 */
2627 LogFlowThisFunc(("cursorRootX=%d, cursorRootY=%d\n", fx, fy));
2628 int rc = mouseCursorMove(fx, fy);
2629 if (RT_SUCCESS(rc))
2630 {
2631 /* Move the cursor back to its original position. */
2632 rc = mouseCursorMove(rx, ry);
2633 }
2634
2635 return rc;
2636}
2637
2638/**
2639 * Moves the mouse pointer to a specific position.
2640 *
2641 * @returns IPRT status code.
2642 * @param iPosX Absolute X coordinate.
2643 * @param iPosY Absolute Y coordinate.
2644 */
2645int DragInstance::mouseCursorMove(int iPosX, int iPosY)
2646{
2647 int const iScreenID = XDefaultScreen(m_pDisplay);
2648 /** @todo What about multiple screens? Test this! */
2649
2650 int const iScreenWidth = XDisplayWidth (m_pDisplay, iScreenID);
2651 int const iScreenHeight = XDisplayHeight(m_pDisplay, iScreenID);
2652
2653 iPosX = RT_CLAMP(iPosX, 0, iScreenWidth);
2654 iPosY = RT_CLAMP(iPosY, 0, iScreenHeight);
2655
2656 /* Same mouse position as before? No need to do anything. */
2657 if ( m_lastMouseX == iPosX
2658 && m_lastMouseY == iPosY)
2659 {
2660 return VINF_SUCCESS;
2661 }
2662
2663 LogFlowThisFunc(("iPosX=%d, iPosY=%d, m_wndRoot=%#x\n", iPosX, iPosY, m_wndRoot));
2664
2665 /* Move the guest pointer to the DnD position, so we can find the window
2666 * below that position. */
2667 int xRc = XWarpPointer(m_pDisplay, None, m_wndRoot, 0, 0, 0, 0, iPosX, iPosY);
2668 if (xRc == Success)
2669 {
2670 XFlush(m_pDisplay);
2671
2672 m_lastMouseX = iPosX;
2673 m_lastMouseY = iPosY;
2674 }
2675 else
2676 VBClLogError("Moving mouse cursor failed: %s", gX11->xErrorToString(xRc).c_str());
2677
2678 return VINF_SUCCESS;
2679}
2680
2681/**
2682 * Sends a mouse button event to a specific window.
2683 *
2684 * @param wndDest Window to send the mouse button event to.
2685 * @param rx X coordinate relative to the root window's origin.
2686 * @param ry Y coordinate relative to the root window's origin.
2687 * @param iButton Mouse button to press/release.
2688 * @param fPress Whether to press or release the mouse button.
2689 */
2690void DragInstance::mouseButtonSet(Window wndDest, int rx, int ry, int iButton, bool fPress)
2691{
2692 LogFlowThisFunc(("wndDest=%#x, rx=%d, ry=%d, iBtn=%d, fPress=%RTbool\n",
2693 wndDest, rx, ry, iButton, fPress));
2694
2695#ifdef VBOX_DND_WITH_XTEST
2696 /** @todo Make this check run only once. */
2697 int ev, er, ma, mi;
2698 if (XTestQueryExtension(m_pDisplay, &ev, &er, &ma, &mi))
2699 {
2700 LogFlowThisFunc(("XText extension available\n"));
2701
2702 int xRc = XTestFakeButtonEvent(m_pDisplay, 1, fPress ? True : False, CurrentTime);
2703 if (Rc == 0)
2704 VBClLogError("Error sending XTestFakeButtonEvent event: %s\n", gX11->xErrorToString(xRc).c_str());
2705 XFlush(m_pDisplay);
2706 }
2707 else
2708 {
2709#endif
2710 LogFlowThisFunc(("Note: XText extension not available or disabled\n"));
2711
2712 unsigned int mask = 0;
2713
2714 if ( rx == -1
2715 && ry == -1)
2716 {
2717 Window wndRoot, wndChild;
2718 int wx, wy;
2719 XQueryPointer(m_pDisplay, m_wndRoot, &wndRoot, &wndChild, &rx, &ry, &wx, &wy, &mask);
2720 LogFlowThisFunc(("Mouse pointer is at root x=%d, y=%d\n", rx, ry));
2721 }
2722
2723 XButtonEvent eBtn;
2724 RT_ZERO(eBtn);
2725
2726 eBtn.display = m_pDisplay;
2727 eBtn.root = m_wndRoot;
2728 eBtn.window = wndDest;
2729 eBtn.subwindow = None;
2730 eBtn.same_screen = True;
2731 eBtn.time = CurrentTime;
2732 eBtn.button = iButton;
2733 eBtn.state = mask | (iButton == 1 ? Button1MotionMask :
2734 iButton == 2 ? Button2MotionMask :
2735 iButton == 3 ? Button3MotionMask :
2736 iButton == 4 ? Button4MotionMask :
2737 iButton == 5 ? Button5MotionMask : 0);
2738 eBtn.type = fPress ? ButtonPress : ButtonRelease;
2739 eBtn.send_event = False;
2740 eBtn.x_root = rx;
2741 eBtn.y_root = ry;
2742
2743 XTranslateCoordinates(m_pDisplay, eBtn.root, eBtn.window, eBtn.x_root, eBtn.y_root, &eBtn.x, &eBtn.y, &eBtn.subwindow);
2744 LogFlowThisFunc(("state=0x%x, x=%d, y=%d\n", eBtn.state, eBtn.x, eBtn.y));
2745
2746 int xRc = XSendEvent(m_pDisplay, wndDest, True /* fPropagate */,
2747 ButtonPressMask,
2748 reinterpret_cast<XEvent*>(&eBtn));
2749 if (xRc == 0)
2750 VBClLogError("Error sending XButtonEvent event to window=%#x: %s\n", wndDest, gX11->xErrorToString(xRc).c_str());
2751
2752 XFlush(m_pDisplay);
2753
2754#ifdef VBOX_DND_WITH_XTEST
2755 }
2756#endif
2757}
2758
2759/**
2760 * Shows the (invisible) proxy window. The proxy window is needed for intercepting
2761 * drags from the host to the guest or from the guest to the host. It acts as a proxy
2762 * between the host and the actual (UI) element on the guest OS.
2763 *
2764 * To not make it miss any actions this window gets spawned across the entire guest
2765 * screen (think of an umbrella) to (hopefully) capture everything. A proxy window
2766 * which follows the cursor would be far too slow here.
2767 *
2768 * @returns IPRT status code.
2769 * @param piRootX X coordinate relative to the root window's origin. Optional.
2770 * @param piRootY Y coordinate relative to the root window's origin. Optional.
2771 */
2772int DragInstance::proxyWinShow(int *piRootX /* = NULL */, int *piRootY /* = NULL */) const
2773{
2774 /* piRootX is optional. */
2775 /* piRootY is optional. */
2776
2777 LogFlowThisFuncEnter();
2778
2779 int rc = VINF_SUCCESS;
2780
2781#if 0
2782# ifdef VBOX_DND_WITH_XTEST
2783 XTestGrabControl(m_pDisplay, False);
2784# endif
2785#endif
2786
2787 /* Get the mouse pointer position and determine if we're on the same screen as the root window
2788 * and return the current child window beneath our mouse pointer, if any. */
2789 int iRootX, iRootY;
2790 int iChildX, iChildY;
2791 unsigned int iMask;
2792 Window wndRoot, wndChild;
2793 Bool fInRootWnd = XQueryPointer(m_pDisplay, m_wndRoot, &wndRoot, &wndChild,
2794 &iRootX, &iRootY, &iChildX, &iChildY, &iMask);
2795
2796 LogFlowThisFunc(("fInRootWnd=%RTbool, wndRoot=%RU32, wndChild=%RU32, iRootX=%d, iRootY=%d\n",
2797 RT_BOOL(fInRootWnd), wndRoot, wndChild, iRootX, iRootY)); RT_NOREF(fInRootWnd);
2798
2799 if (piRootX)
2800 *piRootX = iRootX;
2801 if (piRootY)
2802 *piRootY = iRootY;
2803
2804 XSynchronize(m_pDisplay, True /* Enable sync */);
2805
2806 /* Bring our proxy window into foreground. */
2807 XMapWindow(m_pDisplay, m_wndProxy.hWnd);
2808 XRaiseWindow(m_pDisplay, m_wndProxy.hWnd);
2809
2810 /* Spawn our proxy window over the entire screen, making it an easy drop target for the host's cursor. */
2811 LogFlowThisFunc(("Proxy window x=%d, y=%d, width=%d, height=%d\n",
2812 m_wndProxy.iX, m_wndProxy.iY, m_wndProxy.iWidth, m_wndProxy.iHeight));
2813 XMoveResizeWindow(m_pDisplay, m_wndProxy.hWnd, m_wndProxy.iX, m_wndProxy.iY, m_wndProxy.iWidth, m_wndProxy.iHeight);
2814
2815 XFlush(m_pDisplay);
2816
2817 XSynchronize(m_pDisplay, False /* Disable sync */);
2818
2819#if 0
2820# ifdef VBOX_DND_WITH_XTEST
2821 XTestGrabControl(m_pDisplay, True);
2822# endif
2823#endif
2824
2825 LogFlowFuncLeaveRC(rc);
2826 return rc;
2827}
2828
2829/**
2830 * Hides the (invisible) proxy window.
2831 */
2832int DragInstance::proxyWinHide(void)
2833{
2834 LogFlowFuncEnter();
2835
2836 XUnmapWindow(m_pDisplay, m_wndProxy.hWnd);
2837 XFlush(m_pDisplay);
2838
2839 return VINF_SUCCESS; /** @todo Add error checking. */
2840}
2841
2842/**
2843 * Allocates the name (title) of an X window.
2844 * The returned pointer must be freed using RTStrFree().
2845 *
2846 * @returns Pointer to the allocated window name.
2847 * @retval NULL on allocation failure.
2848 * @retval "<No name>" if window name was not found / invalid window handle.
2849 * @param wndThis Window to retrieve name for.
2850 */
2851char *DragInstance::wndX11GetNameA(Window wndThis) const
2852{
2853 char *pszName = NULL;
2854
2855 XTextProperty propName;
2856 if ( wndThis != None
2857 && XGetWMName(m_pDisplay, wndThis, &propName))
2858 {
2859 if (propName.value)
2860 pszName = RTStrDup((char *)propName.value); /** @todo UTF8? */
2861 XFree(propName.value);
2862 }
2863
2864 if (!pszName) /* No window name found? */
2865 pszName = RTStrDup("<No name>");
2866
2867 return pszName;
2868}
2869
2870/**
2871 * Clear a window's supported/accepted actions list.
2872 *
2873 * @param wndThis Window to clear the list for.
2874 */
2875void DragInstance::wndXDnDClearActionList(Window wndThis) const
2876{
2877 XDeleteProperty(m_pDisplay, wndThis, xAtom(XA_XdndActionList));
2878}
2879
2880/**
2881 * Clear a window's supported/accepted formats list.
2882 *
2883 * @param wndThis Window to clear the list for.
2884 */
2885void DragInstance::wndXDnDClearFormatList(Window wndThis) const
2886{
2887 XDeleteProperty(m_pDisplay, wndThis, xAtom(XA_XdndTypeList));
2888}
2889
2890/**
2891 * Retrieves a window's supported/accepted XDnD actions.
2892 *
2893 * @returns IPRT status code.
2894 * @param wndThis Window to retrieve the XDnD actions for.
2895 * @param lstActions Reference to VBoxDnDAtomList to store the action into.
2896 */
2897int DragInstance::wndXDnDGetActionList(Window wndThis, VBoxDnDAtomList &lstActions) const
2898{
2899 Atom iActType = None;
2900 int iActFmt;
2901 unsigned long cItems, cbData;
2902 unsigned char *pcbData = NULL;
2903
2904 /* Fetch the possible list of actions, if this property is set. */
2905 int xRc = XGetWindowProperty(m_pDisplay, wndThis,
2906 xAtom(XA_XdndActionList),
2907 0, VBOX_MAX_XPROPERTIES,
2908 False, XA_ATOM, &iActType, &iActFmt, &cItems, &cbData, &pcbData);
2909 if (xRc != Success)
2910 {
2911 LogFlowThisFunc(("Error getting XA_XdndActionList atoms from window=%#x: %s\n",
2912 wndThis, gX11->xErrorToString(xRc).c_str()));
2913 return VERR_NOT_FOUND;
2914 }
2915
2916 LogFlowThisFunc(("wndThis=%#x, cItems=%RU32, pcbData=%p\n", wndThis, cItems, pcbData));
2917
2918 if (cItems > 0)
2919 {
2920 AssertPtr(pcbData);
2921 Atom *paData = reinterpret_cast<Atom *>(pcbData);
2922
2923 for (unsigned i = 0; i < RT_MIN(VBOX_MAX_XPROPERTIES, cItems); i++)
2924 {
2925 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(paData[i]).c_str()));
2926 lstActions.append(paData[i]);
2927 }
2928
2929 XFree(pcbData);
2930 }
2931
2932 return VINF_SUCCESS;
2933}
2934
2935/**
2936 * Retrieves a window's supported/accepted XDnD formats.
2937 *
2938 * @returns IPRT status code.
2939 * @param wndThis Window to retrieve the XDnD formats for.
2940 * @param lstTypes Reference to VBoxDnDAtomList to store the formats into.
2941 */
2942int DragInstance::wndXDnDGetFormatList(Window wndThis, VBoxDnDAtomList &lstTypes) const
2943{
2944 Atom iActType = None;
2945 int iActFmt;
2946 unsigned long cItems, cbData;
2947 unsigned char *pcbData = NULL;
2948
2949 int xRc = XGetWindowProperty(m_pDisplay, wndThis,
2950 xAtom(XA_XdndTypeList),
2951 0, VBOX_MAX_XPROPERTIES,
2952 False, XA_ATOM, &iActType, &iActFmt, &cItems, &cbData, &pcbData);
2953 if (xRc != Success)
2954 {
2955 LogFlowThisFunc(("Error getting XA_XdndTypeList atoms from window=%#x: %s\n",
2956 wndThis, gX11->xErrorToString(xRc).c_str()));
2957 return VERR_NOT_FOUND;
2958 }
2959
2960 LogFlowThisFunc(("wndThis=%#x, cItems=%RU32, pcbData=%p\n", wndThis, cItems, pcbData));
2961
2962 if (cItems > 0)
2963 {
2964 AssertPtr(pcbData);
2965 Atom *paData = reinterpret_cast<Atom *>(pcbData);
2966
2967 for (unsigned i = 0; i < RT_MIN(VBOX_MAX_XPROPERTIES, cItems); i++)
2968 {
2969 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(paData[i]).c_str()));
2970 lstTypes.append(paData[i]);
2971 }
2972
2973 XFree(pcbData);
2974 }
2975
2976 return VINF_SUCCESS;
2977}
2978
2979/**
2980 * Sets (replaces) a window's XDnD accepted/allowed actions.
2981 *
2982 * @returns IPRT status code.
2983 * @param wndThis Window to set the format list for.
2984 * @param lstActions Reference to list of XDnD actions to set.
2985 */
2986int DragInstance::wndXDnDSetActionList(Window wndThis, const VBoxDnDAtomList &lstActions) const
2987{
2988 if (lstActions.isEmpty())
2989 return VINF_SUCCESS;
2990
2991 XChangeProperty(m_pDisplay, wndThis,
2992 xAtom(XA_XdndActionList),
2993 XA_ATOM, 32, PropModeReplace,
2994 reinterpret_cast<const unsigned char*>(lstActions.raw()),
2995 lstActions.size());
2996
2997 return VINF_SUCCESS;
2998}
2999
3000/**
3001 * Sets (replaces) a window's XDnD accepted format list.
3002 *
3003 * @returns IPRT status code.
3004 * @param wndThis Window to set the format list for.
3005 * @param atmProp Property to set.
3006 * @param lstFormats Reference to list of XDnD formats to set.
3007 */
3008int DragInstance::wndXDnDSetFormatList(Window wndThis, Atom atmProp, const VBoxDnDAtomList &lstFormats) const
3009{
3010 if (lstFormats.isEmpty())
3011 return VERR_INVALID_PARAMETER;
3012
3013 /* Add the property with the property data to the window. */
3014 XChangeProperty(m_pDisplay, wndThis, atmProp,
3015 XA_ATOM, 32, PropModeReplace,
3016 reinterpret_cast<const unsigned char*>(lstFormats.raw()),
3017 lstFormats.size());
3018
3019 return VINF_SUCCESS;
3020}
3021
3022/**
3023 * Appends a RTCString list to VBoxDnDAtomList list.
3024 *
3025 * @returns IPRT status code.
3026 * @param lstFormats Reference to RTCString list to convert.
3027 * @param lstAtoms Reference to VBoxDnDAtomList list to store results in.
3028 */
3029int DragInstance::appendFormatsToList(const RTCList<RTCString> &lstFormats, VBoxDnDAtomList &lstAtoms) const
3030{
3031 for (size_t i = 0; i < lstFormats.size(); ++i)
3032 lstAtoms.append(XInternAtom(m_pDisplay, lstFormats.at(i).c_str(), False));
3033
3034 return VINF_SUCCESS;
3035}
3036
3037/**
3038 * Appends a raw-data string list to VBoxDnDAtomList list.
3039 *
3040 * @returns IPRT status code.
3041 * @param pvData Pointer to string data to convert.
3042 * @param cbData Size (in bytes) to convert.
3043 * @param lstAtoms Reference to VBoxDnDAtomList list to store results in.
3044 */
3045int DragInstance::appendDataToList(const void *pvData, uint32_t cbData, VBoxDnDAtomList &lstAtoms) const
3046{
3047 RT_NOREF1(lstAtoms);
3048 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
3049 AssertReturn(cbData, VERR_INVALID_PARAMETER);
3050
3051 const char *pszStr = (char *)pvData;
3052 uint32_t cbStr = cbData;
3053
3054 int rc = VINF_SUCCESS;
3055
3056 VBoxDnDAtomList lstAtom;
3057 while (cbStr)
3058 {
3059 size_t cbSize = RTStrNLen(pszStr, cbStr);
3060
3061 /* Create a copy with max N chars, so that we are on the save side,
3062 * even if the data isn't zero terminated. */
3063 char *pszTmp = RTStrDupN(pszStr, cbSize);
3064 if (!pszTmp)
3065 {
3066 rc = VERR_NO_MEMORY;
3067 break;
3068 }
3069
3070 lstAtom.append(XInternAtom(m_pDisplay, pszTmp, False));
3071 RTStrFree(pszTmp);
3072
3073 pszStr += cbSize + 1;
3074 cbStr -= cbSize + 1;
3075 }
3076
3077 return rc;
3078}
3079
3080/**
3081 * Converts a HGCM-based drag'n drop action to a Atom-based drag'n drop action.
3082 *
3083 * @returns Converted Atom-based drag'n drop action.
3084 * @param dndAction HGCM drag'n drop actions to convert.
3085 */
3086/* static */
3087Atom DragInstance::toAtomAction(VBOXDNDACTION dndAction)
3088{
3089 /* Ignore is None. */
3090 return (isDnDCopyAction(dndAction) ? xAtom(XA_XdndActionCopy) :
3091 isDnDMoveAction(dndAction) ? xAtom(XA_XdndActionMove) :
3092 isDnDLinkAction(dndAction) ? xAtom(XA_XdndActionLink) :
3093 None);
3094}
3095
3096/**
3097 * Converts HGCM-based drag'n drop actions to a VBoxDnDAtomList list.
3098 *
3099 * @returns IPRT status code.
3100 * @param dndActionList HGCM drag'n drop actions to convert.
3101 * @param lstAtoms Reference to VBoxDnDAtomList to store actions in.
3102 */
3103/* static */
3104int DragInstance::toAtomActions(VBOXDNDACTIONLIST dndActionList, VBoxDnDAtomList &lstAtoms)
3105{
3106 if (hasDnDCopyAction(dndActionList))
3107 lstAtoms.append(xAtom(XA_XdndActionCopy));
3108 if (hasDnDMoveAction(dndActionList))
3109 lstAtoms.append(xAtom(XA_XdndActionMove));
3110 if (hasDnDLinkAction(dndActionList))
3111 lstAtoms.append(xAtom(XA_XdndActionLink));
3112
3113 return VINF_SUCCESS;
3114}
3115
3116/**
3117 * Converts an Atom-based drag'n drop action to a HGCM drag'n drop action.
3118 *
3119 * @returns HGCM drag'n drop action.
3120 * @param atom Atom-based drag'n drop action to convert.
3121 */
3122/* static */
3123uint32_t DragInstance::toHGCMAction(Atom atom)
3124{
3125 uint32_t uAction = VBOX_DND_ACTION_IGNORE;
3126
3127 if (atom == xAtom(XA_XdndActionCopy))
3128 uAction = VBOX_DND_ACTION_COPY;
3129 else if (atom == xAtom(XA_XdndActionMove))
3130 uAction = VBOX_DND_ACTION_MOVE;
3131 else if (atom == xAtom(XA_XdndActionLink))
3132 uAction = VBOX_DND_ACTION_LINK;
3133
3134 return uAction;
3135}
3136
3137/**
3138 * Converts an VBoxDnDAtomList list to an HGCM action list.
3139 *
3140 * @returns ORed HGCM action list.
3141 * @param lstActions List of Atom-based actions to convert.
3142 */
3143/* static */
3144uint32_t DragInstance::toHGCMActions(const VBoxDnDAtomList &lstActions)
3145{
3146 uint32_t uActions = VBOX_DND_ACTION_IGNORE;
3147
3148 for (size_t i = 0; i < lstActions.size(); i++)
3149 uActions |= toHGCMAction(lstActions.at(i));
3150
3151 return uActions;
3152}
3153
3154/*********************************************************************************************************************************
3155 * VBoxDnDProxyWnd implementation. *
3156 ********************************************************************************************************************************/
3157
3158VBoxDnDProxyWnd::VBoxDnDProxyWnd(void)
3159 : pDisp(NULL)
3160 , hWnd(0)
3161 , iX(0)
3162 , iY(0)
3163 , iWidth(0)
3164 , iHeight(0)
3165{
3166
3167}
3168
3169VBoxDnDProxyWnd::~VBoxDnDProxyWnd(void)
3170{
3171 destroy();
3172}
3173
3174int VBoxDnDProxyWnd::init(Display *pDisplay)
3175{
3176 /** @todo What about multiple screens? Test this! */
3177 int iScreenID = XDefaultScreen(pDisplay);
3178
3179 iWidth = XDisplayWidth(pDisplay, iScreenID);
3180 iHeight = XDisplayHeight(pDisplay, iScreenID);
3181 pDisp = pDisplay;
3182
3183 return VINF_SUCCESS;
3184}
3185
3186void VBoxDnDProxyWnd::destroy(void)
3187{
3188
3189}
3190
3191int VBoxDnDProxyWnd::sendFinished(Window hWndSource, VBOXDNDACTION dndAction)
3192{
3193 /* Was the drop accepted by the host? That is, anything than ignoring. */
3194 bool fDropAccepted = dndAction > VBOX_DND_ACTION_IGNORE;
3195
3196 LogFlowFunc(("dndAction=0x%x\n", dndAction));
3197
3198 /* Confirm the result of the transfer to the target window. */
3199 XClientMessageEvent m;
3200 RT_ZERO(m);
3201 m.type = ClientMessage;
3202 m.display = pDisp;
3203 m.window = hWnd;
3204 m.message_type = xAtom(XA_XdndFinished);
3205 m.format = 32;
3206 m.data.l[XdndFinishedWindow] = hWnd; /* Target window. */
3207 m.data.l[XdndFinishedFlags] = fDropAccepted ? RT_BIT(0) : 0; /* Was the drop accepted? */
3208 m.data.l[XdndFinishedAction] = fDropAccepted ? DragInstance::toAtomAction(dndAction) : None; /* Action used on accept. */
3209
3210 int xRc = XSendEvent(pDisp, hWndSource, True, NoEventMask, reinterpret_cast<XEvent*>(&m));
3211 if (xRc == 0)
3212 {
3213 VBClLogError("Error sending finished event to source window=%#x: %s\n",
3214 hWndSource, gX11->xErrorToString(xRc).c_str());
3215
3216 return VERR_GENERAL_FAILURE; /** @todo Fudge. */
3217 }
3218
3219 return VINF_SUCCESS;
3220}
3221
3222/*********************************************************************************************************************************
3223 * DragAndDropService implementation. *
3224 ********************************************************************************************************************************/
3225
3226/** @copydoc VBCLSERVICE::pfnInit */
3227int DragAndDropService::init(void)
3228{
3229 LogFlowFuncEnter();
3230
3231 /* Connect to the x11 server. */
3232 m_pDisplay = XOpenDisplay(NULL);
3233 if (!m_pDisplay)
3234 {
3235 VBClLogFatalError("Unable to connect to X server -- running in a terminal session?\n");
3236 return VERR_NOT_FOUND;
3237 }
3238
3239 xHelpers *pHelpers = xHelpers::getInstance(m_pDisplay);
3240 if (!pHelpers)
3241 return VERR_NO_MEMORY;
3242
3243 int rc;
3244
3245 do
3246 {
3247 rc = RTSemEventCreate(&m_hEventSem);
3248 AssertRCBreak(rc);
3249
3250 rc = RTCritSectInit(&m_eventQueueCS);
3251 AssertRCBreak(rc);
3252
3253 rc = VbglR3DnDConnect(&m_dndCtx);
3254 AssertRCBreak(rc);
3255
3256 /* Event thread for events coming from the HGCM device. */
3257 rc = RTThreadCreate(&m_hHGCMThread, hgcmEventThread, this,
3258 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE, "dndHGCM");
3259 AssertRCBreak(rc);
3260
3261 rc = RTThreadUserWait(m_hHGCMThread, RT_MS_30SEC);
3262 AssertRCBreak(rc);
3263
3264 if (ASMAtomicReadBool(&m_fStop))
3265 break;
3266
3267 /* Event thread for events coming from the x11 system. */
3268 rc = RTThreadCreate(&m_hX11Thread, x11EventThread, this,
3269 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE, "dndX11");
3270 AssertRCBreak(rc);
3271
3272 rc = RTThreadUserWait(m_hX11Thread, RT_MS_30SEC);
3273 AssertRCBreak(rc);
3274
3275 if (ASMAtomicReadBool(&m_fStop))
3276 break;
3277
3278 } while (0);
3279
3280 if (m_fStop)
3281 rc = VERR_GENERAL_FAILURE; /** @todo Fudge! */
3282
3283 if (RT_FAILURE(rc))
3284 VBClLogError("Failed to initialize, rc=%Rrc\n", rc);
3285
3286 LogFlowFuncLeaveRC(rc);
3287 return rc;
3288}
3289
3290/** @copydoc VBCLSERVICE::pfnWorker */
3291int DragAndDropService::worker(bool volatile *pfShutdown)
3292{
3293 int rc;
3294 do
3295 {
3296 m_pCurDnD = new DragInstance(m_pDisplay, this);
3297 if (!m_pCurDnD)
3298 {
3299 rc = VERR_NO_MEMORY;
3300 break;
3301 }
3302
3303 /* Note: For multiple screen support in VBox it is not necessary to use
3304 * another screen number than zero. Maybe in the future it will become
3305 * necessary if VBox supports multiple X11 screens. */
3306 rc = m_pCurDnD->init(0 /* uScreenID */);
3307 /* Note: Can return VINF_PERMISSION_DENIED if HGCM host service is not available. */
3308 if (rc != VINF_SUCCESS)
3309 {
3310 if (RT_FAILURE(rc))
3311 VBClLogError("Unable to connect to drag and drop service, rc=%Rrc\n", rc);
3312 else if (rc == VINF_PERMISSION_DENIED) /* No error, DnD might be just disabled. */
3313 VBClLogInfo("Not available on host, terminating\n");
3314 break;
3315 }
3316
3317 /* Let the main thread know that it can continue spawning services. */
3318 RTThreadUserSignal(RTThreadSelf());
3319
3320 /* Enter the main event processing loop. */
3321 do
3322 {
3323 DNDEVENT e;
3324 RT_ZERO(e);
3325
3326 LogFlowFunc(("Waiting for new events ...\n"));
3327 rc = RTSemEventWait(m_hEventSem, RT_INDEFINITE_WAIT);
3328 if (RT_FAILURE(rc))
3329 break;
3330
3331 size_t cEvents = 0;
3332
3333 int rc2 = RTCritSectEnter(&m_eventQueueCS);
3334 if (RT_SUCCESS(rc2))
3335 {
3336 cEvents = m_eventQueue.size();
3337
3338 rc2 = RTCritSectLeave(&m_eventQueueCS);
3339 AssertRC(rc2);
3340 }
3341
3342 while (cEvents)
3343 {
3344 rc2 = RTCritSectEnter(&m_eventQueueCS);
3345 if (RT_SUCCESS(rc2))
3346 {
3347 if (m_eventQueue.isEmpty())
3348 {
3349 rc2 = RTCritSectLeave(&m_eventQueueCS);
3350 AssertRC(rc2);
3351 break;
3352 }
3353
3354 e = m_eventQueue.first();
3355 m_eventQueue.removeFirst();
3356
3357 rc2 = RTCritSectLeave(&m_eventQueueCS);
3358 AssertRC(rc2);
3359 }
3360
3361 if (e.enmType == DNDEVENT::DnDEventType_HGCM)
3362 {
3363 PVBGLR3DNDEVENT pVbglR3Event = e.hgcm;
3364 AssertPtrBreak(pVbglR3Event);
3365
3366 LogFlowThisFunc(("HGCM event enmType=%RU32\n", pVbglR3Event->enmType));
3367 switch (pVbglR3Event->enmType)
3368 {
3369 case VBGLR3DNDEVENTTYPE_HG_ENTER:
3370 {
3371 if (pVbglR3Event->u.HG_Enter.cbFormats)
3372 {
3373 RTCList<RTCString> lstFormats =
3374 RTCString(pVbglR3Event->u.HG_Enter.pszFormats, pVbglR3Event->u.HG_Enter.cbFormats - 1).split("\r\n");
3375 rc = m_pCurDnD->hgEnter(lstFormats, pVbglR3Event->u.HG_Enter.dndLstActionsAllowed);
3376 if (RT_FAILURE(rc))
3377 break;
3378 /* Enter is always followed by a move event. */
3379 }
3380 else
3381 {
3382 AssertMsgFailed(("cbFormats is 0\n"));
3383 rc = VERR_INVALID_PARAMETER;
3384 break;
3385 }
3386
3387 /* Note: After HOST_DND_FN_HG_EVT_ENTER there immediately is a move
3388 * event, so fall through is intentional here. */
3389 RT_FALL_THROUGH();
3390 }
3391
3392 case VBGLR3DNDEVENTTYPE_HG_MOVE:
3393 {
3394 rc = m_pCurDnD->hgMove(pVbglR3Event->u.HG_Move.uXpos, pVbglR3Event->u.HG_Move.uYpos,
3395 pVbglR3Event->u.HG_Move.dndActionDefault);
3396 break;
3397 }
3398
3399 case VBGLR3DNDEVENTTYPE_HG_LEAVE:
3400 {
3401 rc = m_pCurDnD->hgLeave();
3402 break;
3403 }
3404
3405 case VBGLR3DNDEVENTTYPE_HG_DROP:
3406 {
3407 rc = m_pCurDnD->hgDrop(pVbglR3Event->u.HG_Drop.uXpos, pVbglR3Event->u.HG_Drop.uYpos,
3408 pVbglR3Event->u.HG_Drop.dndActionDefault);
3409 break;
3410 }
3411
3412 /* Note: VbglR3DnDRecvNextMsg() will return HOST_DND_FN_HG_SND_DATA_HDR when
3413 * the host has finished copying over all the data to the guest.
3414 *
3415 * The actual data transfer (and message processing for it) will be done
3416 * internally by VbglR3DnDRecvNextMsg() to not duplicate any code for different
3417 * platforms.
3418 *
3419 * The data header now will contain all the (meta) data the guest needs in
3420 * order to complete the DnD operation. */
3421 case VBGLR3DNDEVENTTYPE_HG_RECEIVE:
3422 {
3423 rc = m_pCurDnD->hgDataReceive(&pVbglR3Event->u.HG_Received.Meta);
3424 break;
3425 }
3426
3427 case VBGLR3DNDEVENTTYPE_HG_CANCEL:
3428 {
3429 m_pCurDnD->reset(); /** @todo Test this! */
3430 break;
3431 }
3432
3433#ifdef VBOX_WITH_DRAG_AND_DROP_GH
3434 case VBGLR3DNDEVENTTYPE_GH_ERROR:
3435 {
3436 m_pCurDnD->reset();
3437 break;
3438 }
3439
3440 case VBGLR3DNDEVENTTYPE_GH_REQ_PENDING:
3441 {
3442 rc = m_pCurDnD->ghIsDnDPending();
3443 break;
3444 }
3445
3446 case VBGLR3DNDEVENTTYPE_GH_DROP:
3447 {
3448 rc = m_pCurDnD->ghDropped(pVbglR3Event->u.GH_Drop.pszFormat, pVbglR3Event->u.GH_Drop.dndActionRequested);
3449 break;
3450 }
3451#endif
3452 case VBGLR3DNDEVENTTYPE_QUIT:
3453 {
3454 rc = VINF_SUCCESS;
3455 break;
3456 }
3457
3458 default:
3459 {
3460 VBClLogError("Received unsupported message type %RU32\n", pVbglR3Event->enmType);
3461 rc = VERR_NOT_SUPPORTED;
3462 break;
3463 }
3464 }
3465
3466 LogFlowFunc(("Message %RU32 processed with %Rrc\n", pVbglR3Event->enmType, rc));
3467 if (RT_FAILURE(rc))
3468 {
3469 /* Tell the user. */
3470 VBClLogError("Processing message %RU32 failed with %Rrc\n", pVbglR3Event->enmType, rc);
3471
3472 /* If anything went wrong, do a reset and start over. */
3473 reset();
3474 }
3475
3476 const bool fQuit = pVbglR3Event->enmType == VBGLR3DNDEVENTTYPE_QUIT;
3477
3478 VbglR3DnDEventFree(e.hgcm);
3479 e.hgcm = NULL;
3480
3481 if (fQuit)
3482 break;
3483 }
3484 else if (e.enmType == DNDEVENT::DnDEventType_X11)
3485 {
3486 LogFlowThisFunc(("X11 event (type %#x)\n", e.x11.type));
3487 m_pCurDnD->onX11Event(e.x11);
3488 }
3489 else
3490 AssertMsgFailed(("Unknown event queue type %RU32\n", e.enmType));
3491
3492 --cEvents;
3493
3494 } /* for */
3495
3496 /*
3497 * Make sure that any X11 requests have actually been sent to the
3498 * server, since we are waiting for responses using poll() on
3499 * another thread which will not automatically trigger flushing.
3500 */
3501 XFlush(m_pDisplay);
3502
3503 if (m_fStop)
3504 break;
3505
3506 } while (!ASMAtomicReadBool(pfShutdown));
3507
3508 } while (0);
3509
3510 if (m_pCurDnD)
3511 {
3512 delete m_pCurDnD;
3513 m_pCurDnD = NULL;
3514 }
3515
3516 LogFlowFuncLeaveRC(rc);
3517 return rc;
3518}
3519
3520/**
3521 * Resets the DnD service' data.
3522 */
3523void DragAndDropService::reset(void)
3524{
3525 LogFlowFuncEnter();
3526
3527 if (m_pCurDnD)
3528 m_pCurDnD->reset();
3529
3530 /*
3531 * Clear the event queue.
3532 */
3533 int rc2 = RTCritSectEnter(&m_eventQueueCS);
3534 if (RT_SUCCESS(rc2))
3535 {
3536 for (size_t i = 0; i < m_eventQueue.size(); i++)
3537 {
3538 switch (m_eventQueue[i].enmType)
3539 {
3540 case DNDEVENT::DnDEventType_HGCM:
3541 {
3542 VbglR3DnDEventFree(m_eventQueue[i].hgcm);
3543 break;
3544 }
3545
3546 default:
3547 break;
3548 }
3549
3550 }
3551
3552 m_eventQueue.clear();
3553
3554 rc2 = RTCritSectLeave(&m_eventQueueCS);
3555 AssertRC(rc2);
3556 }
3557
3558 LogFlowFuncLeave();
3559}
3560
3561/** @copydoc VBCLSERVICE::pfnStop */
3562void DragAndDropService::stop(void)
3563{
3564 LogFlowFuncEnter();
3565
3566 /* Set stop flag first. */
3567 ASMAtomicXchgBool(&m_fStop, true);
3568
3569 /* First, disconnect any instances. */
3570 if (m_pCurDnD)
3571 m_pCurDnD->stop();
3572
3573 /* Second, disconnect the service's DnD connection. */
3574 VbglR3DnDDisconnect(&m_dndCtx);
3575
3576 LogFlowFuncLeave();
3577}
3578
3579/** @copydoc VBCLSERVICE::pfnTerm */
3580int DragAndDropService::term(void)
3581{
3582 int rc = VINF_SUCCESS;
3583
3584 /*
3585 * Wait for threads to terminate.
3586 */
3587 int rcThread;
3588
3589 if (m_hX11Thread != NIL_RTTHREAD)
3590 {
3591 VBClLogVerbose(2, "Terminating X11 thread ...\n");
3592
3593 int rc2 = RTThreadWait(m_hX11Thread, RT_MS_30SEC, &rcThread);
3594 if (RT_SUCCESS(rc2))
3595 rc2 = rcThread;
3596
3597 if (RT_FAILURE(rc2))
3598 VBClLogError("Error waiting for X11 thread to terminate: %Rrc\n", rc2);
3599
3600 if (RT_SUCCESS(rc))
3601 rc = rc2;
3602
3603 m_hX11Thread = NIL_RTTHREAD;
3604
3605 VBClLogVerbose(2, "X11 thread terminated\n");
3606 }
3607
3608 if (m_hHGCMThread != NIL_RTTHREAD)
3609 {
3610 VBClLogVerbose(2, "Terminating HGCM thread ...\n");
3611
3612 int rc2 = RTThreadWait(m_hHGCMThread, RT_MS_30SEC, &rcThread);
3613 if (RT_SUCCESS(rc2))
3614 rc2 = rcThread;
3615
3616 if (RT_FAILURE(rc2))
3617 VBClLogError("Error waiting for HGCM thread to terminate: %Rrc\n", rc2);
3618
3619 if (RT_SUCCESS(rc))
3620 rc = rc2;
3621
3622 m_hHGCMThread = NIL_RTTHREAD;
3623
3624 VBClLogVerbose(2, "HGCM thread terminated\n");
3625 }
3626
3627 reset();
3628
3629 if (m_pCurDnD)
3630 {
3631 delete m_pCurDnD;
3632 m_pCurDnD = NULL;
3633 }
3634
3635 xHelpers::destroyInstance();
3636
3637 return rc;
3638}
3639
3640/**
3641 * Static callback function for HGCM message processing thread. An internal
3642 * message queue will be filled which then will be processed by the according
3643 * drag'n drop instance.
3644 *
3645 * @returns IPRT status code.
3646 * @param hThread Thread handle to use.
3647 * @param pvUser Pointer to DragAndDropService instance to use.
3648 */
3649/* static */
3650DECLCALLBACK(int) DragAndDropService::hgcmEventThread(RTTHREAD hThread, void *pvUser)
3651{
3652 AssertPtrReturn(pvUser, VERR_INVALID_PARAMETER);
3653 DragAndDropService *pThis = static_cast<DragAndDropService*>(pvUser);
3654
3655 /* Let the service instance know in any case. */
3656 int rc = RTThreadUserSignal(hThread);
3657 AssertRCReturn(rc, rc);
3658
3659 VBClLogVerbose(2, "HGCM thread started\n");
3660
3661 /* Number of invalid messages skipped in a row. */
3662 int cMsgSkippedInvalid = 0;
3663 DNDEVENT e;
3664
3665 do
3666 {
3667 RT_ZERO(e);
3668 e.enmType = DNDEVENT::DnDEventType_HGCM;
3669
3670 /* Wait for new events. */
3671 rc = VbglR3DnDEventGetNext(&pThis->m_dndCtx, &e.hgcm);
3672 if (RT_SUCCESS(rc))
3673 {
3674 cMsgSkippedInvalid = 0; /* Reset skipped messages count. */
3675
3676 int rc2 = RTCritSectEnter(&pThis->m_eventQueueCS);
3677 if (RT_SUCCESS(rc2))
3678 {
3679 VBClLogVerbose(2, "Received new HGCM message (type %#x)\n", e.hgcm->enmType);
3680
3681 pThis->m_eventQueue.append(e);
3682
3683 rc2 = RTCritSectLeave(&pThis->m_eventQueueCS);
3684 AssertRC(rc2);
3685 }
3686
3687 rc = RTSemEventSignal(pThis->m_hEventSem);
3688 if (RT_FAILURE(rc))
3689 break;
3690 }
3691 else
3692 {
3693 VBClLogError("Processing next message failed with rc=%Rrc\n", rc);
3694
3695 /* Old(er) hosts either are broken regarding DnD support or otherwise
3696 * don't support the stuff we do on the guest side, so make sure we
3697 * don't process invalid messages forever. */
3698
3699 if (cMsgSkippedInvalid++ > 32)
3700 {
3701 VBClLogError("Too many invalid/skipped messages from host, exiting ...\n");
3702 break;
3703 }
3704 }
3705
3706 } while (!ASMAtomicReadBool(&pThis->m_fStop));
3707
3708 VBClLogVerbose(2, "HGCM thread ended\n");
3709
3710 LogFlowFuncLeaveRC(rc);
3711 return rc;
3712}
3713
3714/**
3715 * Static callback function for X11 message processing thread. All X11 messages
3716 * will be directly routed to the according drag'n drop instance.
3717 *
3718 * @returns IPRT status code.
3719 * @param hThread Thread handle to use.
3720 * @param pvUser Pointer to DragAndDropService instance to use.
3721 */
3722/* static */
3723DECLCALLBACK(int) DragAndDropService::x11EventThread(RTTHREAD hThread, void *pvUser)
3724{
3725 AssertPtrReturn(pvUser, VERR_INVALID_PARAMETER);
3726 DragAndDropService *pThis = static_cast<DragAndDropService*>(pvUser);
3727 AssertPtr(pThis);
3728
3729 int rc = VINF_SUCCESS;
3730
3731 /* Note: Nothing to initialize here (yet). */
3732
3733 /* Let the service instance know in any case. */
3734 int rc2 = RTThreadUserSignal(hThread);
3735 AssertRC(rc2);
3736
3737 VBClLogVerbose(2, "X11 thread started\n");
3738
3739 DNDEVENT e;
3740 RT_ZERO(e);
3741 e.enmType = DNDEVENT::DnDEventType_X11;
3742
3743 do
3744 {
3745 /*
3746 * Wait for new events. We can't use XIfEvent here, cause this locks
3747 * the window connection with a mutex and if no X11 events occurs this
3748 * blocks any other calls we made to X11. So instead check for new
3749 * events and if there are not any new one, sleep for a certain amount
3750 * of time.
3751 */
3752 unsigned cNewEvents = 0;
3753 unsigned cQueued = XEventsQueued(pThis->m_pDisplay, QueuedAfterFlush);
3754 while (cQueued)
3755 {
3756 /* XNextEvent will block until a new X event becomes available. */
3757 XNextEvent(pThis->m_pDisplay, &e.x11);
3758 {
3759 rc2 = RTCritSectEnter(&pThis->m_eventQueueCS);
3760 if (RT_SUCCESS(rc2))
3761 {
3762 LogFlowFunc(("Added new X11 event, type=%d\n", e.x11.type));
3763
3764 pThis->m_eventQueue.append(e);
3765 cNewEvents++;
3766
3767 rc2 = RTCritSectLeave(&pThis->m_eventQueueCS);
3768 AssertRC(rc2);
3769 }
3770 }
3771
3772 cQueued--;
3773 }
3774
3775 if (cNewEvents)
3776 {
3777 rc = RTSemEventSignal(pThis->m_hEventSem);
3778 if (RT_FAILURE(rc))
3779 break;
3780
3781 continue;
3782 }
3783
3784 /* No new events; wait a bit. */
3785 RTThreadSleep(25 /* ms */);
3786
3787 } while (!ASMAtomicReadBool(&pThis->m_fStop));
3788
3789 VBClLogVerbose(2, "X11 thread ended\n");
3790
3791 LogFlowFuncLeaveRC(rc);
3792 return rc;
3793}
3794/**
3795 * @interface_method_impl{VBCLSERVICE,pfnInit}
3796 */
3797static DECLCALLBACK(int) vbclDnDInit(void)
3798{
3799 return g_Svc.init();
3800}
3801
3802/**
3803 * @interface_method_impl{VBCLSERVICE,pfnWorker}
3804 */
3805static DECLCALLBACK(int) vbclDnDWorker(bool volatile *pfShutdown)
3806{
3807 return g_Svc.worker(pfShutdown);
3808}
3809
3810/**
3811 * @interface_method_impl{VBCLSERVICE,pfnStop}
3812 */
3813static DECLCALLBACK(void) vbclDnDStop(void)
3814{
3815 g_Svc.stop();
3816}
3817
3818/**
3819 * @interface_method_impl{VBCLSERVICE,pfnTerm}
3820 */
3821static DECLCALLBACK(int) vbclDnDTerm(void)
3822{
3823 return g_Svc.term();
3824}
3825
3826VBCLSERVICE g_SvcDragAndDrop =
3827{
3828 "dnd", /* szName */
3829 "Drag'n'Drop", /* pszDescription */
3830 ".vboxclient-draganddrop.pid", /* pszPidFilePath */
3831 NULL, /* pszUsage */
3832 NULL, /* pszOptions */
3833 NULL, /* pfnOption */
3834 vbclDnDInit, /* pfnInit */
3835 vbclDnDWorker, /* pfnWorker */
3836 vbclDnDStop, /* pfnStop*/
3837 vbclDnDTerm /* pfnTerm */
3838};
3839
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