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