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