VirtualBox

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

最後變更 在這個檔案從96407是 96407,由 vboxsync 提交於 3 年 前

scm copyright and license note update

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

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