VirtualBox

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

Last change on this file since 67954 was 65641, checked in by vboxsync, 8 years ago

gcc 7: Additions: fall-thru

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 117.6 KB
Line 
1/* $Id: draganddrop.cpp 65641 2017-02-07 11:28:09Z 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 RTCString strActions = xAtomToString( e.xclient.data.l[XdndStatusAction]);
924#ifdef LOG_ENABLED
925 bool fWantsPosition = ASMBitTest (&e.xclient.data.l[XdndStatusFlags], 1); /* Does the target want XdndPosition messages? */
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 cx = RT_HI_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgWH]);
942 uint16_t cy = RT_LO_U16((uint32_t)e.xclient.data.l[XdndStatusNoMsgWH]);
943 LogFlowThisFunc(("\tReported dead area: x=%RU16, y=%RU16, cx=%RU16, cy=%RU16\n", x, y, cx, cy));
944#endif
945
946 uint32_t uAction = DND_IGNORE_ACTION; /* Default is ignoring. */
947 /** @todo Compare this with the allowed actions. */
948 if (fAcceptDrop)
949 uAction = toHGCMAction(static_cast<Atom>(e.xclient.data.l[XdndStatusAction]));
950
951 rc = VbglR3DnDHGSendAckOp(&m_dndCtx, uAction);
952 }
953 else if (e.xclient.message_type == xAtom(XA_XdndFinished))
954 {
955#ifdef LOG_ENABLED
956 bool fSucceeded = ASMBitTest(&e.xclient.data.l[XdndFinishedFlags], 0);
957
958 char *pszWndName = wndX11GetNameA(e.xclient.data.l[XdndFinishedWindow]);
959 AssertPtr(pszWndName);
960
961 /* This message is sent on an un/successful DnD drop request. */
962 LogFlowThisFunc(("XA_XdndFinished: wnd=%#x ('%s'), success=%RTbool, action=%s\n",
963 e.xclient.data.l[XdndFinishedWindow], pszWndName, fSucceeded,
964 xAtomToString(e.xclient.data.l[XdndFinishedAction]).c_str()));
965
966 RTStrFree(pszWndName);
967#endif
968
969 reset();
970 }
971 else
972 {
973 char *pszWndName = wndX11GetNameA(e.xclient.data.l[0]);
974 AssertPtr(pszWndName);
975 LogFlowThisFunc(("Unhandled: wnd=%#x ('%s'), msg=%s\n",
976 e.xclient.data.l[0], pszWndName, xAtomToString(e.xclient.message_type).c_str()));
977 RTStrFree(pszWndName);
978
979 rc = VERR_NOT_SUPPORTED;
980 }
981
982 break;
983 }
984
985 case Unknown: /* Mode not set (yet). */
986 case GH:
987 {
988 /*
989 * This message marks the beginning of a new drag and drop
990 * operation on the guest.
991 */
992 if (e.xclient.message_type == xAtom(XA_XdndEnter))
993 {
994 LogFlowFunc(("XA_XdndEnter\n"));
995
996 /*
997 * Get the window which currently has the XA_XdndSelection
998 * bit set.
999 */
1000 Window wndSelection = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
1001
1002 char *pszWndName = wndX11GetNameA(wndSelection);
1003 AssertPtr(pszWndName);
1004 LogFlowThisFunc(("wndSelection=%#x ('%s'), wndProxy=%#x\n", wndSelection, pszWndName, m_wndProxy.hWnd));
1005 RTStrFree(pszWndName);
1006
1007 mouseButtonSet(m_wndProxy.hWnd, -1, -1, 1, true /* fPress */);
1008
1009 /*
1010 * Update our state and the window handle to process.
1011 */
1012 int rc2 = RTCritSectEnter(&m_dataCS);
1013 if (RT_SUCCESS(rc2))
1014 {
1015 m_wndCur = wndSelection;
1016 m_curVer = e.xclient.data.l[XdndEnterFlags] >> XdndEnterVersionRShift;
1017 Assert(m_wndCur == (Window)e.xclient.data.l[XdndEnterWindow]); /* Source window. */
1018#ifdef DEBUG
1019 XWindowAttributes xwa;
1020 XGetWindowAttributes(m_pDisplay, m_wndCur, &xwa);
1021 LogFlowThisFunc(("wndCur=%#x, x=%d, y=%d, width=%d, height=%d\n", m_wndCur, xwa.x, xwa.y, xwa.width, xwa.height));
1022#endif
1023 /*
1024 * Retrieve supported formats.
1025 */
1026
1027 /* Check if the MIME types are in the message itself or if we need
1028 * to fetch the XdndTypeList property from the window. */
1029 bool fMoreTypes = e.xclient.data.l[XdndEnterFlags] & XdndEnterMoreTypesFlag;
1030 LogFlowThisFunc(("XdndVer=%d, fMoreTypes=%RTbool\n", m_curVer, fMoreTypes));
1031 if (!fMoreTypes)
1032 {
1033 /* Only up to 3 format types supported. */
1034 /* Start with index 2 (first item). */
1035 for (int i = 2; i < 5; i++)
1036 {
1037 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(e.xclient.data.l[i]).c_str()));
1038 m_lstFormats.append(e.xclient.data.l[i]);
1039 }
1040 }
1041 else
1042 {
1043 /* More than 3 format types supported. */
1044 rc = wndXDnDGetFormatList(wndSelection, m_lstFormats);
1045 }
1046
1047 /*
1048 * Retrieve supported actions.
1049 */
1050 if (RT_SUCCESS(rc))
1051 {
1052 if (m_curVer >= 2) /* More than one action allowed since protocol version 2. */
1053 {
1054 rc = wndXDnDGetActionList(wndSelection, m_lstActions);
1055 }
1056 else /* Only "copy" action allowed on legacy applications. */
1057 m_lstActions.append(XA_XdndActionCopy);
1058 }
1059
1060 if (RT_SUCCESS(rc))
1061 {
1062 m_enmMode = GH;
1063 m_enmState = Dragging;
1064 }
1065
1066 RTCritSectLeave(&m_dataCS);
1067 }
1068 }
1069 else if ( e.xclient.message_type == xAtom(XA_XdndPosition)
1070 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndPositionWindow]))
1071 {
1072 if (m_enmState != Dragging) /* Wrong mode? Bail out. */
1073 {
1074 reset();
1075 break;
1076 }
1077#ifdef LOG_ENABLED
1078 int32_t iPos = e.xclient.data.l[XdndPositionXY];
1079 Atom atmAction = m_curVer >= 2 /* Actions other than "copy" or only supported since protocol version 2. */
1080 ? e.xclient.data.l[XdndPositionAction] : xAtom(XA_XdndActionCopy);
1081 LogFlowThisFunc(("XA_XdndPosition: wndProxy=%#x, wndCur=%#x, x=%RI32, y=%RI32, strAction=%s\n",
1082 m_wndProxy.hWnd, m_wndCur, RT_HIWORD(iPos), RT_LOWORD(iPos),
1083 xAtomToString(atmAction).c_str()));
1084#endif
1085
1086 bool fAcceptDrop = true;
1087
1088 /* Reply with a XdndStatus message to tell the source whether
1089 * the data can be dropped or not. */
1090 XClientMessageEvent m;
1091 RT_ZERO(m);
1092 m.type = ClientMessage;
1093 m.display = m_pDisplay;
1094 m.window = e.xclient.data.l[XdndPositionWindow];
1095 m.message_type = xAtom(XA_XdndStatus);
1096 m.format = 32;
1097 m.data.l[XdndStatusWindow] = m_wndProxy.hWnd;
1098 m.data.l[XdndStatusFlags] = fAcceptDrop ? RT_BIT(0) : 0; /* Whether to accept the drop or not. */
1099
1100 /* We don't want any new XA_XdndPosition messages while being
1101 * in our proxy window. */
1102 m.data.l[XdndStatusNoMsgXY] = RT_MAKE_U32(m_wndProxy.iY, m_wndProxy.iX);
1103 m.data.l[XdndStatusNoMsgWH] = RT_MAKE_U32(m_wndProxy.iHeight, m_wndProxy.iWidth);
1104
1105 /** @todo Handle default action! */
1106 m.data.l[XdndStatusAction] = fAcceptDrop ? toAtomAction(DND_COPY_ACTION) : None;
1107
1108 int xRc = XSendEvent(m_pDisplay, e.xclient.data.l[XdndPositionWindow],
1109 False /* Propagate */, NoEventMask, reinterpret_cast<XEvent *>(&m));
1110 if (xRc == 0)
1111 logError("Error sending position XA_XdndStatus event to current window=%#x: %s\n",
1112 m_wndCur, gX11->xErrorToString(xRc).c_str());
1113 }
1114 else if ( e.xclient.message_type == xAtom(XA_XdndLeave)
1115 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndLeaveWindow]))
1116 {
1117 LogFlowThisFunc(("XA_XdndLeave\n"));
1118 logInfo("Guest to host transfer canceled by the guest source window\n");
1119
1120 /* Start over. */
1121 reset();
1122 }
1123 else if ( e.xclient.message_type == xAtom(XA_XdndDrop)
1124 && m_wndCur == static_cast<Window>(e.xclient.data.l[XdndDropWindow]))
1125 {
1126 LogFlowThisFunc(("XA_XdndDrop\n"));
1127
1128 if (m_enmState != Dropped) /* Wrong mode? Bail out. */
1129 {
1130 /* Can occur when dragging from guest->host, but then back in to the guest again. */
1131 logInfo("Could not drop on own proxy window\n"); /* Not fatal. */
1132
1133 /* Let the source know. */
1134 rc = m_wndProxy.sendFinished(m_wndCur, DND_IGNORE_ACTION);
1135
1136 /* Start over. */
1137 reset();
1138 break;
1139 }
1140
1141 m_eventQueueList.append(e);
1142 rc = RTSemEventSignal(m_eventQueueEvent);
1143 }
1144 else
1145 {
1146 logInfo("Unhandled event from wnd=%#x, msg=%s\n", e.xclient.window, xAtomToString(e.xclient.message_type).c_str());
1147
1148 /* Let the source know. */
1149 rc = m_wndProxy.sendFinished(m_wndCur, DND_IGNORE_ACTION);
1150
1151 /* Start over. */
1152 reset();
1153 }
1154 break;
1155 }
1156
1157 default:
1158 {
1159 AssertMsgFailed(("Drag and drop mode not implemented: %RU32\n", m_enmMode));
1160 rc = VERR_NOT_IMPLEMENTED;
1161 break;
1162 }
1163 }
1164
1165 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1166 return rc;
1167}
1168
1169int DragInstance::onX11MotionNotify(const XEvent &e)
1170{
1171 RT_NOREF1(e);
1172 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1173
1174 return VINF_SUCCESS;
1175}
1176
1177/**
1178 * Callback handler for being notified if some other window now
1179 * is the owner of the current selection.
1180 *
1181 * @return IPRT status code.
1182 * @param e X11 event to handle.
1183 *
1184 * @remark
1185 */
1186int DragInstance::onX11SelectionClear(const XEvent &e)
1187{
1188 RT_NOREF1(e);
1189 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1190
1191 return VINF_SUCCESS;
1192}
1193
1194/**
1195 * Callback handler for a XDnD selection notify from a window. This is needed
1196 * to let the us know if a certain window has drag'n drop data to share with us,
1197 * e.g. our proxy window.
1198 *
1199 * @return IPRT status code.
1200 * @param e X11 event to handle.
1201 */
1202int DragInstance::onX11SelectionNotify(const XEvent &e)
1203{
1204 AssertReturn(e.type == SelectionNotify, VERR_INVALID_PARAMETER);
1205
1206 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1207
1208 int rc;
1209
1210 switch (m_enmMode)
1211 {
1212 case GH:
1213 {
1214 if (m_enmState == Dropped)
1215 {
1216 m_eventQueueList.append(e);
1217 rc = RTSemEventSignal(m_eventQueueEvent);
1218 }
1219 else
1220 rc = VERR_WRONG_ORDER;
1221 break;
1222 }
1223
1224 default:
1225 {
1226 LogFlowThisFunc(("Unhandled: wnd=%#x, msg=%s\n",
1227 e.xclient.data.l[0], xAtomToString(e.xclient.message_type).c_str()));
1228 rc = VERR_INVALID_STATE;
1229 break;
1230 }
1231 }
1232
1233 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1234 return rc;
1235}
1236
1237/**
1238 * Callback handler for a XDnD selection request from a window. This is needed
1239 * to retrieve the data required to complete the actual drag'n drop operation.
1240 *
1241 * @returns IPRT status code.
1242 * @param e X11 event to handle.
1243 */
1244int DragInstance::onX11SelectionRequest(const XEvent &e)
1245{
1246 AssertReturn(e.type == SelectionRequest, VERR_INVALID_PARAMETER);
1247
1248 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1249 LogFlowThisFunc(("Event owner=%#x, requestor=%#x, selection=%s, target=%s, prop=%s, time=%u\n",
1250 e.xselectionrequest.owner,
1251 e.xselectionrequest.requestor,
1252 xAtomToString(e.xselectionrequest.selection).c_str(),
1253 xAtomToString(e.xselectionrequest.target).c_str(),
1254 xAtomToString(e.xselectionrequest.property).c_str(),
1255 e.xselectionrequest.time));
1256 int rc;
1257
1258 switch (m_enmMode)
1259 {
1260 case HG:
1261 {
1262 rc = VINF_SUCCESS;
1263
1264 char *pszWndName = wndX11GetNameA(e.xselectionrequest.requestor);
1265 AssertPtr(pszWndName);
1266
1267 /*
1268 * Start by creating a refusal selection notify message.
1269 * That way we only need to care for the success case.
1270 */
1271
1272 XEvent s;
1273 RT_ZERO(s);
1274 s.xselection.type = SelectionNotify;
1275 s.xselection.display = e.xselectionrequest.display;
1276 s.xselection.requestor = e.xselectionrequest.requestor;
1277 s.xselection.selection = e.xselectionrequest.selection;
1278 s.xselection.target = e.xselectionrequest.target;
1279 s.xselection.property = None; /* "None" means refusal. */
1280 s.xselection.time = e.xselectionrequest.time;
1281
1282 const XSelectionRequestEvent *pReq = &e.xselectionrequest;
1283
1284#ifdef DEBUG
1285 LogFlowFunc(("Supported formats:\n"));
1286 for (size_t i = 0; i < m_lstFormats.size(); i++)
1287 LogFlowFunc(("\t%s\n", xAtomToString(m_lstFormats.at(i)).c_str()));
1288#endif
1289 /* Is the requestor asking for the possible MIME types? */
1290 if (pReq->target == xAtom(XA_TARGETS))
1291 {
1292 logInfo("Target window %#x ('%s') asking for target list\n", e.xselectionrequest.requestor, pszWndName);
1293
1294 /* If so, set the window property with the formats on the requestor
1295 * window. */
1296 rc = wndXDnDSetFormatList(pReq->requestor, pReq->property, m_lstFormats);
1297 if (RT_SUCCESS(rc))
1298 s.xselection.property = pReq->property;
1299 }
1300 /* Is the requestor asking for a specific MIME type (we support)? */
1301 else if (m_lstFormats.contains(pReq->target))
1302 {
1303 logInfo("Target window %#x ('%s') is asking for data as '%s'\n",
1304 pReq->requestor, pszWndName, xAtomToString(pReq->target).c_str());
1305
1306 /* Did we not drop our stuff to the guest yet? Bail out. */
1307 if (m_enmState != Dropped)
1308 {
1309 LogFlowThisFunc(("Wrong state (%RU32), refusing request\n", m_enmState));
1310 }
1311 /* Did we not store the requestor's initial selection request yet? Then do so now. */
1312 else
1313 {
1314 /* Get the data format the requestor wants from us. */
1315 RTCString strFormat = xAtomToString(pReq->target);
1316 Assert(strFormat.isNotEmpty());
1317 logInfo("Target window=%#x requested data from host as '%s', rc=%Rrc\n",
1318 pReq->requestor, strFormat.c_str(), rc);
1319
1320 /* Make a copy of the MIME data to be passed back. The X server will be become
1321 * the new owner of that data, so no deletion needed. */
1322 /** @todo Do we need to do some more conversion here? XConvertSelection? */
1323 void *pvData = RTMemDup(m_pvSelReqData, m_cbSelReqData);
1324 uint32_t cbData = m_cbSelReqData;
1325
1326 /* Always return the requested property. */
1327 s.xselection.property = pReq->property;
1328
1329 /* Note: Always seems to return BadRequest. Seems fine. */
1330 int xRc = XChangeProperty(s.xselection.display, s.xselection.requestor, s.xselection.property,
1331 s.xselection.target, 8, PropModeReplace,
1332 reinterpret_cast<const unsigned char*>(pvData), cbData);
1333
1334 LogFlowFunc(("Changing property '%s' (target '%s') of window=0x%x: %s\n",
1335 xAtomToString(pReq->property).c_str(),
1336 xAtomToString(pReq->target).c_str(),
1337 pReq->requestor,
1338 gX11->xErrorToString(xRc).c_str()));
1339 NOREF(xRc);
1340 }
1341 }
1342 /* Anything else. */
1343 else
1344 {
1345 logError("Refusing unknown command/format '%s' of wnd=%#x ('%s')\n",
1346 xAtomToString(e.xselectionrequest.target).c_str(), pReq->requestor, pszWndName);
1347 rc = VERR_NOT_SUPPORTED;
1348 }
1349
1350 LogFlowThisFunc(("Offering type '%s', property '%s' to wnd=%#x ...\n",
1351 xAtomToString(pReq->target).c_str(),
1352 xAtomToString(pReq->property).c_str(), pReq->requestor));
1353
1354 int xRc = XSendEvent(pReq->display, pReq->requestor, True /* Propagate */, 0, &s);
1355 if (xRc == 0)
1356 logError("Error sending SelectionNotify(1) event to wnd=%#x: %s\n", pReq->requestor,
1357 gX11->xErrorToString(xRc).c_str());
1358 XFlush(pReq->display);
1359
1360 if (pszWndName)
1361 RTStrFree(pszWndName);
1362 break;
1363 }
1364
1365 default:
1366 rc = VERR_INVALID_STATE;
1367 break;
1368 }
1369
1370 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
1371 return rc;
1372}
1373
1374/**
1375 * Handles X11 events, called by x11EventThread.
1376 *
1377 * @returns IPRT status code.
1378 * @param e X11 event to handle.
1379 */
1380int DragInstance::onX11Event(const XEvent &e)
1381{
1382 int rc;
1383
1384 LogFlowThisFunc(("X11 event, type=%d\n", e.type));
1385 switch (e.type)
1386 {
1387 /*
1388 * This can happen if a guest->host drag operation
1389 * goes back from the host to the guest. This is not what
1390 * we want and thus resetting everything.
1391 */
1392 case ButtonPress:
1393 case ButtonRelease:
1394 LogFlowThisFunc(("Mouse button press/release\n"));
1395 rc = VINF_SUCCESS;
1396
1397 reset();
1398 break;
1399
1400 case ClientMessage:
1401 rc = onX11ClientMessage(e);
1402 break;
1403
1404 case SelectionClear:
1405 rc = onX11SelectionClear(e);
1406 break;
1407
1408 case SelectionNotify:
1409 rc = onX11SelectionNotify(e);
1410 break;
1411
1412 case SelectionRequest:
1413 rc = onX11SelectionRequest(e);
1414 break;
1415
1416 case MotionNotify:
1417 rc = onX11MotionNotify(e);
1418 break;
1419
1420 default:
1421 rc = VERR_NOT_IMPLEMENTED;
1422 break;
1423 }
1424
1425 LogFlowThisFunc(("rc=%Rrc\n", rc));
1426 return rc;
1427}
1428
1429int DragInstance::waitForStatusChange(uint32_t enmState, RTMSINTERVAL uTimeoutMS /* = 30000 */)
1430{
1431 const uint64_t uiStart = RTTimeMilliTS();
1432 volatile uint32_t enmCurState;
1433
1434 int rc = VERR_TIMEOUT;
1435
1436 LogFlowFunc(("enmState=%RU32, uTimeoutMS=%RU32\n", enmState, uTimeoutMS));
1437
1438 do
1439 {
1440 enmCurState = ASMAtomicReadU32(&m_enmState);
1441 if (enmCurState == enmState)
1442 {
1443 rc = VINF_SUCCESS;
1444 break;
1445 }
1446 }
1447 while (RTTimeMilliTS() - uiStart < uTimeoutMS);
1448
1449 LogFlowThisFunc(("Returning %Rrc\n", rc));
1450 return rc;
1451}
1452
1453#ifdef VBOX_WITH_DRAG_AND_DROP_GH
1454/**
1455 * Waits for an X11 event of a specific type.
1456 *
1457 * @returns IPRT status code.
1458 * @param evX Reference where to store the event into.
1459 * @param iType Event type to wait for.
1460 * @param uTimeoutMS Timeout (in ms) to wait for the event.
1461 */
1462bool DragInstance::waitForX11Msg(XEvent &evX, int iType, RTMSINTERVAL uTimeoutMS /* = 100 */)
1463{
1464 LogFlowThisFunc(("iType=%d, uTimeoutMS=%RU32, cEventQueue=%zu\n", iType, uTimeoutMS, m_eventQueueList.size()));
1465
1466 bool fFound = false;
1467 const uint64_t uiStart = RTTimeMilliTS();
1468
1469 do
1470 {
1471 /* Check if there is a client message in the queue. */
1472 for (size_t i = 0; i < m_eventQueueList.size(); i++)
1473 {
1474 int rc2 = RTCritSectEnter(&m_eventQueueCS);
1475 if (RT_SUCCESS(rc2))
1476 {
1477 XEvent e = m_eventQueueList.at(i);
1478
1479 fFound = e.type == iType;
1480 if (fFound)
1481 {
1482 m_eventQueueList.removeAt(i);
1483 evX = e;
1484 }
1485
1486 rc2 = RTCritSectLeave(&m_eventQueueCS);
1487 AssertRC(rc2);
1488
1489 if (fFound)
1490 break;
1491 }
1492 }
1493
1494 if (fFound)
1495 break;
1496
1497 int rc2 = RTSemEventWait(m_eventQueueEvent, 25 /* ms */);
1498 if ( RT_FAILURE(rc2)
1499 && rc2 != VERR_TIMEOUT)
1500 {
1501 LogFlowFunc(("Waiting failed with rc=%Rrc\n", rc2));
1502 break;
1503 }
1504 }
1505 while (RTTimeMilliTS() - uiStart < uTimeoutMS);
1506
1507 LogFlowThisFunc(("Returning fFound=%RTbool, msRuntime=%RU64\n", fFound, RTTimeMilliTS() - uiStart));
1508 return fFound;
1509}
1510
1511/**
1512 * Waits for an X11 client message of a specific type.
1513 *
1514 * @returns IPRT status code.
1515 * @param evMsg Reference where to store the event into.
1516 * @param aType Event type to wait for.
1517 * @param uTimeoutMS Timeout (in ms) to wait for the event.
1518 */
1519bool DragInstance::waitForX11ClientMsg(XClientMessageEvent &evMsg, Atom aType,
1520 RTMSINTERVAL uTimeoutMS /* = 100 */)
1521{
1522 LogFlowThisFunc(("aType=%s, uTimeoutMS=%RU32, cEventQueue=%zu\n",
1523 xAtomToString(aType).c_str(), uTimeoutMS, m_eventQueueList.size()));
1524
1525 bool fFound = false;
1526 const uint64_t uiStart = RTTimeMilliTS();
1527 do
1528 {
1529 /* Check if there is a client message in the queue. */
1530 for (size_t i = 0; i < m_eventQueueList.size(); i++)
1531 {
1532 int rc2 = RTCritSectEnter(&m_eventQueueCS);
1533 if (RT_SUCCESS(rc2))
1534 {
1535 XEvent e = m_eventQueueList.at(i);
1536 if ( e.type == ClientMessage
1537 && e.xclient.message_type == aType)
1538 {
1539 m_eventQueueList.removeAt(i);
1540 evMsg = e.xclient;
1541
1542 fFound = true;
1543 }
1544
1545 if (e.type == ClientMessage)
1546 {
1547 LogFlowThisFunc(("Client message: Type=%ld (%s)\n",
1548 e.xclient.message_type, xAtomToString(e.xclient.message_type).c_str()));
1549 }
1550 else
1551 LogFlowThisFunc(("X message: Type=%d\n", e.type));
1552
1553 rc2 = RTCritSectLeave(&m_eventQueueCS);
1554 AssertRC(rc2);
1555
1556 if (fFound)
1557 break;
1558 }
1559 }
1560
1561 if (fFound)
1562 break;
1563
1564 int rc2 = RTSemEventWait(m_eventQueueEvent, 25 /* ms */);
1565 if ( RT_FAILURE(rc2)
1566 && rc2 != VERR_TIMEOUT)
1567 {
1568 LogFlowFunc(("Waiting failed with rc=%Rrc\n", rc2));
1569 break;
1570 }
1571 }
1572 while (RTTimeMilliTS() - uiStart < uTimeoutMS);
1573
1574 LogFlowThisFunc(("Returning fFound=%RTbool, msRuntime=%RU64\n", fFound, RTTimeMilliTS() - uiStart));
1575 return fFound;
1576}
1577#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
1578
1579/*
1580 * Host -> Guest
1581 */
1582
1583/**
1584 * Host -> Guest: Event signalling that the host's (mouse) cursor just entered the VM's (guest's) display
1585 * area.
1586 *
1587 * @returns IPRT status code.
1588 * @param lstFormats List of supported formats from the host.
1589 * @param uActions (ORed) List of supported actions from the host.
1590 */
1591int DragInstance::hgEnter(const RTCList<RTCString> &lstFormats, uint32_t uActions)
1592{
1593 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1594
1595 if (m_enmMode != Unknown)
1596 return VERR_INVALID_STATE;
1597
1598 reset();
1599
1600#ifdef DEBUG
1601 LogFlowThisFunc(("uActions=0x%x, lstFormats=%zu: ", uActions, lstFormats.size()));
1602 for (size_t i = 0; i < lstFormats.size(); ++i)
1603 LogFlow(("'%s' ", lstFormats.at(i).c_str()));
1604 LogFlow(("\n"));
1605#endif
1606
1607 int rc;
1608
1609 do
1610 {
1611 rc = toAtomList(lstFormats, m_lstFormats);
1612 if (RT_FAILURE(rc))
1613 break;
1614
1615 /* If we have more than 3 formats we have to use the type list extension. */
1616 if (m_lstFormats.size() > 3)
1617 {
1618 rc = wndXDnDSetFormatList(m_wndProxy.hWnd, xAtom(XA_XdndTypeList), m_lstFormats);
1619 if (RT_FAILURE(rc))
1620 break;
1621 }
1622
1623 /* Announce the possible actions. */
1624 VBoxDnDAtomList lstActions;
1625 rc = toAtomActions(uActions, lstActions);
1626 if (RT_FAILURE(rc))
1627 break;
1628 rc = wndXDnDSetActionList(m_wndProxy.hWnd, lstActions);
1629
1630 /* Set the DnD selection owner to our window. */
1631 /** @todo Don't use CurrentTime -- according to ICCCM section 2.1. */
1632 XSetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection), m_wndProxy.hWnd, CurrentTime);
1633
1634 m_enmMode = HG;
1635 m_enmState = Dragging;
1636
1637 } while (0);
1638
1639 LogFlowFuncLeaveRC(rc);
1640 return rc;
1641}
1642
1643/**
1644 * Host -> Guest: Event signalling that the host's (mouse) cursor has left the VM's (guest's)
1645 * display area.
1646 */
1647int DragInstance::hgLeave(void)
1648{
1649 if (m_enmMode == HG) /* Only reset if in the right operation mode. */
1650 reset();
1651
1652 return VINF_SUCCESS;
1653}
1654
1655/**
1656 * Host -> Guest: Event signalling that the host's (mouse) cursor has been moved within the VM's
1657 * (guest's) display area.
1658 *
1659 * @returns IPRT status code.
1660 * @param u32xPos Relative X position within the guest's display area.
1661 * @param u32yPos Relative Y position within the guest's display area.
1662 * @param uDefaultAction Default action the host wants to perform on the guest
1663 * as soon as the operation successfully finishes.
1664 */
1665int DragInstance::hgMove(uint32_t u32xPos, uint32_t u32yPos, uint32_t uDefaultAction)
1666{
1667 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1668 LogFlowThisFunc(("u32xPos=%RU32, u32yPos=%RU32, uAction=%RU32\n", u32xPos, u32yPos, uDefaultAction));
1669
1670 if ( m_enmMode != HG
1671 || m_enmState != Dragging)
1672 {
1673 return VERR_INVALID_STATE;
1674 }
1675
1676 int rc = VINF_SUCCESS;
1677 int xRc = Success;
1678
1679 /* Move the mouse cursor within the guest. */
1680 mouseCursorMove(u32xPos, u32yPos);
1681
1682 long newVer = -1; /* This means the current window is _not_ XdndAware. */
1683
1684 /* Search for the application window below the cursor. */
1685 Window wndCursor = gX11->applicationWindowBelowCursor(m_wndRoot);
1686 if (wndCursor != None)
1687 {
1688 /* Temp stuff for the XGetWindowProperty call. */
1689 Atom atmp;
1690 int fmt;
1691 unsigned long cItems, cbRemaining;
1692 unsigned char *pcData = NULL;
1693
1694 /* Query the XdndAware property from the window. We are interested in
1695 * the version and if it is XdndAware at all. */
1696 xRc = XGetWindowProperty(m_pDisplay, wndCursor, xAtom(XA_XdndAware),
1697 0, 2, False, AnyPropertyType,
1698 &atmp, &fmt, &cItems, &cbRemaining, &pcData);
1699 if (xRc != Success)
1700 {
1701 logError("Error getting properties of cursor window=%#x: %s\n", wndCursor, gX11->xErrorToString(xRc).c_str());
1702 }
1703 else
1704 {
1705 if (pcData == NULL || fmt != 32 || cItems != 1)
1706 {
1707 /** @todo Do we need to deal with this? */
1708 logError("Wrong window properties for window %#x: pcData=%#x, iFmt=%d, cItems=%ul\n",
1709 wndCursor, pcData, fmt, cItems);
1710 }
1711 else
1712 {
1713 /* Get the current window's Xdnd version. */
1714 newVer = reinterpret_cast<long *>(pcData)[0];
1715 }
1716
1717 XFree(pcData);
1718 }
1719 }
1720
1721#ifdef DEBUG
1722 char *pszNameCursor = wndX11GetNameA(wndCursor);
1723 AssertPtr(pszNameCursor);
1724 char *pszNameCur = wndX11GetNameA(m_wndCur);
1725 AssertPtr(pszNameCur);
1726
1727 LogFlowThisFunc(("wndCursor=%x ('%s', Xdnd version %ld), wndCur=%x ('%s', Xdnd version %ld)\n",
1728 wndCursor, pszNameCursor, newVer, m_wndCur, pszNameCur, m_curVer));
1729
1730 RTStrFree(pszNameCursor);
1731 RTStrFree(pszNameCur);
1732#endif
1733
1734 if ( wndCursor != m_wndCur
1735 && m_curVer != -1)
1736 {
1737 LogFlowThisFunc(("XA_XdndLeave: window=%#x\n", m_wndCur));
1738
1739 char *pszWndName = wndX11GetNameA(m_wndCur);
1740 AssertPtr(pszWndName);
1741 logInfo("Left old window %#x ('%s'), Xdnd version=%ld\n", m_wndCur, pszWndName, newVer);
1742 RTStrFree(pszWndName);
1743
1744 /* We left the current XdndAware window. Announce this to the current indow. */
1745 XClientMessageEvent m;
1746 RT_ZERO(m);
1747 m.type = ClientMessage;
1748 m.display = m_pDisplay;
1749 m.window = m_wndCur;
1750 m.message_type = xAtom(XA_XdndLeave);
1751 m.format = 32;
1752 m.data.l[XdndLeaveWindow] = m_wndProxy.hWnd;
1753
1754 xRc = XSendEvent(m_pDisplay, m_wndCur, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
1755 if (xRc == 0)
1756 logError("Error sending XA_XdndLeave event to old window=%#x: %s\n", m_wndCur, gX11->xErrorToString(xRc).c_str());
1757
1758 /* Reset our current window. */
1759 m_wndCur = 0;
1760 m_curVer = -1;
1761 }
1762
1763 /*
1764 * Do we have a new Xdnd-aware window which now is under the cursor?
1765 */
1766 if ( wndCursor != m_wndCur
1767 && newVer != -1)
1768 {
1769 LogFlowThisFunc(("XA_XdndEnter: window=%#x\n", wndCursor));
1770
1771 char *pszWndName = wndX11GetNameA(wndCursor);
1772 AssertPtr(pszWndName);
1773 logInfo("Entered new window %#x ('%s'), supports Xdnd version=%ld\n", wndCursor, pszWndName, newVer);
1774 RTStrFree(pszWndName);
1775
1776 /*
1777 * We enter a new window. Announce the XdndEnter event to the new
1778 * window. The first three mime types are attached to the event (the
1779 * others could be requested by the XdndTypeList property from the
1780 * window itself).
1781 */
1782 XClientMessageEvent m;
1783 RT_ZERO(m);
1784 m.type = ClientMessage;
1785 m.display = m_pDisplay;
1786 m.window = wndCursor;
1787 m.message_type = xAtom(XA_XdndEnter);
1788 m.format = 32;
1789 m.data.l[XdndEnterWindow] = m_wndProxy.hWnd;
1790 m.data.l[XdndEnterFlags] = RT_MAKE_U32_FROM_U8(
1791 /* Bit 0 is set if the source supports more than three data types. */
1792 m_lstFormats.size() > 3 ? RT_BIT(0) : 0,
1793 /* Reserved for future use. */
1794 0, 0,
1795 /* Protocol version to use. */
1796 RT_MIN(VBOX_XDND_VERSION, newVer));
1797 m.data.l[XdndEnterType1] = m_lstFormats.value(0, None); /* First data type to use. */
1798 m.data.l[XdndEnterType2] = m_lstFormats.value(1, None); /* Second data type to use. */
1799 m.data.l[XdndEnterType3] = m_lstFormats.value(2, None); /* Third data type to use. */
1800
1801 xRc = XSendEvent(m_pDisplay, wndCursor, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
1802 if (xRc == 0)
1803 logError("Error sending XA_XdndEnter event to window=%#x: %s\n", wndCursor, gX11->xErrorToString(xRc).c_str());
1804 }
1805
1806 if (newVer != -1)
1807 {
1808 Assert(wndCursor != None);
1809
1810 LogFlowThisFunc(("XA_XdndPosition: xPos=%RU32, yPos=%RU32 to window=%#x\n", u32xPos, u32yPos, wndCursor));
1811
1812 /*
1813 * Send a XdndPosition event with the proposed action to the guest.
1814 */
1815 Atom pa = toAtomAction(uDefaultAction);
1816 LogFlowThisFunc(("strAction=%s\n", xAtomToString(pa).c_str()));
1817
1818 XClientMessageEvent m;
1819 RT_ZERO(m);
1820 m.type = ClientMessage;
1821 m.display = m_pDisplay;
1822 m.window = wndCursor;
1823 m.message_type = xAtom(XA_XdndPosition);
1824 m.format = 32;
1825 m.data.l[XdndPositionWindow] = m_wndProxy.hWnd; /* X window ID of source window. */
1826 m.data.l[XdndPositionXY] = RT_MAKE_U32(u32yPos, u32xPos); /* Cursor coordinates relative to the root window. */
1827 m.data.l[XdndPositionTimeStamp] = CurrentTime; /* Timestamp for retrieving data. */
1828 m.data.l[XdndPositionAction] = pa; /* Actions requested by the user. */
1829
1830 xRc = XSendEvent(m_pDisplay, wndCursor, False, NoEventMask, reinterpret_cast<XEvent*>(&m));
1831 if (xRc == 0)
1832 logError("Error sending XA_XdndPosition event to current window=%#x: %s\n", wndCursor, gX11->xErrorToString(xRc).c_str());
1833 }
1834
1835 if (newVer == -1)
1836 {
1837 /* No window to process, so send a ignore ack event to the host. */
1838 rc = VbglR3DnDHGSendAckOp(&m_dndCtx, DND_IGNORE_ACTION);
1839 }
1840 else
1841 {
1842 Assert(wndCursor != None);
1843
1844 m_wndCur = wndCursor;
1845 m_curVer = newVer;
1846 }
1847
1848 LogFlowFuncLeaveRC(rc);
1849 return rc;
1850}
1851
1852/**
1853 * Host -> Guest: Event signalling that the host has dropped the data over the VM (guest) window.
1854 *
1855 * @returns IPRT status code.
1856 * @param u32xPos Relative X position within the guest's display area.
1857 * @param u32yPos Relative Y position within the guest's display area.
1858 * @param uDefaultAction Default action the host wants to perform on the guest
1859 * as soon as the operation successfully finishes.
1860 */
1861int DragInstance::hgDrop(uint32_t u32xPos, uint32_t u32yPos, uint32_t uDefaultAction)
1862{
1863
1864
1865 /** @todo r=bird: Please, stop using 'u32' as a prefix unless you've got a _real_ _important_ reason for needing the bit count. */
1866
1867
1868 RT_NOREF3(u32xPos, u32yPos, uDefaultAction);
1869 LogFlowThisFunc(("wndCur=%#x, wndProxy=%#x, mode=%RU32, state=%RU32\n", m_wndCur, m_wndProxy.hWnd, m_enmMode, m_enmState));
1870 LogFlowThisFunc(("u32xPos=%RU32, u32yPos=%RU32, uAction=%RU32\n", u32xPos, u32yPos, uDefaultAction));
1871
1872 if ( m_enmMode != HG
1873 || m_enmState != Dragging)
1874 {
1875 return VERR_INVALID_STATE;
1876 }
1877
1878 /* Set the state accordingly. */
1879 m_enmState = Dropped;
1880
1881 /*
1882 * Ask the host to send the raw data, as we don't (yet) know which format
1883 * the guest exactly expects. As blocking in a SelectionRequest message turned
1884 * out to be very unreliable (e.g. with KDE apps) we request to start transferring
1885 * file/directory data (if any) here.
1886 */
1887 char szFormat[] = { "text/uri-list" };
1888
1889 int rc = VbglR3DnDHGSendReqData(&m_dndCtx, szFormat);
1890 logInfo("Drop event from host resuled in: %Rrc\n", rc);
1891
1892 LogFlowFuncLeaveRC(rc);
1893 return rc;
1894}
1895
1896/**
1897 * Host -> Guest: Event signalling that the host has finished sending drag'n drop
1898 * data to the guest for further processing.
1899 *
1900 * @returns IPRT status code.
1901 * @param pvData Pointer to (MIME) data from host.
1902 * @param cbData Size (in bytes) of data from host.
1903 */
1904int DragInstance::hgDataReceived(const void *pvData, uint32_t cbData)
1905{
1906 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1907 LogFlowThisFunc(("pvData=%p, cbData=%RU32\n", pvData, cbData));
1908
1909 if ( m_enmMode != HG
1910 || m_enmState != Dropped)
1911 {
1912 return VERR_INVALID_STATE;
1913 }
1914
1915 if ( pvData == NULL
1916 || cbData == 0)
1917 {
1918 return VERR_INVALID_PARAMETER;
1919 }
1920
1921 int rc = VINF_SUCCESS;
1922
1923 /*
1924 * At this point all data needed (including sent files/directories) should
1925 * be on the guest, so proceed working on communicating with the target window.
1926 */
1927 logInfo("Received %RU32 bytes MIME data from host\n", cbData);
1928
1929 /* Destroy any old data. */
1930 if (m_pvSelReqData)
1931 {
1932 Assert(m_cbSelReqData);
1933
1934 RTMemFree(m_pvSelReqData); /** @todo RTMemRealloc? */
1935 m_cbSelReqData = 0;
1936 }
1937
1938 /** @todo Handle incremental transfers. */
1939
1940 /* Make a copy of the data. This data later then will be used to fill into
1941 * the selection request. */
1942 if (cbData)
1943 {
1944 m_pvSelReqData = RTMemAlloc(cbData);
1945 if (!m_pvSelReqData)
1946 return VERR_NO_MEMORY;
1947
1948 memcpy(m_pvSelReqData, pvData, cbData);
1949 m_cbSelReqData = cbData;
1950 }
1951
1952 /*
1953 * Send a drop event to the current window (target).
1954 * This window in turn then will raise a SelectionRequest message to our proxy window,
1955 * which we will handle in our onX11SelectionRequest handler.
1956 *
1957 * The SelectionRequest will tell us in which format the target wants the data from the host.
1958 */
1959 XClientMessageEvent m;
1960 RT_ZERO(m);
1961 m.type = ClientMessage;
1962 m.display = m_pDisplay;
1963 m.window = m_wndCur;
1964 m.message_type = xAtom(XA_XdndDrop);
1965 m.format = 32;
1966 m.data.l[XdndDropWindow] = m_wndProxy.hWnd; /* Source window. */
1967 m.data.l[XdndDropFlags] = 0; /* Reserved for future use. */
1968 m.data.l[XdndDropTimeStamp] = CurrentTime; /* Our DnD data does not rely on any timing, so just use the current time. */
1969
1970 int xRc = XSendEvent(m_pDisplay, m_wndCur, False /* Propagate */, NoEventMask, reinterpret_cast<XEvent*>(&m));
1971 if (xRc == 0)
1972 logError("Error sending XA_XdndDrop event to window=%#x: %s\n", m_wndCur, gX11->xErrorToString(xRc).c_str());
1973 XFlush(m_pDisplay);
1974
1975 LogFlowFuncLeaveRC(rc);
1976 return rc;
1977}
1978
1979#ifdef VBOX_WITH_DRAG_AND_DROP_GH
1980/**
1981 * Guest -> Host: Event signalling that the host is asking whether there is a pending
1982 * drag event on the guest (to the host).
1983 *
1984 * @returns IPRT status code.
1985 */
1986int DragInstance::ghIsDnDPending(void)
1987{
1988 LogFlowThisFunc(("mode=%RU32, state=%RU32\n", m_enmMode, m_enmState));
1989
1990 int rc;
1991
1992 RTCString strFormats = "\r\n"; /** @todo If empty, IOCTL fails with VERR_ACCESS_DENIED. */
1993 uint32_t uDefAction = DND_IGNORE_ACTION;
1994 uint32_t uAllActions = DND_IGNORE_ACTION;
1995
1996 /* Currently in wrong mode? Bail out. */
1997 if (m_enmMode == HG)
1998 rc = VERR_INVALID_STATE;
1999 /* Message already processed successfully? */
2000 else if ( m_enmMode == GH
2001 && ( m_enmState == Dragging
2002 || m_enmState == Dropped)
2003 )
2004 {
2005 /* No need to query for the source window again. */
2006 rc = VINF_SUCCESS;
2007 }
2008 else
2009 {
2010 rc = VINF_SUCCESS;
2011
2012 /* Determine the current window which currently has the XdndSelection set. */
2013 Window wndSelection = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
2014 LogFlowThisFunc(("wndSelection=%#x, wndProxy=%#x, wndCur=%#x\n", wndSelection, m_wndProxy.hWnd, m_wndCur));
2015
2016 /* Is this another window which has a Xdnd selection and not our proxy window? */
2017 if ( wndSelection
2018 && wndSelection != m_wndCur)
2019 {
2020 char *pszWndName = wndX11GetNameA(wndSelection);
2021 AssertPtr(pszWndName);
2022 logInfo("New guest source window %#x ('%s')\n", wndSelection, pszWndName);
2023
2024 /* Start over. */
2025 reset();
2026
2027 /* Map the window on the current cursor position, which should provoke
2028 * an XdndEnter event. */
2029 rc = proxyWinShow();
2030 if (RT_SUCCESS(rc))
2031 {
2032 rc = mouseCursorFakeMove();
2033 if (RT_SUCCESS(rc))
2034 {
2035 bool fWaitFailed = false; /* Waiting for status changed failed? */
2036
2037 /* Wait until we're in "Dragging" state. */
2038 rc = waitForStatusChange(Dragging, 100 /* 100ms timeout */);
2039
2040 /*
2041 * Note: Don't wait too long here, as this mostly will make
2042 * the drag and drop experience on the host being laggy
2043 * and unresponsive.
2044 *
2045 * Instead, let the host query multiple times with 100ms
2046 * timeout each (see above) and only report an error if
2047 * the overall querying time has been exceeded.<
2048 */
2049 if (RT_SUCCESS(rc))
2050 {
2051 m_enmMode = GH;
2052 }
2053 else if (rc == VERR_TIMEOUT)
2054 {
2055 /** @todo Make m_cFailedPendingAttempts configurable. For slower window managers? */
2056 if (m_cFailedPendingAttempts++ > 50) /* Tolerate up to 5s total (100ms for each slot). */
2057 fWaitFailed = true;
2058 else
2059 rc = VINF_SUCCESS;
2060 }
2061 else if (RT_FAILURE(rc))
2062 fWaitFailed = true;
2063
2064 if (fWaitFailed)
2065 {
2066 logError("Error mapping proxy window to guest source window %#x ('%s'), rc=%Rrc\n",
2067 wndSelection, pszWndName, rc);
2068
2069 /* Reset the counter in any case. */
2070 m_cFailedPendingAttempts = 0;
2071 }
2072 }
2073 }
2074
2075 RTStrFree(pszWndName);
2076 }
2077 }
2078
2079 /*
2080 * Acknowledge to the host in any case, regardless
2081 * if something failed here or not. Be responsive.
2082 */
2083
2084 int rc2 = RTCritSectEnter(&m_dataCS);
2085 if (RT_SUCCESS(rc2))
2086 {
2087 RTCString strFormatsCur = gX11->xAtomListToString(m_lstFormats);
2088 if (!strFormatsCur.isEmpty())
2089 {
2090 strFormats = strFormatsCur;
2091 uDefAction = DND_COPY_ACTION; /** @todo Handle default action! */
2092 uAllActions = DND_COPY_ACTION; /** @todo Ditto. */
2093 uAllActions |= toHGCMActions(m_lstActions);
2094 }
2095
2096 RTCritSectLeave(&m_dataCS);
2097 }
2098
2099 rc2 = VbglR3DnDGHSendAckPending(&m_dndCtx, uDefAction, uAllActions,
2100 strFormats.c_str(), strFormats.length() + 1 /* Include termination */);
2101 LogFlowThisFunc(("uClientID=%RU32, uDefAction=0x%x, allActions=0x%x, strFormats=%s, rc=%Rrc\n",
2102 m_dndCtx.uClientID, uDefAction, uAllActions, strFormats.c_str(), rc2));
2103 if (RT_FAILURE(rc2))
2104 {
2105 logError("Error reporting pending drag and drop operation status to host: %Rrc\n", rc2);
2106 if (RT_SUCCESS(rc))
2107 rc = rc2;
2108 }
2109
2110 LogFlowFuncLeaveRC(rc);
2111 return rc;
2112}
2113
2114/**
2115 * Guest -> Host: Event signalling that the host has dropped the item(s) on the
2116 * host side.
2117 *
2118 * @returns IPRT status code.
2119 * @param strFormat Requested format to send to the host.
2120 * @param uAction Requested action to perform on the guest.
2121 */
2122int DragInstance::ghDropped(const RTCString &strFormat, uint32_t uAction)
2123{
2124 LogFlowThisFunc(("mode=%RU32, state=%RU32, strFormat=%s, uAction=%RU32\n",
2125 m_enmMode, m_enmState, strFormat.c_str(), uAction));
2126
2127 /* Currently in wrong mode? Bail out. */
2128 if ( m_enmMode == Unknown
2129 || m_enmMode == HG)
2130 {
2131 return VERR_INVALID_STATE;
2132 }
2133
2134 if ( m_enmMode == GH
2135 && m_enmState != Dragging)
2136 {
2137 return VERR_INVALID_STATE;
2138 }
2139
2140 int rc = VINF_SUCCESS;
2141
2142 m_enmState = Dropped;
2143
2144#ifdef DEBUG
2145 XWindowAttributes xwa;
2146 XGetWindowAttributes(m_pDisplay, m_wndCur, &xwa);
2147 LogFlowThisFunc(("wndProxy=%#x, wndCur=%#x, x=%d, y=%d, width=%d, height=%d\n",
2148 m_wndProxy.hWnd, m_wndCur, xwa.x, xwa.y, xwa.width, xwa.height));
2149
2150 Window wndSelection = XGetSelectionOwner(m_pDisplay, xAtom(XA_XdndSelection));
2151 LogFlowThisFunc(("wndSelection=%#x\n", wndSelection));
2152#endif
2153
2154 /* We send a fake mouse move event to the current window, cause
2155 * this should have the grab. */
2156 mouseCursorFakeMove();
2157
2158 /**
2159 * The fake button release event above should lead to a XdndDrop event from the
2160 * source window. Because of showing our proxy window, other Xdnd events can
2161 * occur before, e.g. a XdndPosition event. We are not interested
2162 * in those, so just try to get the right one.
2163 */
2164
2165 XClientMessageEvent evDnDDrop;
2166 bool fDrop = waitForX11ClientMsg(evDnDDrop, xAtom(XA_XdndDrop), 5 * 1000 /* 5s timeout */);
2167 if (fDrop)
2168 {
2169 LogFlowThisFunc(("XA_XdndDrop\n"));
2170
2171 /* Request to convert the selection in the specific format and
2172 * place it to our proxy window as property. */
2173 Assert(evDnDDrop.message_type == xAtom(XA_XdndDrop));
2174
2175 Window wndSource = evDnDDrop.data.l[XdndDropWindow]; /* Source window which has sent the message. */
2176 Assert(wndSource == m_wndCur);
2177
2178 Atom aFormat = gX11->stringToxAtom(strFormat.c_str());
2179
2180 Time tsDrop;
2181 if (m_curVer >= 1)
2182 tsDrop = evDnDDrop.data.l[XdndDropTimeStamp];
2183 else
2184 tsDrop = CurrentTime;
2185
2186 XConvertSelection(m_pDisplay, xAtom(XA_XdndSelection), aFormat, xAtom(XA_XdndSelection),
2187 m_wndProxy.hWnd, tsDrop);
2188
2189 /* Wait for the selection notify event. */
2190 XEvent evSelNotify;
2191 RT_ZERO(evSelNotify);
2192 if (waitForX11Msg(evSelNotify, SelectionNotify, 5 * 1000 /* 5s timeout */))
2193 {
2194 bool fCancel = false;
2195
2196 /* Make some paranoid checks. */
2197 if ( evSelNotify.xselection.type == SelectionNotify
2198 && evSelNotify.xselection.display == m_pDisplay
2199 && evSelNotify.xselection.selection == xAtom(XA_XdndSelection)
2200 && evSelNotify.xselection.requestor == m_wndProxy.hWnd
2201 && evSelNotify.xselection.target == aFormat)
2202 {
2203 LogFlowThisFunc(("Selection notfiy (from wnd=%#x)\n", m_wndCur));
2204
2205 Atom aPropType;
2206 int iPropFormat;
2207 unsigned long cItems, cbRemaining;
2208 unsigned char *pcData = NULL;
2209 int xRc = XGetWindowProperty(m_pDisplay, m_wndProxy.hWnd,
2210 xAtom(XA_XdndSelection) /* Property */,
2211 0 /* Offset */,
2212 VBOX_MAX_XPROPERTIES /* Length of 32-bit multiples */,
2213 True /* Delete property? */,
2214 AnyPropertyType, /* Property type */
2215 &aPropType, &iPropFormat, &cItems, &cbRemaining, &pcData);
2216 if (xRc != Success)
2217 logError("Error getting XA_XdndSelection property of proxy window=%#x: %s\n",
2218 m_wndProxy.hWnd, gX11->xErrorToString(xRc).c_str());
2219
2220 LogFlowThisFunc(("strType=%s, iPropFormat=%d, cItems=%RU32, cbRemaining=%RU32\n",
2221 gX11->xAtomToString(aPropType).c_str(), iPropFormat, cItems, cbRemaining));
2222
2223 if ( aPropType != None
2224 && pcData != NULL
2225 && iPropFormat >= 8
2226 && cItems > 0
2227 && cbRemaining == 0)
2228 {
2229 size_t cbData = cItems * (iPropFormat / 8);
2230 LogFlowThisFunc(("cbData=%zu\n", cbData));
2231
2232 /* For whatever reason some of the string MIME types are not
2233 * zero terminated. Check that and correct it when necessary,
2234 * because the guest side wants this in any case. */
2235 if ( m_lstAllowedFormats.contains(strFormat)
2236 && pcData[cbData - 1] != '\0')
2237 {
2238 unsigned char *pvDataTmp = static_cast<unsigned char*>(RTMemAlloc(cbData + 1));
2239 if (pvDataTmp)
2240 {
2241 memcpy(pvDataTmp, pcData, cbData);
2242 pvDataTmp[cbData++] = '\0';
2243
2244 rc = VbglR3DnDGHSendData(&m_dndCtx, strFormat.c_str(), pvDataTmp, cbData);
2245 RTMemFree(pvDataTmp);
2246 }
2247 else
2248 rc = VERR_NO_MEMORY;
2249 }
2250 else
2251 {
2252 /* Send the raw data to the host. */
2253 rc = VbglR3DnDGHSendData(&m_dndCtx, strFormat.c_str(), pcData, cbData);
2254 LogFlowThisFunc(("Sent strFormat=%s, rc=%Rrc\n", strFormat.c_str(), rc));
2255 }
2256
2257 if (RT_SUCCESS(rc))
2258 {
2259 rc = m_wndProxy.sendFinished(wndSource, uAction);
2260 }
2261 else
2262 fCancel = true;
2263 }
2264 else
2265 {
2266 if (aPropType == xAtom(XA_INCR))
2267 {
2268 /** @todo Support incremental transfers. */
2269 AssertMsgFailed(("Incremental transfers are not supported yet\n"));
2270
2271 logError("Incremental transfers are not supported yet\n");
2272 rc = VERR_NOT_IMPLEMENTED;
2273 }
2274 else
2275 {
2276 logError("Not supported data type: %s\n", gX11->xAtomToString(aPropType).c_str());
2277 rc = VERR_NOT_SUPPORTED;
2278 }
2279
2280 fCancel = true;
2281 }
2282
2283 if (fCancel)
2284 {
2285 logInfo("Cancelling dropping to host\n");
2286
2287 /* Cancel the operation -- inform the source window by
2288 * sending a XdndFinished message so that the source can toss the required data. */
2289 rc = m_wndProxy.sendFinished(wndSource, DND_IGNORE_ACTION);
2290 }
2291
2292 /* Cleanup. */
2293 if (pcData)
2294 XFree(pcData);
2295 }
2296 else
2297 rc = VERR_INVALID_PARAMETER;
2298 }
2299 else
2300 rc = VERR_TIMEOUT;
2301 }
2302 else
2303 rc = VERR_TIMEOUT;
2304
2305 /* Inform the host on error. */
2306 if (RT_FAILURE(rc))
2307 {
2308 int rc2 = VbglR3DnDGHSendError(&m_dndCtx, rc);
2309 LogFlowThisFunc(("Sending error to host resulted in %Rrc\n", rc2)); NOREF(rc2);
2310 /* This is not fatal for us, just ignore. */
2311 }
2312
2313 /* At this point, we have either successfully transfered any data or not.
2314 * So reset our internal state because we are done here for the current (ongoing)
2315 * drag and drop operation. */
2316 reset();
2317
2318 LogFlowFuncLeaveRC(rc);
2319 return rc;
2320}
2321#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
2322
2323/*
2324 * Helpers
2325 */
2326
2327/**
2328 * Fakes moving the mouse cursor to provoke various drag and drop
2329 * events such as entering a target window or moving within a
2330 * source window.
2331 *
2332 * Not the most elegant and probably correct function, but does
2333 * the work for now.
2334 *
2335 * @returns IPRT status code.
2336 */
2337int DragInstance::mouseCursorFakeMove(void) const
2338{
2339 int iScreenID = XDefaultScreen(m_pDisplay);
2340 /** @todo What about multiple screens? Test this! */
2341
2342 const int iScrX = XDisplayWidth(m_pDisplay, iScreenID);
2343 const int iScrY = XDisplayHeight(m_pDisplay, iScreenID);
2344
2345 int fx, fy, rx, ry;
2346 Window wndTemp, wndChild;
2347 int wx, wy; unsigned int mask;
2348 XQueryPointer(m_pDisplay, m_wndRoot, &wndTemp, &wndChild, &rx, &ry, &wx, &wy, &mask);
2349
2350 /*
2351 * Apply some simple clipping and change the position slightly.
2352 */
2353
2354 /* FakeX */
2355 if (rx == 0) fx = 1;
2356 else if (rx == iScrX) fx = iScrX - 1;
2357 else fx = rx + 1;
2358
2359 /* FakeY */
2360 if (ry == 0) fy = 1;
2361 else if (ry == iScrY) fy = iScrY - 1;
2362 else fy = ry + 1;
2363
2364 /*
2365 * Move the cursor to trigger the wanted events.
2366 */
2367 LogFlowThisFunc(("cursorRootX=%d, cursorRootY=%d\n", fx, fy));
2368 int rc = mouseCursorMove(fx, fy);
2369 if (RT_SUCCESS(rc))
2370 {
2371 /* Move the cursor back to its original position. */
2372 rc = mouseCursorMove(rx, ry);
2373 }
2374
2375 return rc;
2376}
2377
2378/**
2379 * Moves the mouse pointer to a specific position.
2380 *
2381 * @returns IPRT status code.
2382 * @param iPosX Absolute X coordinate.
2383 * @param iPosY Absolute Y coordinate.
2384 */
2385int DragInstance::mouseCursorMove(int iPosX, int iPosY) const
2386{
2387 int iScreenID = XDefaultScreen(m_pDisplay);
2388 /** @todo What about multiple screens? Test this! */
2389
2390 const int iScrX = XDisplayWidth(m_pDisplay, iScreenID);
2391 const int iScrY = XDisplayHeight(m_pDisplay, iScreenID);
2392
2393 iPosX = RT_CLAMP(iPosX, 0, iScrX);
2394 iPosY = RT_CLAMP(iPosY, 0, iScrY);
2395
2396 LogFlowThisFunc(("iPosX=%d, iPosY=%d\n", iPosX, iPosY));
2397
2398 /* Move the guest pointer to the DnD position, so we can find the window
2399 * below that position. */
2400 XWarpPointer(m_pDisplay, None, m_wndRoot, 0, 0, 0, 0, iPosX, iPosY);
2401 return VINF_SUCCESS;
2402}
2403
2404/**
2405 * Sends a mouse button event to a specific window.
2406 *
2407 * @param wndDest Window to send the mouse button event to.
2408 * @param rx X coordinate relative to the root window's origin.
2409 * @param ry Y coordinate relative to the root window's origin.
2410 * @param iButton Mouse button to press/release.
2411 * @param fPress Whether to press or release the mouse button.
2412 */
2413void DragInstance::mouseButtonSet(Window wndDest, int rx, int ry, int iButton, bool fPress)
2414{
2415 LogFlowThisFunc(("wndDest=%#x, rx=%d, ry=%d, iBtn=%d, fPress=%RTbool\n",
2416 wndDest, rx, ry, iButton, fPress));
2417
2418#ifdef VBOX_DND_WITH_XTEST
2419 /** @todo Make this check run only once. */
2420 int ev, er, ma, mi;
2421 if (XTestQueryExtension(m_pDisplay, &ev, &er, &ma, &mi))
2422 {
2423 LogFlowThisFunc(("XText extension available\n"));
2424
2425 int xRc = XTestFakeButtonEvent(m_pDisplay, 1, fPress ? True : False, CurrentTime);
2426 if (Rc == 0)
2427 logError("Error sending XTestFakeButtonEvent event: %s\n", gX11->xErrorToString(xRc).c_str());
2428 XFlush(m_pDisplay);
2429 }
2430 else
2431 {
2432#endif
2433 LogFlowThisFunc(("Note: XText extension not available or disabled\n"));
2434
2435 unsigned int mask = 0;
2436
2437 if ( rx == -1
2438 && ry == -1)
2439 {
2440 Window wndRoot, wndChild;
2441 int wx, wy;
2442 XQueryPointer(m_pDisplay, m_wndRoot, &wndRoot, &wndChild, &rx, &ry, &wx, &wy, &mask);
2443 LogFlowThisFunc(("Mouse pointer is at root x=%d, y=%d\n", rx, ry));
2444 }
2445
2446 XButtonEvent eBtn;
2447 RT_ZERO(eBtn);
2448
2449 eBtn.display = m_pDisplay;
2450 eBtn.root = m_wndRoot;
2451 eBtn.window = wndDest;
2452 eBtn.subwindow = None;
2453 eBtn.same_screen = True;
2454 eBtn.time = CurrentTime;
2455 eBtn.button = iButton;
2456 eBtn.state = mask | (iButton == 1 ? Button1MotionMask :
2457 iButton == 2 ? Button2MotionMask :
2458 iButton == 3 ? Button3MotionMask :
2459 iButton == 4 ? Button4MotionMask :
2460 iButton == 5 ? Button5MotionMask : 0);
2461 eBtn.type = fPress ? ButtonPress : ButtonRelease;
2462 eBtn.send_event = False;
2463 eBtn.x_root = rx;
2464 eBtn.y_root = ry;
2465
2466 XTranslateCoordinates(m_pDisplay, eBtn.root, eBtn.window, eBtn.x_root, eBtn.y_root, &eBtn.x, &eBtn.y, &eBtn.subwindow);
2467 LogFlowThisFunc(("state=0x%x, x=%d, y=%d\n", eBtn.state, eBtn.x, eBtn.y));
2468
2469 int xRc = XSendEvent(m_pDisplay, wndDest, True /* fPropagate */,
2470 ButtonPressMask,
2471 reinterpret_cast<XEvent*>(&eBtn));
2472 if (xRc == 0)
2473 logError("Error sending XButtonEvent event to window=%#x: %s\n", wndDest, gX11->xErrorToString(xRc).c_str());
2474
2475 XFlush(m_pDisplay);
2476
2477#ifdef VBOX_DND_WITH_XTEST
2478 }
2479#endif
2480}
2481
2482/**
2483 * Shows the (invisible) proxy window. The proxy window is needed for intercepting
2484 * drags from the host to the guest or from the guest to the host. It acts as a proxy
2485 * between the host and the actual (UI) element on the guest OS.
2486 *
2487 * To not make it miss any actions this window gets spawned across the entire guest
2488 * screen (think of an umbrella) to (hopefully) capture everything. A proxy window
2489 * which follows the cursor would be far too slow here.
2490 *
2491 * @returns IPRT status code.
2492 * @param piRootX X coordinate relative to the root window's origin. Optional.
2493 * @param piRootY Y coordinate relative to the root window's origin. Optional.
2494 */
2495int DragInstance::proxyWinShow(int *piRootX /* = NULL */, int *piRootY /* = NULL */) const
2496{
2497 /* piRootX is optional. */
2498 /* piRootY is optional. */
2499
2500 LogFlowThisFuncEnter();
2501
2502 int rc = VINF_SUCCESS;
2503
2504#if 0
2505# ifdef VBOX_DND_WITH_XTEST
2506 XTestGrabControl(m_pDisplay, False);
2507# endif
2508#endif
2509
2510 /* Get the mouse pointer position and determine if we're on the same screen as the root window
2511 * and return the current child window beneath our mouse pointer, if any. */
2512 int iRootX, iRootY;
2513 int iChildX, iChildY;
2514 unsigned int iMask;
2515 Window wndRoot, wndChild;
2516 Bool fInRootWnd = XQueryPointer(m_pDisplay, m_wndRoot, &wndRoot, &wndChild,
2517 &iRootX, &iRootY, &iChildX, &iChildY, &iMask);
2518
2519 LogFlowThisFunc(("fInRootWnd=%RTbool, wndRoot=0x%x, wndChild=0x%x, iRootX=%d, iRootY=%d\n",
2520 RT_BOOL(fInRootWnd), wndRoot, wndChild, iRootX, iRootY)); NOREF(fInRootWnd);
2521
2522 if (piRootX)
2523 *piRootX = iRootX;
2524 if (piRootY)
2525 *piRootY = iRootY;
2526
2527 XSynchronize(m_pDisplay, True /* Enable sync */);
2528
2529 /* Bring our proxy window into foreground. */
2530 XMapWindow(m_pDisplay, m_wndProxy.hWnd);
2531 XRaiseWindow(m_pDisplay, m_wndProxy.hWnd);
2532
2533 /* Spawn our proxy window over the entire screen, making it an easy drop target for the host's cursor. */
2534 LogFlowThisFunc(("Proxy window x=%d, y=%d, width=%d, height=%d\n",
2535 m_wndProxy.iX, m_wndProxy.iY, m_wndProxy.iWidth, m_wndProxy.iHeight));
2536 XMoveResizeWindow(m_pDisplay, m_wndProxy.hWnd, m_wndProxy.iX, m_wndProxy.iY, m_wndProxy.iWidth, m_wndProxy.iHeight);
2537
2538 XFlush(m_pDisplay);
2539
2540 XSynchronize(m_pDisplay, False /* Disable sync */);
2541
2542#if 0
2543# ifdef VBOX_DND_WITH_XTEST
2544 XTestGrabControl(m_pDisplay, True);
2545# endif
2546#endif
2547
2548 LogFlowFuncLeaveRC(rc);
2549 return rc;
2550}
2551
2552/**
2553 * Hides the (invisible) proxy window.
2554 */
2555int DragInstance::proxyWinHide(void)
2556{
2557 LogFlowFuncEnter();
2558
2559 XUnmapWindow(m_pDisplay, m_wndProxy.hWnd);
2560 XFlush(m_pDisplay);
2561
2562 m_eventQueueList.clear();
2563
2564 return VINF_SUCCESS; /** @todo Add error checking. */
2565}
2566
2567/**
2568 * Allocates the name (title) of an X window.
2569 * The returned pointer must be freed using RTStrFree().
2570 *
2571 * @returns Pointer to the allocated window name.
2572 * @param wndThis Window to retrieve name for.
2573 *
2574 * @remark If the window title is not available, the text
2575 * "<No name>" will be returned.
2576 */
2577char *DragInstance::wndX11GetNameA(Window wndThis) const
2578{
2579 char *pszName = NULL;
2580
2581 XTextProperty propName;
2582 if (XGetWMName(m_pDisplay, wndThis, &propName))
2583 {
2584 if (propName.value)
2585 pszName = RTStrDup((char *)propName.value); /** @todo UTF8? */
2586 XFree(propName.value);
2587 }
2588
2589 if (!pszName) /* No window name found? */
2590 pszName = RTStrDup("<No name>");
2591
2592 return pszName;
2593}
2594
2595/**
2596 * Clear a window's supported/accepted actions list.
2597 *
2598 * @param wndThis Window to clear the list for.
2599 */
2600void DragInstance::wndXDnDClearActionList(Window wndThis) const
2601{
2602 XDeleteProperty(m_pDisplay, wndThis, xAtom(XA_XdndActionList));
2603}
2604
2605/**
2606 * Clear a window's supported/accepted formats list.
2607 *
2608 * @param wndThis Window to clear the list for.
2609 */
2610void DragInstance::wndXDnDClearFormatList(Window wndThis) const
2611{
2612 XDeleteProperty(m_pDisplay, wndThis, xAtom(XA_XdndTypeList));
2613}
2614
2615/**
2616 * Retrieves a window's supported/accepted XDnD actions.
2617 *
2618 * @returns IPRT status code.
2619 * @param wndThis Window to retrieve the XDnD actions for.
2620 * @param lstActions Reference to VBoxDnDAtomList to store the action into.
2621 */
2622int DragInstance::wndXDnDGetActionList(Window wndThis, VBoxDnDAtomList &lstActions) const
2623{
2624 Atom iActType = None;
2625 int iActFmt;
2626 unsigned long cItems, cbData;
2627 unsigned char *pcbData = NULL;
2628
2629 /* Fetch the possible list of actions, if this property is set. */
2630 int xRc = XGetWindowProperty(m_pDisplay, wndThis,
2631 xAtom(XA_XdndActionList),
2632 0, VBOX_MAX_XPROPERTIES,
2633 False, XA_ATOM, &iActType, &iActFmt, &cItems, &cbData, &pcbData);
2634 if (xRc != Success)
2635 {
2636 LogFlowThisFunc(("Error getting XA_XdndActionList atoms from window=%#x: %s\n",
2637 wndThis, gX11->xErrorToString(xRc).c_str()));
2638 return VERR_NOT_FOUND;
2639 }
2640
2641 LogFlowThisFunc(("wndThis=%#x, cItems=%RU32, pcbData=%p\n", wndThis, cItems, pcbData));
2642
2643 if (cItems > 0)
2644 {
2645 AssertPtr(pcbData);
2646 Atom *paData = reinterpret_cast<Atom *>(pcbData);
2647
2648 for (unsigned i = 0; i < RT_MIN(VBOX_MAX_XPROPERTIES, cItems); i++)
2649 {
2650 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(paData[i]).c_str()));
2651 lstActions.append(paData[i]);
2652 }
2653
2654 XFree(pcbData);
2655 }
2656
2657 return VINF_SUCCESS;
2658}
2659
2660/**
2661 * Retrieves a window's supported/accepted XDnD formats.
2662 *
2663 * @returns IPRT status code.
2664 * @param wndThis Window to retrieve the XDnD formats for.
2665 * @param lstTypes Reference to VBoxDnDAtomList to store the formats into.
2666 */
2667int DragInstance::wndXDnDGetFormatList(Window wndThis, VBoxDnDAtomList &lstTypes) const
2668{
2669 Atom iActType = None;
2670 int iActFmt;
2671 unsigned long cItems, cbData;
2672 unsigned char *pcbData = NULL;
2673
2674 int xRc = XGetWindowProperty(m_pDisplay, wndThis,
2675 xAtom(XA_XdndTypeList),
2676 0, VBOX_MAX_XPROPERTIES,
2677 False, XA_ATOM, &iActType, &iActFmt, &cItems, &cbData, &pcbData);
2678 if (xRc != Success)
2679 {
2680 LogFlowThisFunc(("Error getting XA_XdndTypeList atoms from window=%#x: %s\n",
2681 wndThis, gX11->xErrorToString(xRc).c_str()));
2682 return VERR_NOT_FOUND;
2683 }
2684
2685 LogFlowThisFunc(("wndThis=%#x, cItems=%RU32, pcbData=%p\n", wndThis, cItems, pcbData));
2686
2687 if (cItems > 0)
2688 {
2689 AssertPtr(pcbData);
2690 Atom *paData = reinterpret_cast<Atom *>(pcbData);
2691
2692 for (unsigned i = 0; i < RT_MIN(VBOX_MAX_XPROPERTIES, cItems); i++)
2693 {
2694 LogFlowThisFunc(("\t%s\n", gX11->xAtomToString(paData[i]).c_str()));
2695 lstTypes.append(paData[i]);
2696 }
2697
2698 XFree(pcbData);
2699 }
2700
2701 return VINF_SUCCESS;
2702}
2703
2704/**
2705 * Sets (replaces) a window's XDnD accepted/allowed actions.
2706 *
2707 * @returns IPRT status code.
2708 * @param wndThis Window to set the format list for.
2709 * @param lstActions Reference to list of XDnD actions to set.
2710 *
2711 * @remark
2712 */
2713int DragInstance::wndXDnDSetActionList(Window wndThis, const VBoxDnDAtomList &lstActions) const
2714{
2715 if (lstActions.isEmpty())
2716 return VINF_SUCCESS;
2717
2718 XChangeProperty(m_pDisplay, wndThis,
2719 xAtom(XA_XdndActionList),
2720 XA_ATOM, 32, PropModeReplace,
2721 reinterpret_cast<const unsigned char*>(lstActions.raw()),
2722 lstActions.size());
2723
2724 return VINF_SUCCESS;
2725}
2726
2727/**
2728 * Sets (replaces) a window's XDnD accepted format list.
2729 *
2730 * @returns IPRT status code.
2731 * @param wndThis Window to set the format list for.
2732 * @param atmProp Property to set.
2733 * @param lstFormats Reference to list of XDnD formats to set.
2734 */
2735int DragInstance::wndXDnDSetFormatList(Window wndThis, Atom atmProp, const VBoxDnDAtomList &lstFormats) const
2736{
2737 if (lstFormats.isEmpty())
2738 return VERR_INVALID_PARAMETER;
2739
2740 /* We support TARGETS and the data types. */
2741 VBoxDnDAtomList lstFormatsExt(lstFormats.size() + 1);
2742 lstFormatsExt.append(xAtom(XA_TARGETS));
2743 lstFormatsExt.append(lstFormats);
2744
2745 /* Add the property with the property data to the window. */
2746 XChangeProperty(m_pDisplay, wndThis, atmProp,
2747 XA_ATOM, 32, PropModeReplace,
2748 reinterpret_cast<const unsigned char*>(lstFormatsExt.raw()),
2749 lstFormatsExt.size());
2750
2751 return VINF_SUCCESS;
2752}
2753
2754/**
2755 * Converts a RTCString list to VBoxDnDAtomList list.
2756 *
2757 * @returns IPRT status code.
2758 * @param lstFormats Reference to RTCString list to convert.
2759 * @param lstAtoms Reference to VBoxDnDAtomList list to store results in.
2760 */
2761int DragInstance::toAtomList(const RTCList<RTCString> &lstFormats, VBoxDnDAtomList &lstAtoms) const
2762{
2763 for (size_t i = 0; i < lstFormats.size(); ++i)
2764 lstAtoms.append(XInternAtom(m_pDisplay, lstFormats.at(i).c_str(), False));
2765
2766 return VINF_SUCCESS;
2767}
2768
2769/**
2770 * Converts a raw-data string list to VBoxDnDAtomList list.
2771 *
2772 * @returns IPRT status code.
2773 * @param pvData Pointer to string data to convert.
2774 * @param cbData Size (in bytes) to convert.
2775 * @param lstAtoms Reference to VBoxDnDAtomList list to store results in.
2776 */
2777int DragInstance::toAtomList(const void *pvData, uint32_t cbData, VBoxDnDAtomList &lstAtoms) const
2778{
2779 RT_NOREF1(lstAtoms);
2780 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
2781 AssertReturn(cbData, VERR_INVALID_PARAMETER);
2782
2783 const char *pszStr = (char *)pvData;
2784 uint32_t cbStr = cbData;
2785
2786 int rc = VINF_SUCCESS;
2787
2788 VBoxDnDAtomList lstAtom;
2789 while (cbStr)
2790 {
2791 size_t cbSize = RTStrNLen(pszStr, cbStr);
2792
2793 /* Create a copy with max N chars, so that we are on the save side,
2794 * even if the data isn't zero terminated. */
2795 char *pszTmp = RTStrDupN(pszStr, cbSize);
2796 if (!pszTmp)
2797 {
2798 rc = VERR_NO_MEMORY;
2799 break;
2800 }
2801
2802 lstAtom.append(XInternAtom(m_pDisplay, pszTmp, False));
2803 RTStrFree(pszTmp);
2804
2805 pszStr += cbSize + 1;
2806 cbStr -= cbSize + 1;
2807 }
2808
2809 return rc;
2810}
2811
2812/**
2813 * Converts a HGCM-based drag'n drop action to a Atom-based drag'n drop action.
2814 *
2815 * @returns Converted Atom-based drag'n drop action.
2816 * @param uAction HGCM drag'n drop actions to convert.
2817 */
2818/* static */
2819Atom DragInstance::toAtomAction(uint32_t uAction)
2820{
2821 /* Ignore is None. */
2822 return (isDnDCopyAction(uAction) ? xAtom(XA_XdndActionCopy) :
2823 isDnDMoveAction(uAction) ? xAtom(XA_XdndActionMove) :
2824 isDnDLinkAction(uAction) ? xAtom(XA_XdndActionLink) :
2825 None);
2826}
2827
2828/**
2829 * Converts HGCM-based drag'n drop actions to a VBoxDnDAtomList list.
2830 *
2831 * @returns IPRT status code.
2832 * @param uActions HGCM drag'n drop actions to convert.
2833 * @param lstAtoms Reference to VBoxDnDAtomList to store actions in.
2834 */
2835/* static */
2836int DragInstance::toAtomActions(uint32_t uActions, VBoxDnDAtomList &lstAtoms)
2837{
2838 if (hasDnDCopyAction(uActions))
2839 lstAtoms.append(xAtom(XA_XdndActionCopy));
2840 if (hasDnDMoveAction(uActions))
2841 lstAtoms.append(xAtom(XA_XdndActionMove));
2842 if (hasDnDLinkAction(uActions))
2843 lstAtoms.append(xAtom(XA_XdndActionLink));
2844
2845 return VINF_SUCCESS;
2846}
2847
2848/**
2849 * Converts an Atom-based drag'n drop action to a HGCM drag'n drop action.
2850 *
2851 * @returns HGCM drag'n drop action.
2852 * @param atom Atom-based drag'n drop action to convert.
2853 */
2854/* static */
2855uint32_t DragInstance::toHGCMAction(Atom atom)
2856{
2857 uint32_t uAction = DND_IGNORE_ACTION;
2858
2859 if (atom == xAtom(XA_XdndActionCopy))
2860 uAction = DND_COPY_ACTION;
2861 else if (atom == xAtom(XA_XdndActionMove))
2862 uAction = DND_MOVE_ACTION;
2863 else if (atom == xAtom(XA_XdndActionLink))
2864 uAction = DND_LINK_ACTION;
2865
2866 return uAction;
2867}
2868
2869/**
2870 * Converts an VBoxDnDAtomList list to an HGCM action list.
2871 *
2872 * @returns ORed HGCM action list.
2873 * @param lstActions List of Atom-based actions to convert.
2874 */
2875/* static */
2876uint32_t DragInstance::toHGCMActions(const VBoxDnDAtomList &lstActions)
2877{
2878 uint32_t uActions = DND_IGNORE_ACTION;
2879
2880 for (size_t i = 0; i < lstActions.size(); i++)
2881 uActions |= toHGCMAction(lstActions.at(i));
2882
2883 return uActions;
2884}
2885
2886/*******************************************************************************
2887 * VBoxDnDProxyWnd implementation.
2888 ******************************************************************************/
2889
2890VBoxDnDProxyWnd::VBoxDnDProxyWnd(void)
2891 : pDisp(NULL)
2892 , hWnd(0)
2893 , iX(0)
2894 , iY(0)
2895 , iWidth(0)
2896 , iHeight(0)
2897{
2898
2899}
2900
2901VBoxDnDProxyWnd::~VBoxDnDProxyWnd(void)
2902{
2903 destroy();
2904}
2905
2906int VBoxDnDProxyWnd::init(Display *pDisplay)
2907{
2908 /** @todo What about multiple screens? Test this! */
2909 int iScreenID = XDefaultScreen(pDisplay);
2910
2911 iWidth = XDisplayWidth(pDisplay, iScreenID);
2912 iHeight = XDisplayHeight(pDisplay, iScreenID);
2913 pDisp = pDisplay;
2914
2915 return VINF_SUCCESS;
2916}
2917
2918void VBoxDnDProxyWnd::destroy(void)
2919{
2920
2921}
2922
2923int VBoxDnDProxyWnd::sendFinished(Window hWndSource, uint32_t uAction)
2924{
2925 /* Was the drop accepted by the host? That is, anything than ignoring. */
2926 bool fDropAccepted = uAction > DND_IGNORE_ACTION;
2927
2928 LogFlowFunc(("uAction=%RU32\n", uAction));
2929
2930 /* Confirm the result of the transfer to the target window. */
2931 XClientMessageEvent m;
2932 RT_ZERO(m);
2933 m.type = ClientMessage;
2934 m.display = pDisp;
2935 m.window = hWnd;
2936 m.message_type = xAtom(XA_XdndFinished);
2937 m.format = 32;
2938 m.data.l[XdndFinishedWindow] = hWnd; /* Target window. */
2939 m.data.l[XdndFinishedFlags] = fDropAccepted ? RT_BIT(0) : 0; /* Was the drop accepted? */
2940 m.data.l[XdndFinishedAction] = fDropAccepted ? DragInstance::toAtomAction(uAction) : None; /* Action used on accept. */
2941
2942 int xRc = XSendEvent(pDisp, hWndSource, True, NoEventMask, reinterpret_cast<XEvent*>(&m));
2943 if (xRc == 0)
2944 {
2945 LogRel(("DnD: Error sending XA_XdndFinished event to source window=%#x: %s\n",
2946 hWndSource, gX11->xErrorToString(xRc).c_str()));
2947
2948 return VERR_GENERAL_FAILURE; /** @todo Fudge. */
2949 }
2950
2951 return VINF_SUCCESS;
2952}
2953
2954/*******************************************************************************
2955 * DragAndDropService implementation.
2956 ******************************************************************************/
2957
2958/**
2959 * Initializes the drag and drop service.
2960 *
2961 * @returns IPRT status code.
2962 */
2963int DragAndDropService::init(void)
2964{
2965 LogFlowFuncEnter();
2966
2967 /* Initialise the guest library. */
2968 int rc = VbglR3InitUser();
2969 if (RT_FAILURE(rc))
2970 {
2971 VBClFatalError(("DnD: Failed to connect to the VirtualBox kernel service, rc=%Rrc\n", rc));
2972 return rc;
2973 }
2974
2975 /* Connect to the x11 server. */
2976 m_pDisplay = XOpenDisplay(NULL);
2977 if (!m_pDisplay)
2978 {
2979 VBClFatalError(("DnD: Unable to connect to X server -- running in a terminal session?\n"));
2980 return VERR_NOT_FOUND;
2981 }
2982
2983 xHelpers *pHelpers = xHelpers::getInstance(m_pDisplay);
2984 if (!pHelpers)
2985 return VERR_NO_MEMORY;
2986
2987 do
2988 {
2989 rc = RTSemEventCreate(&m_hEventSem);
2990 if (RT_FAILURE(rc))
2991 break;
2992
2993 rc = RTCritSectInit(&m_eventQueueCS);
2994 if (RT_FAILURE(rc))
2995 break;
2996
2997 /* Event thread for events coming from the HGCM device. */
2998 rc = RTThreadCreate(&m_hHGCMThread, hgcmEventThread, this,
2999 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE, "dndHGCM");
3000 if (RT_FAILURE(rc))
3001 break;
3002
3003 rc = RTThreadUserWait(m_hHGCMThread, 10 * 1000 /* 10s timeout */);
3004 if (RT_FAILURE(rc))
3005 break;
3006
3007 if (ASMAtomicReadBool(&m_fSrvStopping))
3008 break;
3009
3010 /* Event thread for events coming from the x11 system. */
3011 rc = RTThreadCreate(&m_hX11Thread, x11EventThread, this,
3012 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE, "dndX11");
3013 if (RT_FAILURE(rc))
3014 break;
3015
3016 rc = RTThreadUserWait(m_hX11Thread, 10 * 1000 /* 10s timeout */);
3017 if (RT_FAILURE(rc))
3018 break;
3019
3020 if (ASMAtomicReadBool(&m_fSrvStopping))
3021 break;
3022
3023 } while (0);
3024
3025 if (m_fSrvStopping)
3026 rc = VERR_GENERAL_FAILURE; /** @todo Fudge! */
3027
3028 if (RT_FAILURE(rc))
3029 LogRel(("DnD: Failed to initialize, rc=%Rrc\n", rc));
3030
3031 LogFlowFuncLeaveRC(rc);
3032 return rc;
3033}
3034
3035/**
3036 * Main loop for the drag and drop service which does the HGCM message
3037 * processing and routing to the according drag and drop instance(s).
3038 *
3039 * @returns IPRT status code.
3040 * @param fDaemonised Whether to run in daemonized or not. Does not
3041 * apply for this service.
3042 */
3043int DragAndDropService::run(bool fDaemonised /* = false */)
3044{
3045 RT_NOREF1(fDaemonised);
3046 LogFlowThisFunc(("fDaemonised=%RTbool\n", fDaemonised));
3047
3048 int rc;
3049 do
3050 {
3051 m_pCurDnD = new DragInstance(m_pDisplay, this);
3052 if (!m_pCurDnD)
3053 {
3054 rc = VERR_NO_MEMORY;
3055 break;
3056 }
3057
3058 /* Note: For multiple screen support in VBox it is not necessary to use
3059 * another screen number than zero. Maybe in the future it will become
3060 * necessary if VBox supports multiple X11 screens. */
3061 rc = m_pCurDnD->init(0 /* uScreenID */);
3062 /* Note: Can return VINF_PERMISSION_DENIED if HGCM host service is not available. */
3063 if (rc != VINF_SUCCESS)
3064 {
3065 if (RT_FAILURE(rc))
3066 LogRel(("DnD: Unable to connect to drag and drop service, rc=%Rrc\n", rc));
3067 else if (rc == VINF_PERMISSION_DENIED)
3068 LogRel(("DnD: Not available on host, terminating\n"));
3069 break;
3070 }
3071
3072 LogRel(("DnD: Started\n"));
3073 LogRel2(("DnD: %sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr()));
3074
3075 /* Enter the main event processing loop. */
3076 do
3077 {
3078 DnDEvent e;
3079 RT_ZERO(e);
3080
3081 LogFlowFunc(("Waiting for new event ...\n"));
3082 rc = RTSemEventWait(m_hEventSem, RT_INDEFINITE_WAIT);
3083 if (RT_FAILURE(rc))
3084 break;
3085
3086 AssertMsg(m_eventQueue.size(),
3087 ("Event queue is empty when it shouldn't\n"));
3088
3089 e = m_eventQueue.first();
3090 m_eventQueue.removeFirst();
3091
3092 if (e.type == DnDEvent::HGCM_Type)
3093 {
3094 LogFlowThisFunc(("HGCM event, type=%RU32\n", e.hgcm.uType));
3095 switch (e.hgcm.uType)
3096 {
3097 case DragAndDropSvc::HOST_DND_HG_EVT_ENTER:
3098 {
3099 if (e.hgcm.cbFormats)
3100 {
3101 RTCList<RTCString> lstFormats = RTCString(e.hgcm.pszFormats, e.hgcm.cbFormats - 1).split("\r\n");
3102 rc = m_pCurDnD->hgEnter(lstFormats, e.hgcm.u.a.uAllActions);
3103 /* Enter is always followed by a move event. */
3104 }
3105 else
3106 {
3107 rc = VERR_INVALID_PARAMETER;
3108 break;
3109 }
3110 /* Not breaking unconditionally is intentional. See comment above. */
3111 }
3112 /* fall thru */
3113 case DragAndDropSvc::HOST_DND_HG_EVT_MOVE:
3114 {
3115 rc = m_pCurDnD->hgMove(e.hgcm.u.a.uXpos, e.hgcm.u.a.uYpos, e.hgcm.u.a.uDefAction);
3116 break;
3117 }
3118 case DragAndDropSvc::HOST_DND_HG_EVT_LEAVE:
3119 {
3120 rc = m_pCurDnD->hgLeave();
3121 break;
3122 }
3123 case DragAndDropSvc::HOST_DND_HG_EVT_DROPPED:
3124 {
3125 rc = m_pCurDnD->hgDrop(e.hgcm.u.a.uXpos, e.hgcm.u.a.uYpos, e.hgcm.u.a.uDefAction);
3126 break;
3127 }
3128 case DragAndDropSvc::HOST_DND_HG_SND_DATA:
3129 {
3130 rc = m_pCurDnD->hgDataReceived(e.hgcm.u.b.pvData, e.hgcm.u.b.cbData);
3131 break;
3132 }
3133#ifdef VBOX_WITH_DRAG_AND_DROP_GH
3134 case DragAndDropSvc::HOST_DND_GH_REQ_PENDING:
3135 {
3136 rc = m_pCurDnD->ghIsDnDPending();
3137 break;
3138 }
3139 case DragAndDropSvc::HOST_DND_GH_EVT_DROPPED:
3140 {
3141 rc = m_pCurDnD->ghDropped(e.hgcm.pszFormats, e.hgcm.u.a.uDefAction);
3142 break;
3143 }
3144#endif
3145 default:
3146 {
3147 m_pCurDnD->logError("Received unsupported message: %RU32\n", e.hgcm.uType);
3148 rc = VERR_NOT_SUPPORTED;
3149 break;
3150 }
3151 }
3152
3153 LogFlowFunc(("Message %RU32 processed with %Rrc\n", e.hgcm.uType, rc));
3154 if (RT_FAILURE(rc))
3155 {
3156 /* Tell the user. */
3157 m_pCurDnD->logError("Error processing message %RU32, failed with %Rrc, resetting all\n", e.hgcm.uType, rc);
3158
3159 /* If anything went wrong, do a reset and start over. */
3160 m_pCurDnD->reset();
3161 }
3162
3163 /* Some messages require cleanup. */
3164 switch (e.hgcm.uType)
3165 {
3166 case DragAndDropSvc::HOST_DND_HG_EVT_ENTER:
3167 case DragAndDropSvc::HOST_DND_HG_EVT_MOVE:
3168 case DragAndDropSvc::HOST_DND_HG_EVT_DROPPED:
3169#ifdef VBOX_WITH_DRAG_AND_DROP_GH
3170 case DragAndDropSvc::HOST_DND_GH_EVT_DROPPED:
3171#endif
3172 {
3173 if (e.hgcm.pszFormats)
3174 RTMemFree(e.hgcm.pszFormats);
3175 break;
3176 }
3177
3178 case DragAndDropSvc::HOST_DND_HG_SND_DATA:
3179 {
3180 if (e.hgcm.pszFormats)
3181 RTMemFree(e.hgcm.pszFormats);
3182 if (e.hgcm.u.b.pvData)
3183 RTMemFree(e.hgcm.u.b.pvData);
3184 break;
3185 }
3186
3187 default:
3188 break;
3189 }
3190 }
3191 else if (e.type == DnDEvent::X11_Type)
3192 {
3193 m_pCurDnD->onX11Event(e.x11);
3194 }
3195 else
3196 AssertMsgFailed(("Unknown event queue type %d\n", e.type));
3197
3198 /*
3199 * Make sure that any X11 requests have actually been sent to the
3200 * server, since we are waiting for responses using poll() on
3201 * another thread which will not automatically trigger flushing.
3202 */
3203 XFlush(m_pDisplay);
3204
3205 } while (!ASMAtomicReadBool(&m_fSrvStopping));
3206
3207 LogRel(("DnD: Stopped with rc=%Rrc\n", rc));
3208
3209 } while (0);
3210
3211 if (m_pCurDnD)
3212 {
3213 delete m_pCurDnD;
3214 m_pCurDnD = NULL;
3215 }
3216
3217 LogFlowFuncLeaveRC(rc);
3218 return rc;
3219}
3220
3221void DragAndDropService::cleanup(void)
3222{
3223 LogFlowFuncEnter();
3224
3225 LogRel2(("DnD: Terminating threads ...\n"));
3226
3227 ASMAtomicXchgBool(&m_fSrvStopping, true);
3228
3229 /*
3230 * Wait for threads to terminate.
3231 */
3232 int rcThread, rc2;
3233 if (m_hHGCMThread != NIL_RTTHREAD)
3234 {
3235#if 0 /** @todo Does not work because we don't cancel the HGCM call! */
3236 rc2 = RTThreadWait(m_hHGCMThread, 30 * 1000 /* 30s timeout */, &rcThread);
3237#else
3238 rc2 = RTThreadWait(m_hHGCMThread, 200 /* 200ms timeout */, &rcThread);
3239#endif
3240 if (RT_SUCCESS(rc2))
3241 rc2 = rcThread;
3242
3243 if (RT_FAILURE(rc2))
3244 LogRel(("DnD: Error waiting for HGCM thread to terminate: %Rrc\n", rc2));
3245 }
3246
3247 if (m_hX11Thread != NIL_RTTHREAD)
3248 {
3249#if 0
3250 rc2 = RTThreadWait(m_hX11Thread, 30 * 1000 /* 30s timeout */, &rcThread);
3251#else
3252 rc2 = RTThreadWait(m_hX11Thread, 200 /* 200ms timeout */, &rcThread);
3253#endif
3254 if (RT_SUCCESS(rc2))
3255 rc2 = rcThread;
3256
3257 if (RT_FAILURE(rc2))
3258 LogRel(("DnD: Error waiting for X11 thread to terminate: %Rrc\n", rc2));
3259 }
3260
3261 LogRel2(("DnD: Terminating threads done\n"));
3262
3263 xHelpers::destroyInstance();
3264
3265 VbglR3Term();
3266}
3267
3268/**
3269 * Static callback function for HGCM message processing thread. An internal
3270 * message queue will be filled which then will be processed by the according
3271 * drag'n drop instance.
3272 *
3273 * @returns IPRT status code.
3274 * @param hThread Thread handle to use.
3275 * @param pvUser Pointer to DragAndDropService instance to use.
3276 */
3277/* static */
3278DECLCALLBACK(int) DragAndDropService::hgcmEventThread(RTTHREAD hThread, void *pvUser)
3279{
3280 AssertPtrReturn(pvUser, VERR_INVALID_PARAMETER);
3281 DragAndDropService *pThis = static_cast<DragAndDropService*>(pvUser);
3282 AssertPtr(pThis);
3283
3284 /* This thread has an own DnD context, e.g. an own client ID. */
3285 VBGLR3GUESTDNDCMDCTX dndCtx;
3286
3287 /*
3288 * Initialize thread.
3289 */
3290 int rc = VbglR3DnDConnect(&dndCtx);
3291
3292 /* Set stop indicator on failure. */
3293 if (RT_FAILURE(rc))
3294 ASMAtomicXchgBool(&pThis->m_fSrvStopping, true);
3295
3296 /* Let the service instance know in any case. */
3297 int rc2 = RTThreadUserSignal(hThread);
3298 AssertRC(rc2);
3299
3300 if (RT_FAILURE(rc))
3301 return rc;
3302
3303 /* Number of invalid messages skipped in a row. */
3304 int cMsgSkippedInvalid = 0;
3305 DnDEvent e;
3306
3307 do
3308 {
3309 RT_ZERO(e);
3310 e.type = DnDEvent::HGCM_Type;
3311
3312 /* Wait for new events. */
3313 rc = VbglR3DnDRecvNextMsg(&dndCtx, &e.hgcm);
3314 if ( RT_SUCCESS(rc)
3315 || rc == VERR_CANCELLED)
3316 {
3317 cMsgSkippedInvalid = 0; /* Reset skipped messages count. */
3318 pThis->m_eventQueue.append(e);
3319
3320 rc = RTSemEventSignal(pThis->m_hEventSem);
3321 if (RT_FAILURE(rc))
3322 break;
3323 }
3324 else
3325 {
3326 LogRel(("DnD: Processing next message failed with rc=%Rrc\n", rc));
3327
3328 /* Old(er) hosts either are broken regarding DnD support or otherwise
3329 * don't support the stuff we do on the guest side, so make sure we
3330 * don't process invalid messages forever. */
3331 if (rc == VERR_INVALID_PARAMETER)
3332 cMsgSkippedInvalid++;
3333 if (cMsgSkippedInvalid > 32)
3334 {
3335 LogRel(("DnD: Too many invalid/skipped messages from host, exiting ...\n"));
3336 break;
3337 }
3338 }
3339
3340 } while (!ASMAtomicReadBool(&pThis->m_fSrvStopping));
3341
3342 VbglR3DnDDisconnect(&dndCtx);
3343
3344 LogFlowFuncLeaveRC(rc);
3345 return rc;
3346}
3347
3348/**
3349 * Static callback function for X11 message processing thread. All X11 messages
3350 * will be directly routed to the according drag'n drop instance.
3351 *
3352 * @returns IPRT status code.
3353 * @param hThread Thread handle to use.
3354 * @param pvUser Pointer to DragAndDropService instance to use.
3355 */
3356/* static */
3357DECLCALLBACK(int) DragAndDropService::x11EventThread(RTTHREAD hThread, void *pvUser)
3358{
3359 AssertPtrReturn(pvUser, VERR_INVALID_PARAMETER);
3360 DragAndDropService *pThis = static_cast<DragAndDropService*>(pvUser);
3361 AssertPtr(pThis);
3362
3363 int rc = VINF_SUCCESS;
3364
3365 /* Note: Nothing to initialize here (yet). */
3366
3367 /* Set stop indicator on failure. */
3368 if (RT_FAILURE(rc))
3369 ASMAtomicXchgBool(&pThis->m_fSrvStopping, true);
3370
3371 /* Let the service instance know in any case. */
3372 int rc2 = RTThreadUserSignal(hThread);
3373 AssertRC(rc2);
3374
3375 DnDEvent e;
3376 do
3377 {
3378 /*
3379 * Wait for new events. We can't use XIfEvent here, cause this locks
3380 * the window connection with a mutex and if no X11 events occurs this
3381 * blocks any other calls we made to X11. So instead check for new
3382 * events and if there are not any new one, sleep for a certain amount
3383 * of time.
3384 */
3385 if (XEventsQueued(pThis->m_pDisplay, QueuedAfterFlush) > 0)
3386 {
3387 RT_ZERO(e);
3388 e.type = DnDEvent::X11_Type;
3389
3390 /* XNextEvent will block until a new X event becomes available. */
3391 XNextEvent(pThis->m_pDisplay, &e.x11);
3392 {
3393#ifdef DEBUG
3394 switch (e.x11.type)
3395 {
3396 case ClientMessage:
3397 {
3398 XClientMessageEvent *pEvent = reinterpret_cast<XClientMessageEvent*>(&e);
3399 AssertPtr(pEvent);
3400
3401 RTCString strType = xAtomToString(pEvent->message_type);
3402 LogFlowFunc(("ClientMessage: %s from wnd=%#x\n", strType.c_str(), pEvent->window));
3403 break;
3404 }
3405
3406 default:
3407 LogFlowFunc(("Received X event type=%d\n", e.x11.type));
3408 break;
3409 }
3410#endif
3411 /* At the moment we only have one drag instance. */
3412 DragInstance *pInstance = pThis->m_pCurDnD;
3413 AssertPtr(pInstance);
3414
3415 pInstance->onX11Event(e.x11);
3416 }
3417 }
3418 else
3419 RTThreadSleep(25 /* ms */);
3420
3421 } while (!ASMAtomicReadBool(&pThis->m_fSrvStopping));
3422
3423 LogFlowFuncLeaveRC(rc);
3424 return rc;
3425}
3426
3427/** Drag and drop magic number, start of a UUID. */
3428#define DRAGANDDROPSERVICE_MAGIC 0x67c97173
3429
3430/** VBoxClient service class wrapping the logic for the service while
3431 * the main VBoxClient code provides the daemon logic needed by all services.
3432 */
3433struct DRAGANDDROPSERVICE
3434{
3435 /** The service interface. */
3436 struct VBCLSERVICE *pInterface;
3437 /** Magic number for sanity checks. */
3438 uint32_t uMagic;
3439 /** Service object. */
3440 DragAndDropService mDragAndDrop;
3441};
3442
3443static const char *getPidFilePath()
3444{
3445 return ".vboxclient-draganddrop.pid";
3446}
3447
3448static int init(struct VBCLSERVICE **ppInterface)
3449{
3450 struct DRAGANDDROPSERVICE *pSelf = (struct DRAGANDDROPSERVICE *)ppInterface;
3451
3452 if (pSelf->uMagic != DRAGANDDROPSERVICE_MAGIC)
3453 VBClFatalError(("Bad DnD service object!\n"));
3454 return pSelf->mDragAndDrop.init();
3455}
3456
3457static int run(struct VBCLSERVICE **ppInterface, bool fDaemonised)
3458{
3459 struct DRAGANDDROPSERVICE *pSelf = (struct DRAGANDDROPSERVICE *)ppInterface;
3460
3461 if (pSelf->uMagic != DRAGANDDROPSERVICE_MAGIC)
3462 VBClFatalError(("Bad DnD service object!\n"));
3463 return pSelf->mDragAndDrop.run(fDaemonised);
3464}
3465
3466static void cleanup(struct VBCLSERVICE **ppInterface)
3467{
3468 struct DRAGANDDROPSERVICE *pSelf = (struct DRAGANDDROPSERVICE *)ppInterface;
3469
3470 if (pSelf->uMagic != DRAGANDDROPSERVICE_MAGIC)
3471 VBClFatalError(("Bad DnD service object!\n"));
3472 return pSelf->mDragAndDrop.cleanup();
3473}
3474
3475struct VBCLSERVICE vbclDragAndDropInterface =
3476{
3477 getPidFilePath,
3478 init,
3479 run,
3480 cleanup
3481};
3482
3483/* Static factory. */
3484struct VBCLSERVICE **VBClGetDragAndDropService(void)
3485{
3486 struct DRAGANDDROPSERVICE *pService =
3487 (struct DRAGANDDROPSERVICE *)RTMemAlloc(sizeof(*pService));
3488
3489 if (!pService)
3490 VBClFatalError(("Out of memory\n"));
3491 pService->pInterface = &vbclDragAndDropInterface;
3492 pService->uMagic = DRAGANDDROPSERVICE_MAGIC;
3493 new(&pService->mDragAndDrop) DragAndDropService();
3494 return &pService->pInterface;
3495}
Note: See TracBrowser for help on using the repository browser.

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