VirtualBox

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

Last change on this file since 79482 was 79482, checked in by vboxsync, 6 years ago

x11/VBoxClient: Heed RT_NEED_NEW_AND_DELETE.

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

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