VirtualBox

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

Last change on this file was 99595, checked in by vboxsync, 12 months ago

Guest Additions/VBoxClient: Moved the X11-specific code for drag'n drop into an own submodule and using the actual service as a (runtime) wrapper (for also the Wayland-specific code later). bugref:10427

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

© 2023 Oracle
ContactPrivacy policyTerms of Use