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