winex11: Merge updating the mouse state and sending the input into a single helper...
[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
29 #ifdef SONAME_LIBXCURSOR
30 # include <X11/Xcursor/Xcursor.h>
31 static void *xcursor_handle;
32 # define MAKE_FUNCPTR(f) static typeof(f) * p##f
33 MAKE_FUNCPTR(XcursorImageCreate);
34 MAKE_FUNCPTR(XcursorImageDestroy);
35 MAKE_FUNCPTR(XcursorImageLoadCursor);
36 MAKE_FUNCPTR(XcursorImagesCreate);
37 MAKE_FUNCPTR(XcursorImagesDestroy);
38 MAKE_FUNCPTR(XcursorImagesLoadCursor);
39 MAKE_FUNCPTR(XcursorLibraryLoadCursor);
40 # undef MAKE_FUNCPTR
41 #endif /* SONAME_LIBXCURSOR */
42
43 #define NONAMELESSUNION
44 #define NONAMELESSSTRUCT
45 #define OEMRESOURCE
46 #include "windef.h"
47 #include "winbase.h"
48 #include "winreg.h"
49
50 #include "x11drv.h"
51 #include "wine/server.h"
52 #include "wine/library.h"
53 #include "wine/unicode.h"
54 #include "wine/debug.h"
55
56 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
57
58 /**********************************************************************/
59
60 #ifndef Button6Mask
61 #define Button6Mask (1<<13)
62 #endif
63 #ifndef Button7Mask
64 #define Button7Mask (1<<14)
65 #endif
66
67 #define NB_BUTTONS   9     /* Windows can handle 5 buttons and the wheel too */
68
69 static const UINT button_down_flags[NB_BUTTONS] =
70 {
71     MOUSEEVENTF_LEFTDOWN,
72     MOUSEEVENTF_MIDDLEDOWN,
73     MOUSEEVENTF_RIGHTDOWN,
74     MOUSEEVENTF_WHEEL,
75     MOUSEEVENTF_WHEEL,
76     MOUSEEVENTF_XDOWN,  /* FIXME: horizontal wheel */
77     MOUSEEVENTF_XDOWN,
78     MOUSEEVENTF_XDOWN,
79     MOUSEEVENTF_XDOWN
80 };
81
82 static const UINT button_up_flags[NB_BUTTONS] =
83 {
84     MOUSEEVENTF_LEFTUP,
85     MOUSEEVENTF_MIDDLEUP,
86     MOUSEEVENTF_RIGHTUP,
87     0,
88     0,
89     MOUSEEVENTF_XUP,
90     MOUSEEVENTF_XUP,
91     MOUSEEVENTF_XUP,
92     MOUSEEVENTF_XUP
93 };
94
95 static HWND cursor_window;
96 static DWORD last_time_modified;
97 static XContext cursor_context;
98 static Cursor create_cursor( HANDLE handle );
99
100 BOOL CDECL X11DRV_SetCursorPos( INT x, INT y );
101
102
103 /***********************************************************************
104  *              X11DRV_Xcursor_Init
105  *
106  * Load the Xcursor library for use.
107  */
108 void X11DRV_Xcursor_Init(void)
109 {
110 #ifdef SONAME_LIBXCURSOR
111     xcursor_handle = wine_dlopen(SONAME_LIBXCURSOR, RTLD_NOW, NULL, 0);
112     if (!xcursor_handle)  /* wine_dlopen failed. */
113     {
114         WARN("Xcursor failed to load.  Using fallback code.\n");
115         return;
116     }
117 #define LOAD_FUNCPTR(f) \
118         p##f = wine_dlsym(xcursor_handle, #f, NULL, 0)
119
120     LOAD_FUNCPTR(XcursorImageCreate);
121     LOAD_FUNCPTR(XcursorImageDestroy);
122     LOAD_FUNCPTR(XcursorImageLoadCursor);
123     LOAD_FUNCPTR(XcursorImagesCreate);
124     LOAD_FUNCPTR(XcursorImagesDestroy);
125     LOAD_FUNCPTR(XcursorImagesLoadCursor);
126     LOAD_FUNCPTR(XcursorLibraryLoadCursor);
127 #undef LOAD_FUNCPTR
128 #endif /* SONAME_LIBXCURSOR */
129 }
130
131
132 /***********************************************************************
133  *              get_empty_cursor
134  */
135 static Cursor get_empty_cursor(void)
136 {
137     static Cursor cursor;
138     static const char data[] = { 0 };
139
140     wine_tsx11_lock();
141     if (!cursor)
142     {
143         XColor bg;
144         Pixmap pixmap;
145
146         bg.red = bg.green = bg.blue = 0x0000;
147         pixmap = XCreateBitmapFromData( gdi_display, root_window, data, 1, 1 );
148         if (pixmap)
149         {
150             cursor = XCreatePixmapCursor( gdi_display, pixmap, pixmap, &bg, &bg, 0, 0 );
151             XFreePixmap( gdi_display, pixmap );
152         }
153     }
154     wine_tsx11_unlock();
155     return cursor;
156 }
157
158 /***********************************************************************
159  *              set_window_cursor
160  */
161 void set_window_cursor( struct x11drv_win_data *data, HCURSOR handle )
162 {
163     Cursor cursor, prev;
164
165     wine_tsx11_lock();
166     if (!handle) cursor = get_empty_cursor();
167     else if (!cursor_context || XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&cursor ))
168     {
169         /* try to create it */
170         wine_tsx11_unlock();
171         if (!(cursor = create_cursor( handle ))) return;
172
173         wine_tsx11_lock();
174         if (!cursor_context) cursor_context = XUniqueContext();
175         if (!XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&prev ))
176         {
177             /* someone else was here first */
178             XFreeCursor( gdi_display, cursor );
179             cursor = prev;
180         }
181         else
182         {
183             XSaveContext( gdi_display, (XID)handle, cursor_context, (char *)cursor );
184             TRACE( "cursor %p created %lx\n", handle, cursor );
185         }
186     }
187
188     XDefineCursor( gdi_display, data->whole_window, cursor );
189     /* make the change take effect immediately */
190     XFlush( gdi_display );
191     data->cursor = handle;
192     wine_tsx11_unlock();
193 }
194
195 /***********************************************************************
196  *              sync_window_cursor
197  */
198 void sync_window_cursor( struct x11drv_win_data *data )
199 {
200     HCURSOR cursor;
201
202     SERVER_START_REQ( set_cursor )
203     {
204         req->flags = 0;
205         wine_server_call( req );
206         cursor = reply->prev_count >= 0 ? wine_server_ptr_handle( reply->prev_handle ) : 0;
207     }
208     SERVER_END_REQ;
209
210     if (data->cursor != cursor) set_window_cursor( data, cursor );
211 }
212
213 /***********************************************************************
214  *              send_mouse_input
215  *
216  * Update the various window states on a mouse event.
217  */
218 static void send_mouse_input( HWND hwnd, UINT flags, Window window, int x, int y,
219                               unsigned int state, DWORD mouse_data, Time time )
220 {
221     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
222     POINT pt;
223     INPUT input;
224
225     if (!data) return;
226
227     if (window == data->whole_window)
228     {
229         x += data->whole_rect.left - data->client_rect.left;
230         y += data->whole_rect.top - data->client_rect.top;
231     }
232     if (window == root_window)
233     {
234         x += virtual_screen_rect.left;
235         y += virtual_screen_rect.top;
236     }
237     pt.x = x;
238     pt.y = y;
239     if (GetWindowLongW( data->hwnd, GWL_EXSTYLE ) & WS_EX_LAYOUTRTL)
240         pt.x = data->client_rect.right - data->client_rect.left - 1 - pt.x;
241     MapWindowPoints( hwnd, 0, &pt, 1 );
242
243     if (InterlockedExchangePointer( (void **)&cursor_window, hwnd ) != hwnd ||
244         GetTickCount() - last_time_modified > 100)
245     {
246         cursor_window = hwnd;
247         sync_window_cursor( data );
248     }
249     last_time_modified = GetTickCount();
250
251     if (hwnd != GetDesktopWindow()) hwnd = GetAncestor( hwnd, GA_ROOT );
252
253     /* update the wine server Z-order */
254
255     if (window != x11drv_thread_data()->grab_window &&
256         /* ignore event if a button is pressed, since the mouse is then grabbed too */
257         !(state & (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask|Button6Mask|Button7Mask)))
258     {
259         RECT rect;
260         SetRect( &rect, pt.x, pt.y, pt.x + 1, pt.y + 1 );
261         MapWindowPoints( 0, hwnd, (POINT *)&rect, 2 );
262
263         SERVER_START_REQ( update_window_zorder )
264         {
265             req->window      = wine_server_user_handle( hwnd );
266             req->rect.left   = rect.left;
267             req->rect.top    = rect.top;
268             req->rect.right  = rect.right;
269             req->rect.bottom = rect.bottom;
270             wine_server_call( req );
271         }
272         SERVER_END_REQ;
273     }
274
275     input.type             = INPUT_MOUSE;
276     input.u.mi.dx          = pt.x;
277     input.u.mi.dy          = pt.y;
278     input.u.mi.mouseData   = mouse_data;
279     input.u.mi.dwFlags     = flags;
280     input.u.mi.time        = EVENT_x11_time_to_win32_time( time );
281     input.u.mi.dwExtraInfo = 0;
282
283     __wine_send_input( hwnd, &input );
284 }
285
286 #ifdef SONAME_LIBXCURSOR
287
288 /***********************************************************************
289  *              create_xcursor_frame
290  *
291  * Use Xcursor to create a frame of an X cursor from a Windows one.
292  */
293 static XcursorImage *create_xcursor_frame( HDC hdc, const ICONINFOEXW *iinfo, HANDLE icon,
294                                            HBITMAP hbmColor, unsigned char *color_bits, int color_size,
295                                            HBITMAP hbmMask, unsigned char *mask_bits, int mask_size,
296                                            int width, int height, int istep )
297 {
298     XcursorImage *image, *ret = NULL;
299     int x, y, i, has_alpha;
300     XcursorPixel *ptr;
301
302     wine_tsx11_lock();
303     image = pXcursorImageCreate( width, height );
304     wine_tsx11_unlock();
305     if (!image)
306     {
307         ERR("X11 failed to produce a cursor frame!\n");
308         goto cleanup;
309     }
310
311     image->xhot = iinfo->xHotspot;
312     image->yhot = iinfo->yHotspot;
313     image->delay = 100; /* TODO: find a way to get the proper delay */
314
315     /* draw the cursor frame to a temporary buffer then copy it into the XcursorImage */
316     memset( color_bits, 0x00, color_size );
317     SelectObject( hdc, hbmColor );
318     if (!DrawIconEx( hdc, 0, 0, icon, width, height, istep, NULL, DI_NORMAL ))
319     {
320         TRACE("Could not draw frame %d (walk past end of frames).\n", istep);
321         goto cleanup;
322     }
323     memcpy( image->pixels, color_bits, color_size );
324
325     /* check if the cursor frame was drawn with an alpha channel */
326     for (i = 0, ptr = image->pixels; i < width * height; i++, ptr++)
327         if ((has_alpha = (*ptr & 0xff000000) != 0)) break;
328
329     /* if no alpha channel was drawn then generate it from the mask */
330     if (!has_alpha)
331     {
332         unsigned int width_bytes = (width + 31) / 32 * 4;
333
334         /* draw the cursor mask to a temporary buffer */
335         memset( mask_bits, 0xFF, mask_size );
336         SelectObject( hdc, hbmMask );
337         if (!DrawIconEx( hdc, 0, 0, icon, width, height, istep, NULL, DI_MASK ))
338         {
339             ERR("Failed to draw frame mask %d.\n", istep);
340             goto cleanup;
341         }
342         /* use the buffer to directly modify the XcursorImage alpha channel */
343         for (y = 0, ptr = image->pixels; y < height; y++)
344             for (x = 0; x < width; x++, ptr++)
345                 if (!((mask_bits[y * width_bytes + x / 8] << (x % 8)) & 0x80))
346                     *ptr |= 0xff000000;
347     }
348     ret = image;
349
350 cleanup:
351     if (ret == NULL) pXcursorImageDestroy( image );
352     return ret;
353 }
354
355 /***********************************************************************
356  *              create_xcursor_cursor
357  *
358  * Use Xcursor to create an X cursor from a Windows one.
359  */
360 static Cursor create_xcursor_cursor( HDC hdc, const ICONINFOEXW *iinfo, HANDLE icon, int width, int height )
361 {
362     unsigned char *color_bits, *mask_bits;
363     HBITMAP hbmColor = 0, hbmMask = 0;
364     XcursorImage **imgs, *image;
365     int color_size, mask_size;
366     BITMAPINFO *info = NULL;
367     XcursorImages *images;
368     Cursor cursor = 0;
369     int nFrames = 0;
370
371     if (!(imgs = HeapAlloc( GetProcessHeap(), 0, sizeof(XcursorImage*) ))) return 0;
372
373     /* Allocate all of the resources necessary to obtain a cursor frame */
374     if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto cleanup;
375     info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
376     info->bmiHeader.biWidth = width;
377     info->bmiHeader.biHeight = -height;
378     info->bmiHeader.biPlanes = 1;
379     info->bmiHeader.biCompression = BI_RGB;
380     info->bmiHeader.biXPelsPerMeter = 0;
381     info->bmiHeader.biYPelsPerMeter = 0;
382     info->bmiHeader.biClrUsed = 0;
383     info->bmiHeader.biClrImportant = 0;
384     info->bmiHeader.biBitCount = 32;
385     color_size = width * height * 4;
386     info->bmiHeader.biSizeImage = color_size;
387     hbmColor = CreateDIBSection( hdc, info, DIB_RGB_COLORS, (VOID **) &color_bits, NULL, 0);
388     if (!hbmColor)
389     {
390         ERR("Failed to create DIB section for cursor color data!\n");
391         goto cleanup;
392     }
393     info->bmiHeader.biBitCount = 1;
394     mask_size = ((width + 31) / 32 * 4) * height; /* width_bytes * height */
395     info->bmiHeader.biSizeImage = mask_size;
396     hbmMask = CreateDIBSection( hdc, info, DIB_RGB_COLORS, (VOID **) &mask_bits, NULL, 0);
397     if (!hbmMask)
398     {
399         ERR("Failed to create DIB section for cursor mask data!\n");
400         goto cleanup;
401     }
402
403     /* Create an XcursorImage for each frame of the cursor */
404     while (1)
405     {
406         XcursorImage **imgstmp;
407
408         image = create_xcursor_frame( hdc, iinfo, icon,
409                                       hbmColor, color_bits, color_size,
410                                       hbmMask, mask_bits, mask_size,
411                                       width, height, nFrames );
412         if (!image) break; /* no more drawable frames */
413
414         imgs[nFrames++] = image;
415         if (!(imgstmp = HeapReAlloc( GetProcessHeap(), 0, imgs, (nFrames+1)*sizeof(XcursorImage*) ))) goto cleanup;
416         imgs = imgstmp;
417     }
418
419     /* Build an X cursor out of all of the frames */
420     if (!(images = pXcursorImagesCreate( nFrames ))) goto cleanup;
421     for (images->nimage = 0; images->nimage < nFrames; images->nimage++)
422         images->images[images->nimage] = imgs[images->nimage];
423     wine_tsx11_lock();
424     cursor = pXcursorImagesLoadCursor( gdi_display, images );
425     wine_tsx11_unlock();
426     pXcursorImagesDestroy( images ); /* Note: this frees each individual frame (calls XcursorImageDestroy) */
427     HeapFree( GetProcessHeap(), 0, imgs );
428     imgs = NULL;
429
430 cleanup:
431     if (imgs)
432     {
433         /* Failed to produce a cursor, free previously allocated frames */
434         for (nFrames--; nFrames >= 0; nFrames--)
435             pXcursorImageDestroy( imgs[nFrames] );
436         HeapFree( GetProcessHeap(), 0, imgs );
437     }
438     /* Cleanup all of the resources used to obtain the frame data */
439     if (hbmColor) DeleteObject( hbmColor );
440     if (hbmMask) DeleteObject( hbmMask );
441     HeapFree( GetProcessHeap(), 0, info );
442     return cursor;
443 }
444
445
446 struct system_cursors
447 {
448     WORD id;
449     const char *name;
450 };
451
452 static const struct system_cursors user32_cursors[] =
453 {
454     { OCR_NORMAL,      "left_ptr" },
455     { OCR_IBEAM,       "xterm" },
456     { OCR_WAIT,        "watch" },
457     { OCR_CROSS,       "cross" },
458     { OCR_UP,          "center_ptr" },
459     { OCR_SIZE,        "fleur" },
460     { OCR_SIZEALL,     "fleur" },
461     { OCR_ICON,        "icon" },
462     { OCR_SIZENWSE,    "nwse-resize" },
463     { OCR_SIZENESW,    "nesw-resize" },
464     { OCR_SIZEWE,      "ew-resize" },
465     { OCR_SIZENS,      "ns-resize" },
466     { OCR_NO,          "not-allowed" },
467     { OCR_HAND,        "hand2" },
468     { OCR_APPSTARTING, "left_ptr_watch" },
469     { OCR_HELP,        "question_arrow" },
470     { 0 }
471 };
472
473 static const struct system_cursors comctl32_cursors[] =
474 {
475     { 102, "move" },
476     { 104, "copy" },
477     { 105, "left_ptr" },
478     { 106, "row-resize" },
479     { 107, "row-resize" },
480     { 108, "hand2" },
481     { 135, "col-resize" },
482     { 0 }
483 };
484
485 static const struct system_cursors ole32_cursors[] =
486 {
487     { 1, "no-drop" },
488     { 2, "move" },
489     { 3, "copy" },
490     { 4, "alias" },
491     { 0 }
492 };
493
494 static const struct system_cursors riched20_cursors[] =
495 {
496     { 105, "hand2" },
497     { 107, "right_ptr" },
498     { 109, "copy" },
499     { 110, "move" },
500     { 111, "no-drop" },
501     { 0 }
502 };
503
504 static const struct
505 {
506     const struct system_cursors *cursors;
507     WCHAR name[16];
508 } module_cursors[] =
509 {
510     { user32_cursors, {'u','s','e','r','3','2','.','d','l','l',0} },
511     { comctl32_cursors, {'c','o','m','c','t','l','3','2','.','d','l','l',0} },
512     { ole32_cursors, {'o','l','e','3','2','.','d','l','l',0} },
513     { riched20_cursors, {'r','i','c','h','e','d','2','0','.','d','l','l',0} }
514 };
515
516 /***********************************************************************
517  *              create_xcursor_system_cursor
518  *
519  * Create an X cursor for a system cursor.
520  */
521 static Cursor create_xcursor_system_cursor( const ICONINFOEXW *info )
522 {
523     static const WCHAR idW[] = {'%','h','u',0};
524     const struct system_cursors *cursors;
525     unsigned int i;
526     Cursor cursor = 0;
527     HMODULE module;
528     HKEY key;
529     WCHAR *p, name[MAX_PATH * 2], valueW[64];
530     char valueA[64];
531     DWORD size, ret;
532
533     if (!pXcursorLibraryLoadCursor) return 0;
534     if (!info->szModName[0]) return 0;
535
536     p = strrchrW( info->szModName, '\\' );
537     strcpyW( name, p ? p + 1 : info->szModName );
538     p = name + strlenW( name );
539     *p++ = ',';
540     if (info->szResName[0]) strcpyW( p, info->szResName );
541     else sprintfW( p, idW, info->wResID );
542     valueA[0] = 0;
543
544     /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver\Cursors */
545     if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\X11 Driver\\Cursors", &key ))
546     {
547         size = sizeof(valueW) / sizeof(WCHAR);
548         ret = RegQueryValueExW( key, name, NULL, NULL, (BYTE *)valueW, &size );
549         RegCloseKey( key );
550         if (!ret)
551         {
552             if (!valueW[0]) return 0; /* force standard cursor */
553             if (!WideCharToMultiByte( CP_UNIXCP, 0, valueW, -1, valueA, sizeof(valueA), NULL, NULL ))
554                 valueA[0] = 0;
555             goto done;
556         }
557     }
558
559     if (info->szResName[0]) goto done;  /* only integer resources are supported here */
560     if (!(module = GetModuleHandleW( info->szModName ))) goto done;
561
562     for (i = 0; i < sizeof(module_cursors)/sizeof(module_cursors[0]); i++)
563         if (GetModuleHandleW( module_cursors[i].name ) == module) break;
564     if (i == sizeof(module_cursors)/sizeof(module_cursors[0])) goto done;
565
566     cursors = module_cursors[i].cursors;
567     for (i = 0; cursors[i].id; i++)
568         if (cursors[i].id == info->wResID)
569         {
570             strcpy( valueA, cursors[i].name );
571             break;
572         }
573
574 done:
575     if (valueA[0])
576     {
577         wine_tsx11_lock();
578         cursor = pXcursorLibraryLoadCursor( gdi_display, valueA );
579         wine_tsx11_unlock();
580         if (!cursor) WARN( "no system cursor found for %s mapped to %s\n",
581                            debugstr_w(name), debugstr_a(valueA) );
582     }
583     else WARN( "no system cursor found for %s\n", debugstr_w(name) );
584     return cursor;
585 }
586
587 #endif /* SONAME_LIBXCURSOR */
588
589
590 /***********************************************************************
591  *              create_cursor_from_bitmaps
592  *
593  * Create an X11 cursor from source bitmaps.
594  */
595 static Cursor create_cursor_from_bitmaps( HBITMAP src_xor, HBITMAP src_and, int width, int height,
596                                           int xor_y, int and_y, XColor *fg, XColor *bg,
597                                           int hotspot_x, int hotspot_y )
598 {
599     HDC src = 0, dst = 0;
600     HBITMAP bits = 0, mask = 0, mask_inv = 0;
601     Cursor cursor = 0;
602
603     if (!(src = CreateCompatibleDC( 0 ))) goto done;
604     if (!(dst = CreateCompatibleDC( 0 ))) goto done;
605
606     if (!(bits = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
607     if (!(mask = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
608     if (!(mask_inv = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
609
610     /* We have to do some magic here, as cursors are not fully
611      * compatible between Windows and X11. Under X11, there are
612      * only 3 possible color cursor: black, white and masked. So
613      * we map the 4th Windows color (invert the bits on the screen)
614      * to black and an additional white bit on an other place
615      * (+1,+1). This require some boolean arithmetic:
616      *
617      *         Windows          |          X11
618      * And    Xor      Result   |   Bits     Mask     Result
619      *  0      0     black      |    0        1     background
620      *  0      1     white      |    1        1     foreground
621      *  1      0     no change  |    X        0     no change
622      *  1      1     inverted   |    0        1     background
623      *
624      * which gives:
625      *  Bits = not 'And' and 'Xor' or 'And2' and 'Xor2'
626      *  Mask = not 'And' or 'Xor' or 'And2' and 'Xor2'
627      */
628     SelectObject( src, src_and );
629     SelectObject( dst, bits );
630     BitBlt( dst, 0, 0, width, height, src, 0, and_y, SRCCOPY );
631     SelectObject( dst, mask );
632     BitBlt( dst, 0, 0, width, height, src, 0, and_y, SRCCOPY );
633     SelectObject( dst, mask_inv );
634     BitBlt( dst, 0, 0, width, height, src, 0, and_y, SRCCOPY );
635     SelectObject( src, src_xor );
636     BitBlt( dst, 0, 0, width, height, src, 0, xor_y, SRCAND /* src & dst */ );
637     SelectObject( dst, bits );
638     BitBlt( dst, 0, 0, width, height, src, 0, xor_y, SRCERASE /* src & ~dst */ );
639     SelectObject( dst, mask );
640     BitBlt( dst, 0, 0, width, height, src, 0, xor_y, 0xdd0228 /* src | ~dst */ );
641     /* additional white */
642     SelectObject( src, mask_inv );
643     BitBlt( dst, 1, 1, width, height, src, 0, 0, SRCPAINT /* src | dst */);
644     SelectObject( dst, bits );
645     BitBlt( dst, 1, 1, width, height, src, 0, 0, SRCPAINT /* src | dst */ );
646
647     wine_tsx11_lock();
648     cursor = XCreatePixmapCursor( gdi_display, X11DRV_get_pixmap(bits), X11DRV_get_pixmap(mask),
649                                   fg, bg, hotspot_x, hotspot_y );
650     wine_tsx11_unlock();
651
652 done:
653     DeleteDC( src );
654     DeleteDC( dst );
655     DeleteObject( bits );
656     DeleteObject( mask );
657     DeleteObject( mask_inv );
658     return cursor;
659 }
660
661 /***********************************************************************
662  *              create_xlib_cursor
663  *
664  * Create an X cursor from a Windows one.
665  */
666 static Cursor create_xlib_cursor( HDC hdc, const ICONINFOEXW *icon, int width, int height )
667 {
668     XColor fg, bg;
669     Cursor cursor = None;
670     HBITMAP xor_bitmap = 0;
671     BITMAPINFO *info;
672     unsigned int *color_bits = NULL, *ptr;
673     unsigned char *mask_bits = NULL, *xor_bits = NULL;
674     int i, x, y, has_alpha = 0;
675     int rfg, gfg, bfg, rbg, gbg, bbg, fgBits, bgBits;
676     unsigned int width_bytes = (width + 31) / 32 * 4;
677
678     if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] ))))
679         return FALSE;
680     info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
681     info->bmiHeader.biWidth = width;
682     info->bmiHeader.biHeight = -height;
683     info->bmiHeader.biPlanes = 1;
684     info->bmiHeader.biBitCount = 1;
685     info->bmiHeader.biCompression = BI_RGB;
686     info->bmiHeader.biSizeImage = width_bytes * height;
687     info->bmiHeader.biXPelsPerMeter = 0;
688     info->bmiHeader.biYPelsPerMeter = 0;
689     info->bmiHeader.biClrUsed = 0;
690     info->bmiHeader.biClrImportant = 0;
691
692     if (!(mask_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
693     if (!GetDIBits( hdc, icon->hbmMask, 0, height, mask_bits, info, DIB_RGB_COLORS )) goto done;
694
695     info->bmiHeader.biBitCount = 32;
696     info->bmiHeader.biSizeImage = width * height * 4;
697     if (!(color_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
698     if (!(xor_bits = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, width_bytes * height ))) goto done;
699     GetDIBits( hdc, icon->hbmColor, 0, height, color_bits, info, DIB_RGB_COLORS );
700
701     /* compute fg/bg color and xor bitmap based on average of the color values */
702
703     if (!(xor_bitmap = CreateBitmap( width, height, 1, 1, NULL ))) goto done;
704     rfg = gfg = bfg = rbg = gbg = bbg = fgBits = 0;
705     for (y = 0, ptr = color_bits; y < height; y++)
706     {
707         for (x = 0; x < width; x++, ptr++)
708         {
709             int red   = (*ptr >> 16) & 0xff;
710             int green = (*ptr >> 8) & 0xff;
711             int blue  = (*ptr >> 0) & 0xff;
712             if (red + green + blue > 0x40)
713             {
714                 rfg += red;
715                 gfg += green;
716                 bfg += blue;
717                 fgBits++;
718                 xor_bits[y * width_bytes + x / 8] |= 0x80 >> (x % 8);
719             }
720             else
721             {
722                 rbg += red;
723                 gbg += green;
724                 bbg += blue;
725             }
726         }
727     }
728     if (fgBits)
729     {
730         fg.red   = rfg * 257 / fgBits;
731         fg.green = gfg * 257 / fgBits;
732         fg.blue  = bfg * 257 / fgBits;
733     }
734     else fg.red = fg.green = fg.blue = 0;
735     bgBits = width * height - fgBits;
736     if (bgBits)
737     {
738         bg.red   = rbg * 257 / bgBits;
739         bg.green = gbg * 257 / bgBits;
740         bg.blue  = bbg * 257 / bgBits;
741     }
742     else bg.red = bg.green = bg.blue = 0;
743
744     info->bmiHeader.biBitCount = 1;
745     info->bmiHeader.biSizeImage = width_bytes * height;
746     SetDIBits( hdc, xor_bitmap, 0, height, xor_bits, info, DIB_RGB_COLORS );
747
748     /* generate mask from the alpha channel if we have one */
749
750     for (i = 0, ptr = color_bits; i < width * height; i++, ptr++)
751         if ((has_alpha = (*ptr & 0xff000000) != 0)) break;
752
753     if (has_alpha)
754     {
755         memset( mask_bits, 0, width_bytes * height );
756         for (y = 0, ptr = color_bits; y < height; y++)
757             for (x = 0; x < width; x++, ptr++)
758                 if ((*ptr >> 24) > 25) /* more than 10% alpha */
759                     mask_bits[y * width_bytes + x / 8] |= 0x80 >> (x % 8);
760
761         info->bmiHeader.biBitCount = 1;
762         info->bmiHeader.biSizeImage = width_bytes * height;
763         SetDIBits( hdc, icon->hbmMask, 0, height, mask_bits, info, DIB_RGB_COLORS );
764
765         wine_tsx11_lock();
766         cursor = XCreatePixmapCursor( gdi_display,
767                                       X11DRV_get_pixmap(xor_bitmap),
768                                       X11DRV_get_pixmap(icon->hbmMask),
769                                       &fg, &bg, icon->xHotspot, icon->yHotspot );
770         wine_tsx11_unlock();
771     }
772     else
773     {
774         cursor = create_cursor_from_bitmaps( xor_bitmap, icon->hbmMask, width, height, 0, 0,
775                                              &fg, &bg, icon->xHotspot, icon->yHotspot );
776     }
777
778 done:
779     DeleteObject( xor_bitmap );
780     HeapFree( GetProcessHeap(), 0, info );
781     HeapFree( GetProcessHeap(), 0, color_bits );
782     HeapFree( GetProcessHeap(), 0, xor_bits );
783     HeapFree( GetProcessHeap(), 0, mask_bits );
784     return cursor;
785 }
786
787 /***********************************************************************
788  *              create_cursor
789  *
790  * Create an X cursor from a Windows one.
791  */
792 static Cursor create_cursor( HANDLE handle )
793 {
794     Cursor cursor = 0;
795     ICONINFOEXW info;
796     BITMAP bm;
797
798     if (!handle) return get_empty_cursor();
799
800     info.cbSize = sizeof(info);
801     if (!GetIconInfoExW( handle, &info )) return 0;
802
803 #ifdef SONAME_LIBXCURSOR
804     if (use_system_cursors && (cursor = create_xcursor_system_cursor( &info )))
805     {
806         DeleteObject( info.hbmColor );
807         DeleteObject( info.hbmMask );
808         return cursor;
809     }
810 #endif
811
812     GetObjectW( info.hbmMask, sizeof(bm), &bm );
813     if (!info.hbmColor) bm.bmHeight /= 2;
814
815     /* make sure hotspot is valid */
816     if (info.xHotspot >= bm.bmWidth || info.yHotspot >= bm.bmHeight)
817     {
818         info.xHotspot = bm.bmWidth / 2;
819         info.yHotspot = bm.bmHeight / 2;
820     }
821
822     if (info.hbmColor)
823     {
824         HDC hdc = CreateCompatibleDC( 0 );
825         if (hdc)
826         {
827 #ifdef SONAME_LIBXCURSOR
828             if (pXcursorImagesLoadCursor)
829                 cursor = create_xcursor_cursor( hdc, &info, handle, bm.bmWidth, bm.bmHeight );
830 #endif
831             if (!cursor) cursor = create_xlib_cursor( hdc, &info, bm.bmWidth, bm.bmHeight );
832         }
833         DeleteObject( info.hbmColor );
834         DeleteDC( hdc );
835     }
836     else
837     {
838         XColor fg, bg;
839         fg.red = fg.green = fg.blue = 0xffff;
840         bg.red = bg.green = bg.blue = 0;
841         cursor = create_cursor_from_bitmaps( info.hbmMask, info.hbmMask, bm.bmWidth, bm.bmHeight,
842                                              bm.bmHeight, 0, &fg, &bg, info.xHotspot, info.yHotspot );
843     }
844
845     DeleteObject( info.hbmMask );
846     return cursor;
847 }
848
849 /***********************************************************************
850  *              DestroyCursorIcon (X11DRV.@)
851  */
852 void CDECL X11DRV_DestroyCursorIcon( HCURSOR handle )
853 {
854     Cursor cursor;
855
856     wine_tsx11_lock();
857     if (cursor_context && !XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&cursor ))
858     {
859         TRACE( "%p xid %lx\n", handle, cursor );
860         XFreeCursor( gdi_display, cursor );
861         XDeleteContext( gdi_display, (XID)handle, cursor_context );
862     }
863     wine_tsx11_unlock();
864 }
865
866 /***********************************************************************
867  *              SetCursor (X11DRV.@)
868  */
869 void CDECL X11DRV_SetCursor( HCURSOR handle )
870 {
871     if (cursor_window) SendNotifyMessageW( cursor_window, WM_X11DRV_SET_CURSOR, 0, (LPARAM)handle );
872 }
873
874 /***********************************************************************
875  *              SetCursorPos (X11DRV.@)
876  */
877 BOOL CDECL X11DRV_SetCursorPos( INT x, INT y )
878 {
879     Display *display = thread_init_display();
880
881     TRACE( "warping to (%d,%d)\n", x, y );
882
883     wine_tsx11_lock();
884     XWarpPointer( display, root_window, root_window, 0, 0, 0, 0,
885                   x - virtual_screen_rect.left, y - virtual_screen_rect.top );
886     XFlush( display ); /* avoids bad mouse lag in games that do their own mouse warping */
887     wine_tsx11_unlock();
888     return TRUE;
889 }
890
891 /***********************************************************************
892  *              GetCursorPos (X11DRV.@)
893  */
894 BOOL CDECL X11DRV_GetCursorPos(LPPOINT pos)
895 {
896     Display *display = thread_init_display();
897     Window root, child;
898     int rootX, rootY, winX, winY;
899     unsigned int xstate;
900     BOOL ret;
901
902     wine_tsx11_lock();
903     ret = XQueryPointer( display, root_window, &root, &child, &rootX, &rootY, &winX, &winY, &xstate );
904     if (ret)
905     {
906         pos->x = winX + virtual_screen_rect.left;
907         pos->y = winY + virtual_screen_rect.top;
908         TRACE("pointer at (%d,%d)\n", pos->x, pos->y );
909     }
910     wine_tsx11_unlock();
911     return ret;
912 }
913
914
915 /***********************************************************************
916  *           X11DRV_ButtonPress
917  */
918 void X11DRV_ButtonPress( HWND hwnd, XEvent *xev )
919 {
920     XButtonEvent *event = &xev->xbutton;
921     int buttonNum = event->button - 1;
922     WORD wData = 0;
923
924     if (buttonNum >= NB_BUTTONS) return;
925
926     switch (buttonNum)
927     {
928     case 3:
929         wData = WHEEL_DELTA;
930         break;
931     case 4:
932         wData = -WHEEL_DELTA;
933         break;
934     case 5:
935         wData = XBUTTON1;
936         break;
937     case 6:
938         wData = XBUTTON2;
939         break;
940     case 7:
941         wData = XBUTTON1;
942         break;
943     case 8:
944         wData = XBUTTON2;
945         break;
946     }
947
948     update_user_time( event->time );
949     send_mouse_input( hwnd, button_down_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE,
950                       event->window, event->x, event->y, event->state, wData, event->time );
951 }
952
953
954 /***********************************************************************
955  *           X11DRV_ButtonRelease
956  */
957 void X11DRV_ButtonRelease( HWND hwnd, XEvent *xev )
958 {
959     XButtonEvent *event = &xev->xbutton;
960     int buttonNum = event->button - 1;
961     WORD wData = 0;
962
963     if (buttonNum >= NB_BUTTONS || !button_up_flags[buttonNum]) return;
964
965     switch (buttonNum)
966     {
967     case 5:
968         wData = XBUTTON1;
969         break;
970     case 6:
971         wData = XBUTTON2;
972         break;
973     case 7:
974         wData = XBUTTON1;
975         break;
976     case 8:
977         wData = XBUTTON2;
978         break;
979     }
980
981     send_mouse_input( hwnd, button_up_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE,
982                       event->window, event->x, event->y, event->state, wData, event->time );
983 }
984
985
986 /***********************************************************************
987  *           X11DRV_MotionNotify
988  */
989 void X11DRV_MotionNotify( HWND hwnd, XEvent *xev )
990 {
991     XMotionEvent *event = &xev->xmotion;
992
993     TRACE("hwnd %p, event->is_hint %d\n", hwnd, event->is_hint);
994
995     send_mouse_input( hwnd, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE,
996                       event->window, event->x, event->y, event->state, 0, event->time );
997 }
998
999
1000 /***********************************************************************
1001  *           X11DRV_EnterNotify
1002  */
1003 void X11DRV_EnterNotify( HWND hwnd, XEvent *xev )
1004 {
1005     XCrossingEvent *event = &xev->xcrossing;
1006
1007     TRACE("hwnd %p, event->detail %d\n", hwnd, event->detail);
1008
1009     if (event->detail == NotifyVirtual || event->detail == NotifyNonlinearVirtual) return;
1010     if (event->window == x11drv_thread_data()->grab_window) return;
1011
1012     /* simulate a mouse motion event */
1013     send_mouse_input( hwnd, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE,
1014                       event->window, event->x, event->y, event->state, 0, event->time );
1015 }