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