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