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