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