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