VirtualBox

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

Last change on this file since 61176 was 60981, checked in by vboxsync, 9 years ago

DnD/VBoxClient: Use proper initialization callback handler, fixed some memory leaks on termination, better deal with non-available host service.

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

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