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