VirtualBox

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

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

DnD/VBoxClient: Check for a potentially valid window handle in DragInstance::wndX11GetNameA() before calling the X server.

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

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