winex11: Don't use raw events for button events so that we get the right coordinates.
[wine] / dlls / winex11.drv / mouse.c
1 /*
2  * X11 mouse driver
3  *
4  * Copyright 1998 Ulrich Weigand
5  * Copyright 2007 Henri Verbeet
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <X11/Xlib.h>
26 #include <X11/cursorfont.h>
27 #include <stdarg.h>
28 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
29 #include <X11/extensions/XInput2.h>
30 #endif
31
32 #ifdef SONAME_LIBXCURSOR
33 # include <X11/Xcursor/Xcursor.h>
34 static void *xcursor_handle;
35 # define MAKE_FUNCPTR(f) static typeof(f) * p##f
36 MAKE_FUNCPTR(XcursorImageCreate);
37 MAKE_FUNCPTR(XcursorImageDestroy);
38 MAKE_FUNCPTR(XcursorImageLoadCursor);
39 MAKE_FUNCPTR(XcursorImagesCreate);
40 MAKE_FUNCPTR(XcursorImagesDestroy);
41 MAKE_FUNCPTR(XcursorImagesLoadCursor);
42 MAKE_FUNCPTR(XcursorLibraryLoadCursor);
43 # undef MAKE_FUNCPTR
44 #endif /* SONAME_LIBXCURSOR */
45
46 #define NONAMELESSUNION
47 #define NONAMELESSSTRUCT
48 #define OEMRESOURCE
49 #include "windef.h"
50 #include "winbase.h"
51 #include "winreg.h"
52
53 #include "x11drv.h"
54 #include "wine/server.h"
55 #include "wine/library.h"
56 #include "wine/unicode.h"
57 #include "wine/debug.h"
58
59 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
60
61 /**********************************************************************/
62
63 #ifndef Button6Mask
64 #define Button6Mask (1<<13)
65 #endif
66 #ifndef Button7Mask
67 #define Button7Mask (1<<14)
68 #endif
69
70 #define NB_BUTTONS   9     /* Windows can handle 5 buttons and the wheel too */
71
72 static const UINT button_down_flags[NB_BUTTONS] =
73 {
74     MOUSEEVENTF_LEFTDOWN,
75     MOUSEEVENTF_MIDDLEDOWN,
76     MOUSEEVENTF_RIGHTDOWN,
77     MOUSEEVENTF_WHEEL,
78     MOUSEEVENTF_WHEEL,
79     MOUSEEVENTF_XDOWN,  /* FIXME: horizontal wheel */
80     MOUSEEVENTF_XDOWN,
81     MOUSEEVENTF_XDOWN,
82     MOUSEEVENTF_XDOWN
83 };
84
85 static const UINT button_up_flags[NB_BUTTONS] =
86 {
87     MOUSEEVENTF_LEFTUP,
88     MOUSEEVENTF_MIDDLEUP,
89     MOUSEEVENTF_RIGHTUP,
90     0,
91     0,
92     MOUSEEVENTF_XUP,
93     MOUSEEVENTF_XUP,
94     MOUSEEVENTF_XUP,
95     MOUSEEVENTF_XUP
96 };
97
98 static const UINT button_down_data[NB_BUTTONS] =
99 {
100     0,
101     0,
102     0,
103     WHEEL_DELTA,
104     -WHEEL_DELTA,
105     XBUTTON1,
106     XBUTTON2,
107     XBUTTON1,
108     XBUTTON2
109 };
110
111 static const UINT button_up_data[NB_BUTTONS] =
112 {
113     0,
114     0,
115     0,
116     0,
117     0,
118     XBUTTON1,
119     XBUTTON2,
120     XBUTTON1,
121     XBUTTON2
122 };
123
124 static HWND cursor_window;
125 static HCURSOR last_cursor;
126 static DWORD last_cursor_change;
127 static XContext cursor_context;
128 static RECT clip_rect;
129 static Cursor create_cursor( HANDLE handle );
130
131 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
132 static BOOL xinput2_available;
133 static int xinput2_core_pointer;
134 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
135 MAKE_FUNCPTR(XIFreeDeviceInfo);
136 MAKE_FUNCPTR(XIQueryDevice);
137 MAKE_FUNCPTR(XIQueryVersion);
138 MAKE_FUNCPTR(XISelectEvents);
139 #undef MAKE_FUNCPTR
140 #endif
141
142 /***********************************************************************
143  *              X11DRV_Xcursor_Init
144  *
145  * Load the Xcursor library for use.
146  */
147 void X11DRV_Xcursor_Init(void)
148 {
149 #ifdef SONAME_LIBXCURSOR
150     xcursor_handle = wine_dlopen(SONAME_LIBXCURSOR, RTLD_NOW, NULL, 0);
151     if (!xcursor_handle)  /* wine_dlopen failed. */
152     {
153         WARN("Xcursor failed to load.  Using fallback code.\n");
154         return;
155     }
156 #define LOAD_FUNCPTR(f) \
157         p##f = wine_dlsym(xcursor_handle, #f, NULL, 0)
158
159     LOAD_FUNCPTR(XcursorImageCreate);
160     LOAD_FUNCPTR(XcursorImageDestroy);
161     LOAD_FUNCPTR(XcursorImageLoadCursor);
162     LOAD_FUNCPTR(XcursorImagesCreate);
163     LOAD_FUNCPTR(XcursorImagesDestroy);
164     LOAD_FUNCPTR(XcursorImagesLoadCursor);
165     LOAD_FUNCPTR(XcursorLibraryLoadCursor);
166 #undef LOAD_FUNCPTR
167 #endif /* SONAME_LIBXCURSOR */
168 }
169
170
171 /***********************************************************************
172  *              get_empty_cursor
173  */
174 static Cursor get_empty_cursor(void)
175 {
176     static Cursor cursor;
177     static const char data[] = { 0 };
178
179     wine_tsx11_lock();
180     if (!cursor)
181     {
182         XColor bg;
183         Pixmap pixmap;
184
185         bg.red = bg.green = bg.blue = 0x0000;
186         pixmap = XCreateBitmapFromData( gdi_display, root_window, data, 1, 1 );
187         if (pixmap)
188         {
189             cursor = XCreatePixmapCursor( gdi_display, pixmap, pixmap, &bg, &bg, 0, 0 );
190             XFreePixmap( gdi_display, pixmap );
191         }
192     }
193     wine_tsx11_unlock();
194     return cursor;
195 }
196
197 /***********************************************************************
198  *              set_window_cursor
199  */
200 void set_window_cursor( Window window, HCURSOR handle )
201 {
202     Cursor cursor, prev;
203
204     wine_tsx11_lock();
205     if (!handle) cursor = get_empty_cursor();
206     else if (!cursor_context || XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&cursor ))
207     {
208         /* try to create it */
209         wine_tsx11_unlock();
210         if (!(cursor = create_cursor( handle ))) return;
211
212         wine_tsx11_lock();
213         if (!cursor_context) cursor_context = XUniqueContext();
214         if (!XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&prev ))
215         {
216             /* someone else was here first */
217             XFreeCursor( gdi_display, cursor );
218             cursor = prev;
219         }
220         else
221         {
222             XSaveContext( gdi_display, (XID)handle, cursor_context, (char *)cursor );
223             TRACE( "cursor %p created %lx\n", handle, cursor );
224         }
225     }
226
227     XDefineCursor( gdi_display, window, cursor );
228     /* make the change take effect immediately */
229     XFlush( gdi_display );
230     wine_tsx11_unlock();
231 }
232
233 /***********************************************************************
234  *              sync_window_cursor
235  */
236 void sync_window_cursor( Window window )
237 {
238     HCURSOR cursor;
239
240     SERVER_START_REQ( set_cursor )
241     {
242         req->flags = 0;
243         wine_server_call( req );
244         cursor = reply->prev_count >= 0 ? wine_server_ptr_handle( reply->prev_handle ) : 0;
245     }
246     SERVER_END_REQ;
247
248     set_window_cursor( window, cursor );
249 }
250
251 /***********************************************************************
252  *              enable_xinput2
253  */
254 static void enable_xinput2(void)
255 {
256 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
257     struct x11drv_thread_data *data = x11drv_thread_data();
258     XIDeviceInfo *devices;
259     XIEventMask mask;
260     unsigned char mask_bits[XIMaskLen(XI_LASTEVENT)];
261     int i, count;
262
263     if (!xinput2_available) return;
264
265     if (data->xi2_state == xi_unknown)
266     {
267         int major = 2, minor = 0;
268         wine_tsx11_lock();
269         if (!pXIQueryVersion( data->display, &major, &minor )) data->xi2_state = xi_disabled;
270         else
271         {
272             data->xi2_state = xi_unavailable;
273             WARN( "X Input 2 not available\n" );
274         }
275         wine_tsx11_unlock();
276     }
277     if (data->xi2_state == xi_unavailable) return;
278
279     wine_tsx11_lock();
280     devices = pXIQueryDevice( data->display, XIAllDevices, &count );
281     for (i = 0; i < count; ++i)
282     {
283         if (devices[i].use != XIMasterPointer) continue;
284         TRACE( "Using %u (%s) as core pointer\n",
285                devices[i].deviceid, debugstr_a(devices[i].name) );
286         xinput2_core_pointer = devices[i].deviceid;
287         break;
288     }
289
290     mask.mask     = mask_bits;
291     mask.mask_len = sizeof(mask_bits);
292     memset( mask_bits, 0, sizeof(mask_bits) );
293     XISetMask( mask_bits, XI_RawMotion );
294
295     for (i = 0; i < count; ++i)
296     {
297         if (devices[i].use == XISlavePointer && devices[i].attachment == xinput2_core_pointer)
298         {
299             TRACE( "Device %u (%s) is attached to the core pointer\n",
300                    devices[i].deviceid, debugstr_a(devices[i].name) );
301             mask.deviceid = devices[i].deviceid;
302             pXISelectEvents( data->display, DefaultRootWindow( data->display ), &mask, 1 );
303             data->xi2_state = xi_enabled;
304         }
305     }
306
307     pXIFreeDeviceInfo( devices );
308     wine_tsx11_unlock();
309 #endif
310 }
311
312 /***********************************************************************
313  *              disable_xinput2
314  */
315 static void disable_xinput2(void)
316 {
317 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
318     struct x11drv_thread_data *data = x11drv_thread_data();
319     XIEventMask mask;
320     XIDeviceInfo *devices;
321     int i, count;
322
323     if (data->xi2_state != xi_enabled) return;
324
325     TRACE( "disabling\n" );
326     data->xi2_state = xi_disabled;
327
328     mask.mask = NULL;
329     mask.mask_len = 0;
330
331     wine_tsx11_lock();
332     devices = pXIQueryDevice( data->display, XIAllDevices, &count );
333     for (i = 0; i < count; ++i)
334     {
335         if (devices[i].use == XISlavePointer && devices[i].attachment == xinput2_core_pointer)
336         {
337             mask.deviceid = devices[i].deviceid;
338             pXISelectEvents( data->display, DefaultRootWindow( data->display ), &mask, 1 );
339         }
340     }
341     pXIFreeDeviceInfo( devices );
342     wine_tsx11_unlock();
343 #endif
344 }
345
346 /***********************************************************************
347  *             create_clipping_msg_window
348  */
349 static HWND create_clipping_msg_window(void)
350 {
351     static const WCHAR class_name[] = {'_','_','x','1','1','d','r','v','_','c','l','i','p','_','c','l','a','s','s',0};
352     static ATOM clip_class;
353
354     if (!clip_class)
355     {
356         WNDCLASSW class;
357         ATOM atom;
358
359         memset( &class, 0, sizeof(class) );
360         class.lpfnWndProc   = DefWindowProcW;
361         class.hInstance     = GetModuleHandleW(0);
362         class.lpszClassName = class_name;
363         if ((atom = RegisterClassW( &class ))) clip_class = atom;
364     }
365     return CreateWindowW( class_name, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, GetModuleHandleW(0), NULL );
366 }
367
368 /***********************************************************************
369  *              grab_clipping_window
370  *
371  * Start a pointer grab on the clip window.
372  */
373 static BOOL grab_clipping_window( const RECT *clip, BOOL only_with_xinput )
374 {
375     struct x11drv_thread_data *data = x11drv_thread_data();
376     Window clip_window;
377     HWND msg_hwnd = 0;
378
379     if (!data) return FALSE;
380     if (!(clip_window = init_clip_window())) return TRUE;
381
382     /* create a clip message window unless we are already clipping */
383     if (!data->clip_hwnd)
384     {
385         if (!(msg_hwnd = create_clipping_msg_window())) return TRUE;
386         enable_xinput2();
387     }
388
389     /* don't clip to 1x1 rectangle if we don't have XInput */
390     if (clip->right - clip->left == 1 && clip->bottom - clip->top == 1) only_with_xinput = TRUE;
391     if (only_with_xinput && data->xi2_state != xi_enabled)
392     {
393         WARN( "XInput2 not supported, refusing to clip to %s\n", wine_dbgstr_rect(clip) );
394         if (msg_hwnd) DestroyWindow( msg_hwnd );
395         ClipCursor( NULL );
396         return TRUE;
397     }
398
399     TRACE( "clipping to %s\n", wine_dbgstr_rect(clip) );
400
401     wine_tsx11_lock();
402     if (msg_hwnd) XUnmapWindow( data->display, clip_window );
403     XMoveResizeWindow( data->display, clip_window,
404                        clip->left - virtual_screen_rect.left, clip->top - virtual_screen_rect.top,
405                        clip->right - clip->left, clip->bottom - clip->top );
406     if (msg_hwnd) XMapWindow( data->display, clip_window );
407     if (!XGrabPointer( data->display, clip_window, False,
408                        PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
409                        GrabModeAsync, GrabModeAsync, clip_window, None, CurrentTime ))
410         clipping_cursor = 1;
411     wine_tsx11_unlock();
412
413     if (!clipping_cursor)
414     {
415         disable_xinput2();
416         if (msg_hwnd) DestroyWindow( msg_hwnd );
417         return FALSE;
418     }
419     clip_rect = *clip;
420     if (msg_hwnd)
421     {
422         data->clip_hwnd = msg_hwnd;
423         sync_window_cursor( clip_window );
424         SendMessageW( GetDesktopWindow(), WM_X11DRV_CLIP_CURSOR, 0, (LPARAM)msg_hwnd );
425     }
426     return TRUE;
427 }
428
429 /***********************************************************************
430  *              ungrab_clipping_window
431  *
432  * Release the pointer grab on the clip window.
433  */
434 void ungrab_clipping_window(void)
435 {
436     Display *display = thread_init_display();
437     Window clip_window = init_clip_window();
438
439     if (!clip_window) return;
440
441     TRACE( "no longer clipping\n" );
442     wine_tsx11_lock();
443     XUnmapWindow( display, clip_window );
444     wine_tsx11_unlock();
445     clipping_cursor = 0;
446     SendMessageW( GetDesktopWindow(), WM_X11DRV_CLIP_CURSOR, 0, 0 );
447 }
448
449 /***********************************************************************
450  *              reset_clipping_window
451  *
452  * Forcibly reset the window clipping on external events.
453  */
454 void reset_clipping_window(void)
455 {
456     ungrab_clipping_window();
457     ClipCursor( NULL );  /* make sure the clip rectangle is reset too */
458 }
459
460 /***********************************************************************
461  *             clip_cursor_notify
462  *
463  * Notification function called upon receiving a WM_X11DRV_CLIP_CURSOR.
464  */
465 LRESULT clip_cursor_notify( HWND hwnd, HWND new_clip_hwnd )
466 {
467     struct x11drv_thread_data *data = x11drv_thread_data();
468
469     if (hwnd == GetDesktopWindow())  /* change the clip window stored in the desktop process */
470     {
471         static HWND clip_hwnd;
472
473         HWND prev = clip_hwnd;
474         clip_hwnd = new_clip_hwnd;
475         if (prev || new_clip_hwnd) TRACE( "clip hwnd changed from %p to %p\n", prev, new_clip_hwnd );
476         if (prev) SendNotifyMessageW( prev, WM_X11DRV_CLIP_CURSOR, 0, 0 );
477     }
478     else if (hwnd == data->clip_hwnd)  /* this is a notification that clipping has been reset */
479     {
480         data->clip_hwnd = 0;
481         data->clip_reset = GetTickCount();
482         disable_xinput2();
483         DestroyWindow( hwnd );
484     }
485     else if (hwnd == GetForegroundWindow())  /* request to clip */
486     {
487         RECT clip;
488
489         GetClipCursor( &clip );
490         if (clip.left > virtual_screen_rect.left || clip.right < virtual_screen_rect.right ||
491             clip.top > virtual_screen_rect.top   || clip.bottom < virtual_screen_rect.bottom)
492             return grab_clipping_window( &clip, FALSE );
493     }
494     return 0;
495 }
496
497 /***********************************************************************
498  *              clip_fullscreen_window
499  *
500  * Turn on clipping if the active window is fullscreen.
501  */
502 BOOL clip_fullscreen_window( HWND hwnd, BOOL reset )
503 {
504     struct x11drv_win_data *data;
505     struct x11drv_thread_data *thread_data;
506     RECT rect;
507     DWORD style;
508
509     if (hwnd == GetDesktopWindow()) return FALSE;
510     if (!(data = X11DRV_get_win_data( hwnd ))) return FALSE;
511     style = GetWindowLongW( hwnd, GWL_STYLE );
512     if (!(style & WS_VISIBLE)) return FALSE;
513     if ((style & (WS_POPUP | WS_CHILD)) == WS_CHILD) return FALSE;
514     /* maximized windows don't count as full screen */
515     if ((style & WS_MAXIMIZE) && (style & WS_CAPTION) == WS_CAPTION) return FALSE;
516     if (!is_window_rect_fullscreen( &data->whole_rect )) return FALSE;
517     if (!(thread_data = x11drv_thread_data())) return FALSE;
518     if (GetTickCount() - thread_data->clip_reset < 1000) return FALSE;
519     if (!reset && thread_data->clip_hwnd) return FALSE;  /* already clipping */
520     SetRect( &rect, 0, 0, screen_width, screen_height );
521     if (!grab_fullscreen)
522     {
523         if (!EqualRect( &rect, &virtual_screen_rect )) return FALSE;
524         if (root_window != DefaultRootWindow( gdi_display )) return FALSE;
525     }
526     TRACE( "win %p clipping fullscreen\n", hwnd );
527     return grab_clipping_window( &rect, TRUE );
528 }
529
530 /***********************************************************************
531  *              send_mouse_input
532  *
533  * Update the various window states on a mouse event.
534  */
535 static void send_mouse_input( HWND hwnd, Window window, unsigned int state, INPUT *input )
536 {
537     struct x11drv_win_data *data;
538     POINT pt;
539
540     input->type = INPUT_MOUSE;
541
542     if (!hwnd)
543     {
544         struct x11drv_thread_data *thread_data = x11drv_thread_data();
545
546         if (!thread_data->clip_hwnd) return;
547         if (thread_data->clip_window != window) return;
548         input->u.mi.dx += clip_rect.left;
549         input->u.mi.dy += clip_rect.top;
550         if (!(input->u.mi.dwFlags & ~(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE)))
551         {
552             /* motion events are ignored when xinput2 is active */
553             if (thread_data->xi2_state == xi_enabled) return;
554         }
555         __wine_send_input( hwnd, input );
556         return;
557     }
558
559     if (!(data = X11DRV_get_win_data( hwnd ))) return;
560
561     if (window == data->whole_window)
562     {
563         input->u.mi.dx += data->whole_rect.left - data->client_rect.left;
564         input->u.mi.dy += data->whole_rect.top - data->client_rect.top;
565     }
566     if (window == root_window)
567     {
568         input->u.mi.dx += virtual_screen_rect.left;
569         input->u.mi.dy += virtual_screen_rect.top;
570     }
571     pt.x = input->u.mi.dx;
572     pt.y = input->u.mi.dy;
573     if (GetWindowLongW( data->hwnd, GWL_EXSTYLE ) & WS_EX_LAYOUTRTL)
574         pt.x = data->client_rect.right - data->client_rect.left - 1 - pt.x;
575     MapWindowPoints( hwnd, 0, &pt, 1 );
576
577     if (InterlockedExchangePointer( (void **)&cursor_window, hwnd ) != hwnd ||
578         GetTickCount() - last_cursor_change > 100)
579     {
580         sync_window_cursor( data->whole_window );
581         last_cursor_change = GetTickCount();
582     }
583
584     if (hwnd != GetDesktopWindow())
585     {
586         hwnd = GetAncestor( hwnd, GA_ROOT );
587         if ((input->u.mi.dwFlags & (MOUSEEVENTF_LEFTDOWN|MOUSEEVENTF_RIGHTDOWN)) && hwnd == GetForegroundWindow())
588             clip_fullscreen_window( hwnd, FALSE );
589     }
590
591     /* update the wine server Z-order */
592
593     if (window != x11drv_thread_data()->grab_window &&
594         /* ignore event if a button is pressed, since the mouse is then grabbed too */
595         !(state & (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask|Button6Mask|Button7Mask)))
596     {
597         RECT rect;
598         SetRect( &rect, pt.x, pt.y, pt.x + 1, pt.y + 1 );
599         MapWindowPoints( 0, hwnd, (POINT *)&rect, 2 );
600
601         SERVER_START_REQ( update_window_zorder )
602         {
603             req->window      = wine_server_user_handle( hwnd );
604             req->rect.left   = rect.left;
605             req->rect.top    = rect.top;
606             req->rect.right  = rect.right;
607             req->rect.bottom = rect.bottom;
608             wine_server_call( req );
609         }
610         SERVER_END_REQ;
611     }
612
613     input->u.mi.dx = pt.x;
614     input->u.mi.dy = pt.y;
615     __wine_send_input( hwnd, input );
616 }
617
618 #ifdef SONAME_LIBXCURSOR
619
620 /***********************************************************************
621  *              create_xcursor_frame
622  *
623  * Use Xcursor to create a frame of an X cursor from a Windows one.
624  */
625 static XcursorImage *create_xcursor_frame( HDC hdc, const ICONINFOEXW *iinfo, HANDLE icon,
626                                            HBITMAP hbmColor, unsigned char *color_bits, int color_size,
627                                            HBITMAP hbmMask, unsigned char *mask_bits, int mask_size,
628                                            int width, int height, int istep )
629 {
630     XcursorImage *image, *ret = NULL;
631     DWORD delay_jiffies, num_steps;
632     int x, y, i, has_alpha = FALSE;
633     XcursorPixel *ptr;
634
635     wine_tsx11_lock();
636     image = pXcursorImageCreate( width, height );
637     wine_tsx11_unlock();
638     if (!image)
639     {
640         ERR("X11 failed to produce a cursor frame!\n");
641         goto cleanup;
642     }
643
644     image->xhot = iinfo->xHotspot;
645     image->yhot = iinfo->yHotspot;
646
647     image->delay = 100; /* fallback delay, 100 ms */
648     if (GetCursorFrameInfo(icon, 0x0 /* unknown parameter */, istep, &delay_jiffies, &num_steps) != 0)
649         image->delay = (100 * delay_jiffies) / 6; /* convert jiffies (1/60s) to milliseconds */
650     else
651         WARN("Failed to retrieve animated cursor frame-rate for frame %d.\n", istep);
652
653     /* draw the cursor frame to a temporary buffer then copy it into the XcursorImage */
654     memset( color_bits, 0x00, color_size );
655     SelectObject( hdc, hbmColor );
656     if (!DrawIconEx( hdc, 0, 0, icon, width, height, istep, NULL, DI_NORMAL ))
657     {
658         TRACE("Could not draw frame %d (walk past end of frames).\n", istep);
659         goto cleanup;
660     }
661     memcpy( image->pixels, color_bits, color_size );
662
663     /* check if the cursor frame was drawn with an alpha channel */
664     for (i = 0, ptr = image->pixels; i < width * height; i++, ptr++)
665         if ((has_alpha = (*ptr & 0xff000000) != 0)) break;
666
667     /* if no alpha channel was drawn then generate it from the mask */
668     if (!has_alpha)
669     {
670         unsigned int width_bytes = (width + 31) / 32 * 4;
671
672         /* draw the cursor mask to a temporary buffer */
673         memset( mask_bits, 0xFF, mask_size );
674         SelectObject( hdc, hbmMask );
675         if (!DrawIconEx( hdc, 0, 0, icon, width, height, istep, NULL, DI_MASK ))
676         {
677             ERR("Failed to draw frame mask %d.\n", istep);
678             goto cleanup;
679         }
680         /* use the buffer to directly modify the XcursorImage alpha channel */
681         for (y = 0, ptr = image->pixels; y < height; y++)
682             for (x = 0; x < width; x++, ptr++)
683                 if (!((mask_bits[y * width_bytes + x / 8] << (x % 8)) & 0x80))
684                     *ptr |= 0xff000000;
685     }
686     ret = image;
687
688 cleanup:
689     if (ret == NULL) pXcursorImageDestroy( image );
690     return ret;
691 }
692
693 /***********************************************************************
694  *              create_xcursor_cursor
695  *
696  * Use Xcursor to create an X cursor from a Windows one.
697  */
698 static Cursor create_xcursor_cursor( HDC hdc, const ICONINFOEXW *iinfo, HANDLE icon, int width, int height )
699 {
700     unsigned char *color_bits, *mask_bits;
701     HBITMAP hbmColor = 0, hbmMask = 0;
702     DWORD nFrames, delay_jiffies, i;
703     int color_size, mask_size;
704     BITMAPINFO *info = NULL;
705     XcursorImages *images;
706     XcursorImage **imgs;
707     Cursor cursor = 0;
708
709     /* Retrieve the number of frames to render */
710     if (!GetCursorFrameInfo(icon, 0x0 /* unknown parameter */, 0, &delay_jiffies, &nFrames)) return 0;
711     if (!(imgs = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(XcursorImage*)*nFrames ))) return 0;
712
713     /* Allocate all of the resources necessary to obtain a cursor frame */
714     if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto cleanup;
715     info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
716     info->bmiHeader.biWidth = width;
717     info->bmiHeader.biHeight = -height;
718     info->bmiHeader.biPlanes = 1;
719     info->bmiHeader.biCompression = BI_RGB;
720     info->bmiHeader.biXPelsPerMeter = 0;
721     info->bmiHeader.biYPelsPerMeter = 0;
722     info->bmiHeader.biClrUsed = 0;
723     info->bmiHeader.biClrImportant = 0;
724     info->bmiHeader.biBitCount = 32;
725     color_size = width * height * 4;
726     info->bmiHeader.biSizeImage = color_size;
727     hbmColor = CreateDIBSection( hdc, info, DIB_RGB_COLORS, (VOID **) &color_bits, NULL, 0);
728     if (!hbmColor)
729     {
730         ERR("Failed to create DIB section for cursor color data!\n");
731         goto cleanup;
732     }
733     info->bmiHeader.biBitCount = 1;
734     mask_size = ((width + 31) / 32 * 4) * height; /* width_bytes * height */
735     info->bmiHeader.biSizeImage = mask_size;
736     hbmMask = CreateDIBSection( hdc, info, DIB_RGB_COLORS, (VOID **) &mask_bits, NULL, 0);
737     if (!hbmMask)
738     {
739         ERR("Failed to create DIB section for cursor mask data!\n");
740         goto cleanup;
741     }
742
743     /* Create an XcursorImage for each frame of the cursor */
744     for (i=0; i<nFrames; i++)
745     {
746         imgs[i] = create_xcursor_frame( hdc, iinfo, icon,
747                                         hbmColor, color_bits, color_size,
748                                         hbmMask, mask_bits, mask_size,
749                                         width, height, i );
750         if (!imgs[i]) goto cleanup;
751     }
752
753     /* Build an X cursor out of all of the frames */
754     if (!(images = pXcursorImagesCreate( nFrames ))) goto cleanup;
755     for (images->nimage = 0; images->nimage < nFrames; images->nimage++)
756         images->images[images->nimage] = imgs[images->nimage];
757     wine_tsx11_lock();
758     cursor = pXcursorImagesLoadCursor( gdi_display, images );
759     wine_tsx11_unlock();
760     pXcursorImagesDestroy( images ); /* Note: this frees each individual frame (calls XcursorImageDestroy) */
761     HeapFree( GetProcessHeap(), 0, imgs );
762     imgs = NULL;
763
764 cleanup:
765     if (imgs)
766     {
767         /* Failed to produce a cursor, free previously allocated frames */
768         for (i=0; i<nFrames && imgs[i]; i++)
769             pXcursorImageDestroy( imgs[i] );
770         HeapFree( GetProcessHeap(), 0, imgs );
771     }
772     /* Cleanup all of the resources used to obtain the frame data */
773     if (hbmColor) DeleteObject( hbmColor );
774     if (hbmMask) DeleteObject( hbmMask );
775     HeapFree( GetProcessHeap(), 0, info );
776     return cursor;
777 }
778
779
780 struct system_cursors
781 {
782     WORD id;
783     const char *name;
784 };
785
786 static const struct system_cursors user32_cursors[] =
787 {
788     { OCR_NORMAL,      "left_ptr" },
789     { OCR_IBEAM,       "xterm" },
790     { OCR_WAIT,        "watch" },
791     { OCR_CROSS,       "cross" },
792     { OCR_UP,          "center_ptr" },
793     { OCR_SIZE,        "fleur" },
794     { OCR_SIZEALL,     "fleur" },
795     { OCR_ICON,        "icon" },
796     { OCR_SIZENWSE,    "nwse-resize" },
797     { OCR_SIZENESW,    "nesw-resize" },
798     { OCR_SIZEWE,      "ew-resize" },
799     { OCR_SIZENS,      "ns-resize" },
800     { OCR_NO,          "not-allowed" },
801     { OCR_HAND,        "hand2" },
802     { OCR_APPSTARTING, "left_ptr_watch" },
803     { OCR_HELP,        "question_arrow" },
804     { 0 }
805 };
806
807 static const struct system_cursors comctl32_cursors[] =
808 {
809     { 102, "move" },
810     { 104, "copy" },
811     { 105, "left_ptr" },
812     { 106, "row-resize" },
813     { 107, "row-resize" },
814     { 108, "hand2" },
815     { 135, "col-resize" },
816     { 0 }
817 };
818
819 static const struct system_cursors ole32_cursors[] =
820 {
821     { 1, "no-drop" },
822     { 2, "move" },
823     { 3, "copy" },
824     { 4, "alias" },
825     { 0 }
826 };
827
828 static const struct system_cursors riched20_cursors[] =
829 {
830     { 105, "hand2" },
831     { 107, "right_ptr" },
832     { 109, "copy" },
833     { 110, "move" },
834     { 111, "no-drop" },
835     { 0 }
836 };
837
838 static const struct
839 {
840     const struct system_cursors *cursors;
841     WCHAR name[16];
842 } module_cursors[] =
843 {
844     { user32_cursors, {'u','s','e','r','3','2','.','d','l','l',0} },
845     { comctl32_cursors, {'c','o','m','c','t','l','3','2','.','d','l','l',0} },
846     { ole32_cursors, {'o','l','e','3','2','.','d','l','l',0} },
847     { riched20_cursors, {'r','i','c','h','e','d','2','0','.','d','l','l',0} }
848 };
849
850 /***********************************************************************
851  *              create_xcursor_system_cursor
852  *
853  * Create an X cursor for a system cursor.
854  */
855 static Cursor create_xcursor_system_cursor( const ICONINFOEXW *info )
856 {
857     static const WCHAR idW[] = {'%','h','u',0};
858     const struct system_cursors *cursors;
859     unsigned int i;
860     Cursor cursor = 0;
861     HMODULE module;
862     HKEY key;
863     WCHAR *p, name[MAX_PATH * 2], valueW[64];
864     char valueA[64];
865     DWORD size, ret;
866
867     if (!pXcursorLibraryLoadCursor) return 0;
868     if (!info->szModName[0]) return 0;
869
870     p = strrchrW( info->szModName, '\\' );
871     strcpyW( name, p ? p + 1 : info->szModName );
872     p = name + strlenW( name );
873     *p++ = ',';
874     if (info->szResName[0]) strcpyW( p, info->szResName );
875     else sprintfW( p, idW, info->wResID );
876     valueA[0] = 0;
877
878     /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver\Cursors */
879     if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\X11 Driver\\Cursors", &key ))
880     {
881         size = sizeof(valueW) / sizeof(WCHAR);
882         ret = RegQueryValueExW( key, name, NULL, NULL, (BYTE *)valueW, &size );
883         RegCloseKey( key );
884         if (!ret)
885         {
886             if (!valueW[0]) return 0; /* force standard cursor */
887             if (!WideCharToMultiByte( CP_UNIXCP, 0, valueW, -1, valueA, sizeof(valueA), NULL, NULL ))
888                 valueA[0] = 0;
889             goto done;
890         }
891     }
892
893     if (info->szResName[0]) goto done;  /* only integer resources are supported here */
894     if (!(module = GetModuleHandleW( info->szModName ))) goto done;
895
896     for (i = 0; i < sizeof(module_cursors)/sizeof(module_cursors[0]); i++)
897         if (GetModuleHandleW( module_cursors[i].name ) == module) break;
898     if (i == sizeof(module_cursors)/sizeof(module_cursors[0])) goto done;
899
900     cursors = module_cursors[i].cursors;
901     for (i = 0; cursors[i].id; i++)
902         if (cursors[i].id == info->wResID)
903         {
904             strcpy( valueA, cursors[i].name );
905             break;
906         }
907
908 done:
909     if (valueA[0])
910     {
911         wine_tsx11_lock();
912         cursor = pXcursorLibraryLoadCursor( gdi_display, valueA );
913         wine_tsx11_unlock();
914         if (!cursor) WARN( "no system cursor found for %s mapped to %s\n",
915                            debugstr_w(name), debugstr_a(valueA) );
916     }
917     else WARN( "no system cursor found for %s\n", debugstr_w(name) );
918     return cursor;
919 }
920
921 #endif /* SONAME_LIBXCURSOR */
922
923
924 /***********************************************************************
925  *              create_cursor_from_bitmaps
926  *
927  * Create an X11 cursor from source bitmaps.
928  */
929 static Cursor create_cursor_from_bitmaps( HBITMAP src_xor, HBITMAP src_and, int width, int height,
930                                           int xor_y, int and_y, XColor *fg, XColor *bg,
931                                           int hotspot_x, int hotspot_y )
932 {
933     HDC src = 0, dst = 0;
934     HBITMAP bits = 0, mask = 0, mask_inv = 0;
935     Cursor cursor = 0;
936
937     if (!(src = CreateCompatibleDC( 0 ))) goto done;
938     if (!(dst = CreateCompatibleDC( 0 ))) goto done;
939
940     if (!(bits = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
941     if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
942     if (!(mask_inv = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
943
944     /* We have to do some magic here, as cursors are not fully
945      * compatible between Windows and X11. Under X11, there are
946      * only 3 possible color cursor: black, white and masked. So
947      * we map the 4th Windows color (invert the bits on the screen)
948      * to black and an additional white bit on an other place
949      * (+1,+1). This require some boolean arithmetic:
950      *
951      *         Windows          |          X11
952      * And    Xor      Result   |   Bits     Mask     Result
953      *  0      0     black      |    0        1     background
954      *  0      1     white      |    1        1     foreground
955      *  1      0     no change  |    X        0     no change
956      *  1      1     inverted   |    0        1     background
957      *
958      * which gives:
959      *  Bits = not 'And' and 'Xor' or 'And2' and 'Xor2'
960      *  Mask = not 'And' or 'Xor' or 'And2' and 'Xor2'
961      */
962     SelectObject( src, src_and );
963     SelectObject( dst, bits );
964     BitBlt( dst, 0, 0, width, height, src, 0, and_y, SRCCOPY );
965     SelectObject( dst, mask );
966     BitBlt( dst, 0, 0, width, height, src, 0, and_y, SRCCOPY );
967     SelectObject( dst, mask_inv );
968     BitBlt( dst, 0, 0, width, height, src, 0, and_y, SRCCOPY );
969     SelectObject( src, src_xor );
970     BitBlt( dst, 0, 0, width, height, src, 0, xor_y, SRCAND /* src & dst */ );
971     SelectObject( dst, bits );
972     BitBlt( dst, 0, 0, width, height, src, 0, xor_y, SRCERASE /* src & ~dst */ );
973     SelectObject( dst, mask );
974     BitBlt( dst, 0, 0, width, height, src, 0, xor_y, 0xdd0228 /* src | ~dst */ );
975     /* additional white */
976     SelectObject( src, mask_inv );
977     BitBlt( dst, 1, 1, width, height, src, 0, 0, SRCPAINT /* src | dst */);
978     SelectObject( dst, bits );
979     BitBlt( dst, 1, 1, width, height, src, 0, 0, SRCPAINT /* src | dst */ );
980
981     wine_tsx11_lock();
982     cursor = XCreatePixmapCursor( gdi_display, X11DRV_get_pixmap(bits), X11DRV_get_pixmap(mask),
983                                   fg, bg, hotspot_x, hotspot_y );
984     wine_tsx11_unlock();
985
986 done:
987     DeleteDC( src );
988     DeleteDC( dst );
989     DeleteObject( bits );
990     DeleteObject( mask );
991     DeleteObject( mask_inv );
992     return cursor;
993 }
994
995 /***********************************************************************
996  *              create_xlib_cursor
997  *
998  * Create an X cursor from a Windows one.
999  */
1000 static Cursor create_xlib_cursor( HDC hdc, const ICONINFOEXW *icon, int width, int height )
1001 {
1002     XColor fg, bg;
1003     Cursor cursor = None;
1004     HBITMAP xor_bitmap = 0;
1005     BITMAPINFO *info;
1006     unsigned int *color_bits = NULL, *ptr;
1007     unsigned char *mask_bits = NULL, *xor_bits = NULL;
1008     int i, x, y, has_alpha = 0;
1009     int rfg, gfg, bfg, rbg, gbg, bbg, fgBits, bgBits;
1010     unsigned int width_bytes = (width + 31) / 32 * 4;
1011
1012     if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] ))))
1013         return FALSE;
1014     info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1015     info->bmiHeader.biWidth = width;
1016     info->bmiHeader.biHeight = -height;
1017     info->bmiHeader.biPlanes = 1;
1018     info->bmiHeader.biBitCount = 1;
1019     info->bmiHeader.biCompression = BI_RGB;
1020     info->bmiHeader.biSizeImage = width_bytes * height;
1021     info->bmiHeader.biXPelsPerMeter = 0;
1022     info->bmiHeader.biYPelsPerMeter = 0;
1023     info->bmiHeader.biClrUsed = 0;
1024     info->bmiHeader.biClrImportant = 0;
1025
1026     if (!(mask_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
1027     if (!GetDIBits( hdc, icon->hbmMask, 0, height, mask_bits, info, DIB_RGB_COLORS )) goto done;
1028
1029     info->bmiHeader.biBitCount = 32;
1030     info->bmiHeader.biSizeImage = width * height * 4;
1031     if (!(color_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
1032     if (!(xor_bits = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, width_bytes * height ))) goto done;
1033     GetDIBits( hdc, icon->hbmColor, 0, height, color_bits, info, DIB_RGB_COLORS );
1034
1035     /* compute fg/bg color and xor bitmap based on average of the color values */
1036
1037     if (!(xor_bitmap = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
1038     rfg = gfg = bfg = rbg = gbg = bbg = fgBits = 0;
1039     for (y = 0, ptr = color_bits; y < height; y++)
1040     {
1041         for (x = 0; x < width; x++, ptr++)
1042         {
1043             int red   = (*ptr >> 16) & 0xff;
1044             int green = (*ptr >> 8) & 0xff;
1045             int blue  = (*ptr >> 0) & 0xff;
1046             if (red + green + blue > 0x40)
1047             {
1048                 rfg += red;
1049                 gfg += green;
1050                 bfg += blue;
1051                 fgBits++;
1052                 xor_bits[y * width_bytes + x / 8] |= 0x80 >> (x % 8);
1053             }
1054             else
1055             {
1056                 rbg += red;
1057                 gbg += green;
1058                 bbg += blue;
1059             }
1060         }
1061     }
1062     if (fgBits)
1063     {
1064         fg.red   = rfg * 257 / fgBits;
1065         fg.green = gfg * 257 / fgBits;
1066         fg.blue  = bfg * 257 / fgBits;
1067     }
1068     else fg.red = fg.green = fg.blue = 0;
1069     bgBits = width * height - fgBits;
1070     if (bgBits)
1071     {
1072         bg.red   = rbg * 257 / bgBits;
1073         bg.green = gbg * 257 / bgBits;
1074         bg.blue  = bbg * 257 / bgBits;
1075     }
1076     else bg.red = bg.green = bg.blue = 0;
1077
1078     info->bmiHeader.biBitCount = 1;
1079     info->bmiHeader.biSizeImage = width_bytes * height;
1080     SetDIBits( hdc, xor_bitmap, 0, height, xor_bits, info, DIB_RGB_COLORS );
1081
1082     /* generate mask from the alpha channel if we have one */
1083
1084     for (i = 0, ptr = color_bits; i < width * height; i++, ptr++)
1085         if ((has_alpha = (*ptr & 0xff000000) != 0)) break;
1086
1087     if (has_alpha)
1088     {
1089         memset( mask_bits, 0, width_bytes * height );
1090         for (y = 0, ptr = color_bits; y < height; y++)
1091             for (x = 0; x < width; x++, ptr++)
1092                 if ((*ptr >> 24) > 25) /* more than 10% alpha */
1093                     mask_bits[y * width_bytes + x / 8] |= 0x80 >> (x % 8);
1094
1095         info->bmiHeader.biBitCount = 1;
1096         info->bmiHeader.biSizeImage = width_bytes * height;
1097         SetDIBits( hdc, icon->hbmMask, 0, height, mask_bits, info, DIB_RGB_COLORS );
1098
1099         wine_tsx11_lock();
1100         cursor = XCreatePixmapCursor( gdi_display,
1101                                       X11DRV_get_pixmap(xor_bitmap),
1102                                       X11DRV_get_pixmap(icon->hbmMask),
1103                                       &fg, &bg, icon->xHotspot, icon->yHotspot );
1104         wine_tsx11_unlock();
1105     }
1106     else
1107     {
1108         cursor = create_cursor_from_bitmaps( xor_bitmap, icon->hbmMask, width, height, 0, 0,
1109                                              &fg, &bg, icon->xHotspot, icon->yHotspot );
1110     }
1111
1112 done:
1113     DeleteObject( xor_bitmap );
1114     HeapFree( GetProcessHeap(), 0, info );
1115     HeapFree( GetProcessHeap(), 0, color_bits );
1116     HeapFree( GetProcessHeap(), 0, xor_bits );
1117     HeapFree( GetProcessHeap(), 0, mask_bits );
1118     return cursor;
1119 }
1120
1121 /***********************************************************************
1122  *              create_cursor
1123  *
1124  * Create an X cursor from a Windows one.
1125  */
1126 static Cursor create_cursor( HANDLE handle )
1127 {
1128     Cursor cursor = 0;
1129     ICONINFOEXW info;
1130     BITMAP bm;
1131
1132     if (!handle) return get_empty_cursor();
1133
1134     info.cbSize = sizeof(info);
1135     if (!GetIconInfoExW( handle, &info )) return 0;
1136
1137 #ifdef SONAME_LIBXCURSOR
1138     if (use_system_cursors && (cursor = create_xcursor_system_cursor( &info )))
1139     {
1140         DeleteObject( info.hbmColor );
1141         DeleteObject( info.hbmMask );
1142         return cursor;
1143     }
1144 #endif
1145
1146     GetObjectW( info.hbmMask, sizeof(bm), &bm );
1147     if (!info.hbmColor) bm.bmHeight /= 2;
1148
1149     /* make sure hotspot is valid */
1150     if (info.xHotspot >= bm.bmWidth || info.yHotspot >= bm.bmHeight)
1151     {
1152         info.xHotspot = bm.bmWidth / 2;
1153         info.yHotspot = bm.bmHeight / 2;
1154     }
1155
1156     if (info.hbmColor)
1157     {
1158         HDC hdc = CreateCompatibleDC( 0 );
1159         if (hdc)
1160         {
1161 #ifdef SONAME_LIBXCURSOR
1162             if (pXcursorImagesLoadCursor)
1163                 cursor = create_xcursor_cursor( hdc, &info, handle, bm.bmWidth, bm.bmHeight );
1164 #endif
1165             if (!cursor) cursor = create_xlib_cursor( hdc, &info, bm.bmWidth, bm.bmHeight );
1166         }
1167         DeleteObject( info.hbmColor );
1168         DeleteDC( hdc );
1169     }
1170     else
1171     {
1172         XColor fg, bg;
1173         fg.red = fg.green = fg.blue = 0xffff;
1174         bg.red = bg.green = bg.blue = 0;
1175         cursor = create_cursor_from_bitmaps( info.hbmMask, info.hbmMask, bm.bmWidth, bm.bmHeight,
1176                                              bm.bmHeight, 0, &fg, &bg, info.xHotspot, info.yHotspot );
1177     }
1178
1179     DeleteObject( info.hbmMask );
1180     return cursor;
1181 }
1182
1183 /***********************************************************************
1184  *              DestroyCursorIcon (X11DRV.@)
1185  */
1186 void CDECL X11DRV_DestroyCursorIcon( HCURSOR handle )
1187 {
1188     Cursor cursor;
1189
1190     wine_tsx11_lock();
1191     if (cursor_context && !XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&cursor ))
1192     {
1193         TRACE( "%p xid %lx\n", handle, cursor );
1194         XFreeCursor( gdi_display, cursor );
1195         XDeleteContext( gdi_display, (XID)handle, cursor_context );
1196     }
1197     wine_tsx11_unlock();
1198 }
1199
1200 /***********************************************************************
1201  *              SetCursor (X11DRV.@)
1202  */
1203 void CDECL X11DRV_SetCursor( HCURSOR handle )
1204 {
1205     if (InterlockedExchangePointer( (void **)&last_cursor, handle ) != handle ||
1206         GetTickCount() - last_cursor_change > 100)
1207     {
1208         last_cursor_change = GetTickCount();
1209         if (clipping_cursor) set_window_cursor( init_clip_window(), handle );
1210         else if (cursor_window) SendNotifyMessageW( cursor_window, WM_X11DRV_SET_CURSOR, 0, (LPARAM)handle );
1211     }
1212 }
1213
1214 /***********************************************************************
1215  *              SetCursorPos (X11DRV.@)
1216  */
1217 BOOL CDECL X11DRV_SetCursorPos( INT x, INT y )
1218 {
1219     struct x11drv_thread_data *data = x11drv_init_thread_data();
1220
1221     if (data->xi2_state == xi_enabled) return TRUE;
1222
1223     TRACE( "warping to (%d,%d)\n", x, y );
1224
1225     wine_tsx11_lock();
1226     XWarpPointer( data->display, root_window, root_window, 0, 0, 0, 0,
1227                   x - virtual_screen_rect.left, y - virtual_screen_rect.top );
1228     XFlush( data->display ); /* avoids bad mouse lag in games that do their own mouse warping */
1229     wine_tsx11_unlock();
1230     return TRUE;
1231 }
1232
1233 /***********************************************************************
1234  *              GetCursorPos (X11DRV.@)
1235  */
1236 BOOL CDECL X11DRV_GetCursorPos(LPPOINT pos)
1237 {
1238     Display *display = thread_init_display();
1239     Window root, child;
1240     int rootX, rootY, winX, winY;
1241     unsigned int xstate;
1242     BOOL ret;
1243
1244     wine_tsx11_lock();
1245     ret = XQueryPointer( display, root_window, &root, &child, &rootX, &rootY, &winX, &winY, &xstate );
1246     if (ret)
1247     {
1248         pos->x = winX + virtual_screen_rect.left;
1249         pos->y = winY + virtual_screen_rect.top;
1250         TRACE("pointer at (%d,%d)\n", pos->x, pos->y );
1251     }
1252     wine_tsx11_unlock();
1253     return ret;
1254 }
1255
1256 /***********************************************************************
1257  *              ClipCursor (X11DRV.@)
1258  */
1259 BOOL CDECL X11DRV_ClipCursor( LPCRECT clip )
1260 {
1261     if (!clip)
1262     {
1263         ungrab_clipping_window();
1264         return TRUE;
1265     }
1266
1267     if (GetWindowThreadProcessId( GetDesktopWindow(), NULL ) == GetCurrentThreadId())
1268         return TRUE;  /* don't clip in the desktop process */
1269
1270     if (grab_pointer)
1271     {
1272         HWND foreground = GetForegroundWindow();
1273
1274         /* we are clipping if the clip rectangle is smaller than the screen */
1275         if (clip->left > virtual_screen_rect.left || clip->right < virtual_screen_rect.right ||
1276             clip->top > virtual_screen_rect.top || clip->bottom < virtual_screen_rect.bottom)
1277         {
1278             DWORD tid, pid;
1279
1280             /* forward request to the foreground window if it's in a different thread */
1281             tid = GetWindowThreadProcessId( foreground, &pid );
1282             if (tid && tid != GetCurrentThreadId() && pid == GetCurrentProcessId())
1283             {
1284                 TRACE( "forwarding clip request to %p\n", foreground );
1285                 if (SendMessageW( foreground, WM_X11DRV_CLIP_CURSOR, 0, 0 )) return TRUE;
1286             }
1287             else if (grab_clipping_window( clip, FALSE )) return TRUE;
1288         }
1289         else /* if currently clipping, check if we should switch to fullscreen clipping */
1290         {
1291             struct x11drv_thread_data *data = x11drv_thread_data();
1292             if (data && data->clip_hwnd)
1293             {
1294                 if (EqualRect( clip, &clip_rect ) || clip_fullscreen_window( foreground, TRUE ))
1295                     return TRUE;
1296             }
1297         }
1298     }
1299     ungrab_clipping_window();
1300     return TRUE;
1301 }
1302
1303 /***********************************************************************
1304  *           X11DRV_ButtonPress
1305  */
1306 void X11DRV_ButtonPress( HWND hwnd, XEvent *xev )
1307 {
1308     XButtonEvent *event = &xev->xbutton;
1309     int buttonNum = event->button - 1;
1310     INPUT input;
1311
1312     if (buttonNum >= NB_BUTTONS) return;
1313
1314     TRACE( "hwnd %p/%lx button %u pos %d,%d\n", hwnd, event->window, buttonNum, event->x, event->y );
1315
1316     input.u.mi.dx          = event->x;
1317     input.u.mi.dy          = event->y;
1318     input.u.mi.mouseData   = button_down_data[buttonNum];
1319     input.u.mi.dwFlags     = button_down_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
1320     input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
1321     input.u.mi.dwExtraInfo = 0;
1322
1323     update_user_time( event->time );
1324     send_mouse_input( hwnd, event->window, event->state, &input );
1325 }
1326
1327
1328 /***********************************************************************
1329  *           X11DRV_ButtonRelease
1330  */
1331 void X11DRV_ButtonRelease( HWND hwnd, XEvent *xev )
1332 {
1333     XButtonEvent *event = &xev->xbutton;
1334     int buttonNum = event->button - 1;
1335     INPUT input;
1336
1337     if (buttonNum >= NB_BUTTONS || !button_up_flags[buttonNum]) return;
1338
1339     TRACE( "hwnd %p/%lx button %u pos %d,%d\n", hwnd, event->window, buttonNum, event->x, event->y );
1340
1341     input.u.mi.dx          = event->x;
1342     input.u.mi.dy          = event->y;
1343     input.u.mi.mouseData   = button_up_data[buttonNum];
1344     input.u.mi.dwFlags     = button_up_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
1345     input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
1346     input.u.mi.dwExtraInfo = 0;
1347
1348     send_mouse_input( hwnd, event->window, event->state, &input );
1349 }
1350
1351
1352 /***********************************************************************
1353  *           X11DRV_MotionNotify
1354  */
1355 void X11DRV_MotionNotify( HWND hwnd, XEvent *xev )
1356 {
1357     XMotionEvent *event = &xev->xmotion;
1358     INPUT input;
1359
1360     TRACE( "hwnd %p/%lx pos %d,%d is_hint %d\n", hwnd, event->window, event->x, event->y, event->is_hint );
1361
1362     input.u.mi.dx          = event->x;
1363     input.u.mi.dy          = event->y;
1364     input.u.mi.mouseData   = 0;
1365     input.u.mi.dwFlags     = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
1366     input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
1367     input.u.mi.dwExtraInfo = 0;
1368
1369     send_mouse_input( hwnd, event->window, event->state, &input );
1370 }
1371
1372
1373 /***********************************************************************
1374  *           X11DRV_EnterNotify
1375  */
1376 void X11DRV_EnterNotify( HWND hwnd, XEvent *xev )
1377 {
1378     XCrossingEvent *event = &xev->xcrossing;
1379     INPUT input;
1380
1381     TRACE( "hwnd %p/%lx pos %d,%d detail %d\n", hwnd, event->window, event->x, event->y, event->detail );
1382
1383     if (event->detail == NotifyVirtual || event->detail == NotifyNonlinearVirtual) return;
1384     if (event->window == x11drv_thread_data()->grab_window) return;
1385
1386     /* simulate a mouse motion event */
1387     input.u.mi.dx          = event->x;
1388     input.u.mi.dy          = event->y;
1389     input.u.mi.mouseData   = 0;
1390     input.u.mi.dwFlags     = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
1391     input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
1392     input.u.mi.dwExtraInfo = 0;
1393
1394     send_mouse_input( hwnd, event->window, event->state, &input );
1395 }
1396
1397 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
1398
1399 /***********************************************************************
1400  *           X11DRV_RawMotion
1401  */
1402 static void X11DRV_RawMotion( XIRawEvent *event )
1403 {
1404     const double *values = event->valuators.values;
1405     INPUT input;
1406
1407     if (!event->valuators.mask_len) return;
1408
1409     input.u.mi.dx          = 0;
1410     input.u.mi.dy          = 0;
1411     input.u.mi.mouseData   = 0;
1412     input.u.mi.dwFlags     = MOUSEEVENTF_MOVE;
1413     input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
1414     input.u.mi.dwExtraInfo = 0;
1415
1416     if (XIMaskIsSet( event->valuators.mask, 0 )) input.u.mi.dx = *values++;
1417     if (XIMaskIsSet( event->valuators.mask, 1 )) input.u.mi.dy = *values++;
1418
1419     TRACE( "pos %d,%d\n", input.u.mi.dx, input.u.mi.dy );
1420
1421     input.type = INPUT_MOUSE;
1422     __wine_send_input( 0, &input );
1423 }
1424
1425 #endif /* HAVE_X11_EXTENSIONS_XINPUT2_H */
1426
1427
1428 /***********************************************************************
1429  *              X11DRV_XInput2_Init
1430  */
1431 void X11DRV_XInput2_Init(void)
1432 {
1433 #if defined(SONAME_LIBXI) && defined(HAVE_X11_EXTENSIONS_XINPUT2_H)
1434     int event, error;
1435     void *libxi_handle = wine_dlopen( SONAME_LIBXI, RTLD_NOW, NULL, 0 );
1436
1437     if (!libxi_handle)
1438     {
1439         WARN( "couldn't load %s\n", SONAME_LIBXI );
1440         return;
1441     }
1442 #define LOAD_FUNCPTR(f) \
1443     if (!(p##f = wine_dlsym( libxi_handle, #f, NULL, 0))) \
1444     { \
1445         WARN("Failed to load %s.\n", #f); \
1446         return; \
1447     }
1448
1449     LOAD_FUNCPTR(XIFreeDeviceInfo);
1450     LOAD_FUNCPTR(XIQueryDevice);
1451     LOAD_FUNCPTR(XIQueryVersion);
1452     LOAD_FUNCPTR(XISelectEvents);
1453 #undef LOAD_FUNCPTR
1454
1455     wine_tsx11_lock();
1456     xinput2_available = XQueryExtension( gdi_display, "XInputExtension", &xinput2_opcode, &event, &error );
1457     wine_tsx11_unlock();
1458 #else
1459     TRACE( "X Input 2 support not compiled in.\n" );
1460 #endif
1461 }
1462
1463
1464 /***********************************************************************
1465  *           X11DRV_GenericEvent
1466  */
1467 void X11DRV_GenericEvent( HWND hwnd, XEvent *xev )
1468 {
1469 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
1470     XGenericEventCookie *event = &xev->xcookie;
1471
1472     if (!event->data) return;
1473     if (event->extension != xinput2_opcode) return;
1474
1475     switch (event->evtype)
1476     {
1477     case XI_RawMotion:
1478         X11DRV_RawMotion( event->data );
1479         break;
1480
1481     default:
1482         TRACE( "Unhandled event %#x\n", event->evtype );
1483         break;
1484     }
1485 #endif
1486 }