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