comctl32: We can now store binary files in the repository.
[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 <stdarg.h>
27
28 #ifdef SONAME_LIBXCURSOR
29 # include <X11/Xcursor/Xcursor.h>
30 static void *xcursor_handle;
31 # define MAKE_FUNCPTR(f) static typeof(f) * p##f
32 MAKE_FUNCPTR(XcursorImageCreate);
33 MAKE_FUNCPTR(XcursorImageDestroy);
34 MAKE_FUNCPTR(XcursorImageLoadCursor);
35 # undef MAKE_FUNCPTR
36 #endif /* SONAME_LIBXCURSOR */
37
38 #define NONAMELESSUNION
39 #define NONAMELESSSTRUCT
40 #include "windef.h"
41 #include "winbase.h"
42 #include "wine/winuser16.h"
43
44 #include "win.h"
45 #include "x11drv.h"
46 #include "wine/server.h"
47 #include "wine/library.h"
48 #include "wine/debug.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
51
52 /**********************************************************************/
53
54 #ifndef Button6Mask
55 #define Button6Mask (1<<13)
56 #endif
57 #ifndef Button7Mask
58 #define Button7Mask (1<<14)
59 #endif
60
61 #define NB_BUTTONS   7     /* Windows can handle 5 buttons and the wheel too */
62
63 static const UINT button_down_flags[NB_BUTTONS] =
64 {
65     MOUSEEVENTF_LEFTDOWN,
66     MOUSEEVENTF_MIDDLEDOWN,
67     MOUSEEVENTF_RIGHTDOWN,
68     MOUSEEVENTF_WHEEL,
69     MOUSEEVENTF_WHEEL,
70     MOUSEEVENTF_XDOWN,
71     MOUSEEVENTF_XDOWN
72 };
73
74 static const UINT button_up_flags[NB_BUTTONS] =
75 {
76     MOUSEEVENTF_LEFTUP,
77     MOUSEEVENTF_MIDDLEUP,
78     MOUSEEVENTF_RIGHTUP,
79     0,
80     0,
81     MOUSEEVENTF_XUP,
82     MOUSEEVENTF_XUP
83 };
84
85 POINT cursor_pos;
86 static DWORD last_time_modified;
87 static RECT cursor_clip; /* Cursor clipping rect */
88
89 BOOL X11DRV_SetCursorPos( INT x, INT y );
90
91
92 /***********************************************************************
93  *              X11DRV_Xcursor_Init
94  *
95  * Load the Xcursor library for use.
96  */
97 void X11DRV_Xcursor_Init(void)
98 {
99 #ifdef SONAME_LIBXCURSOR
100     xcursor_handle = wine_dlopen(SONAME_LIBXCURSOR, RTLD_NOW, NULL, 0);
101     if (!xcursor_handle)  /* wine_dlopen failed. */
102     {
103         WARN("Xcursor failed to load.  Using fallback code.\n");
104         return;
105     }
106 #define LOAD_FUNCPTR(f) \
107         p##f = wine_dlsym(xcursor_handle, #f, NULL, 0)
108
109     LOAD_FUNCPTR(XcursorImageCreate);
110     LOAD_FUNCPTR(XcursorImageDestroy);
111     LOAD_FUNCPTR(XcursorImageLoadCursor);
112 #undef LOAD_FUNCPTR
113 #endif /* SONAME_LIBXCURSOR */
114 }
115
116
117 /***********************************************************************
118  *              get_coords
119  *
120  * get the coordinates of a mouse event
121  */
122 static inline void get_coords( HWND hwnd, int x, int y, POINT *pt )
123 {
124     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
125
126     if (!data) return;
127
128     pt->x = x + data->whole_rect.left;
129     pt->y = y + data->whole_rect.top;
130 }
131
132 /***********************************************************************
133  *              clip_point_to_rect
134  *
135  * Clip point to the provided rectangle
136  */
137 static inline void clip_point_to_rect( LPCRECT rect, LPPOINT pt )
138 {
139     if      (pt->x <  rect->left)   pt->x = rect->left;
140     else if (pt->x >= rect->right)  pt->x = rect->right - 1;
141     if      (pt->y <  rect->top)    pt->y = rect->top;
142     else if (pt->y >= rect->bottom) pt->y = rect->bottom - 1;
143 }
144
145 /***********************************************************************
146  *              update_button_state
147  *
148  * Update the button state with what X provides us
149  */
150 static inline void update_button_state( unsigned int state )
151 {
152     key_state_table[VK_LBUTTON] = (state & Button1Mask ? 0x80 : 0);
153     key_state_table[VK_MBUTTON] = (state & Button2Mask ? 0x80 : 0);
154     key_state_table[VK_RBUTTON] = (state & Button3Mask ? 0x80 : 0);
155     /* X-buttons are not reported from XQueryPointer */
156 }
157
158
159 /***********************************************************************
160  *              update_mouse_state
161  *
162  * Update the various window states on a mouse event.
163  */
164 static void update_mouse_state( HWND hwnd, Window window, int x, int y, unsigned int state, POINT *pt )
165 {
166     struct x11drv_thread_data *data = x11drv_thread_data();
167
168     if (window == root_window)
169     {
170         x += virtual_screen_rect.left;
171         y += virtual_screen_rect.top;
172     }
173     get_coords( hwnd, x, y, pt );
174
175     /* update the cursor */
176
177     if (data->cursor_window != window)
178     {
179         data->cursor_window = window;
180         wine_tsx11_lock();
181         if (data->cursor) XDefineCursor( data->display, window, data->cursor );
182         wine_tsx11_unlock();
183     }
184
185     /* update the wine server Z-order */
186
187     if (window != data->grab_window &&
188         /* ignore event if a button is pressed, since the mouse is then grabbed too */
189         !(state & (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask|Button6Mask|Button7Mask)))
190     {
191         SERVER_START_REQ( update_window_zorder )
192         {
193             req->window      = hwnd;
194             req->rect.left   = pt->x;
195             req->rect.top    = pt->y;
196             req->rect.right  = pt->x + 1;
197             req->rect.bottom = pt->y + 1;
198             wine_server_call( req );
199         }
200         SERVER_END_REQ;
201     }
202 }
203
204
205 /***********************************************************************
206  *           get_key_state
207  */
208 static WORD get_key_state(void)
209 {
210     WORD ret = 0;
211
212     if (GetSystemMetrics( SM_SWAPBUTTON ))
213     {
214         if (key_state_table[VK_RBUTTON] & 0x80) ret |= MK_LBUTTON;
215         if (key_state_table[VK_LBUTTON] & 0x80) ret |= MK_RBUTTON;
216     }
217     else
218     {
219         if (key_state_table[VK_LBUTTON] & 0x80) ret |= MK_LBUTTON;
220         if (key_state_table[VK_RBUTTON] & 0x80) ret |= MK_RBUTTON;
221     }
222     if (key_state_table[VK_MBUTTON] & 0x80)  ret |= MK_MBUTTON;
223     if (key_state_table[VK_SHIFT] & 0x80)    ret |= MK_SHIFT;
224     if (key_state_table[VK_CONTROL] & 0x80)  ret |= MK_CONTROL;
225     if (key_state_table[VK_XBUTTON1] & 0x80) ret |= MK_XBUTTON1;
226     if (key_state_table[VK_XBUTTON2] & 0x80) ret |= MK_XBUTTON2;
227     return ret;
228 }
229
230
231 /***********************************************************************
232  *           queue_raw_mouse_message
233  */
234 static void queue_raw_mouse_message( UINT message, HWND hwnd, DWORD x, DWORD y,
235                                      DWORD data, DWORD time, DWORD extra_info, UINT injected_flags )
236 {
237     MSLLHOOKSTRUCT hook;
238
239     hook.pt.x        = x;
240     hook.pt.y        = y;
241     hook.mouseData   = MAKELONG( 0, data );
242     hook.flags       = injected_flags;
243     hook.time        = time;
244     hook.dwExtraInfo = extra_info;
245
246     last_time_modified = GetTickCount();
247     if (HOOK_CallHooks( WH_MOUSE_LL, HC_ACTION, message, (LPARAM)&hook, TRUE )) return;
248
249     SERVER_START_REQ( send_hardware_message )
250     {
251         req->id       = (injected_flags & LLMHF_INJECTED) ? 0 : GetCurrentThreadId();
252         req->win      = hwnd;
253         req->msg      = message;
254         req->wparam   = MAKEWPARAM( get_key_state(), data );
255         req->lparam   = 0;
256         req->x        = x;
257         req->y        = y;
258         req->time     = time;
259         req->info     = extra_info;
260         wine_server_call( req );
261     }
262     SERVER_END_REQ;
263
264 }
265
266
267 /***********************************************************************
268  *              X11DRV_send_mouse_input
269  */
270 void X11DRV_send_mouse_input( HWND hwnd, DWORD flags, DWORD x, DWORD y,
271                               DWORD data, DWORD time, DWORD extra_info, UINT injected_flags )
272 {
273     POINT pt;
274
275     if (flags & MOUSEEVENTF_MOVE && flags & MOUSEEVENTF_ABSOLUTE)
276     {
277         if (injected_flags & LLMHF_INJECTED)
278         {
279             pt.x = (x * screen_width) >> 16;
280             pt.y = (y * screen_height) >> 16;
281         }
282         else
283         {
284             pt.x = x;
285             pt.y = y;
286         }
287     }
288     else if (flags & MOUSEEVENTF_MOVE)
289     {
290         int accel[3], xMult = 1, yMult = 1;
291
292         /* dx and dy can be negative numbers for relative movements */
293         SystemParametersInfoW(SPI_GETMOUSE, 0, accel, 0);
294
295         if (abs(x) > accel[0] && accel[2] != 0)
296         {
297             xMult = 2;
298             if ((abs(x) > accel[1]) && (accel[2] == 2)) xMult = 4;
299         }
300         if (abs(y) > accel[0] && accel[2] != 0)
301         {
302             yMult = 2;
303             if ((abs(y) > accel[1]) && (accel[2] == 2)) yMult = 4;
304         }
305
306         wine_tsx11_lock();
307         pt.x = cursor_pos.x + (long)x * xMult;
308         pt.y = cursor_pos.y + (long)y * yMult;
309         wine_tsx11_unlock();
310     }
311     else
312     {
313         wine_tsx11_lock();
314         pt = cursor_pos;
315         wine_tsx11_unlock();
316     }
317
318     if (flags & MOUSEEVENTF_MOVE)
319     {
320         queue_raw_mouse_message( WM_MOUSEMOVE, hwnd, pt.x, pt.y, data, time,
321                                  extra_info, injected_flags );
322         if ((injected_flags & LLMHF_INJECTED) &&
323             ((flags & MOUSEEVENTF_ABSOLUTE) || x || y))  /* we have to actually move the cursor */
324         {
325             X11DRV_SetCursorPos( pt.x, pt.y );
326         }
327         else
328         {
329             wine_tsx11_lock();
330             clip_point_to_rect( &cursor_clip, &pt);
331             cursor_pos = pt;
332             wine_tsx11_unlock();
333         }
334     }
335     if (flags & MOUSEEVENTF_LEFTDOWN)
336     {
337         key_state_table[VK_LBUTTON] |= 0xc0;
338         queue_raw_mouse_message( GetSystemMetrics(SM_SWAPBUTTON) ? WM_RBUTTONDOWN : WM_LBUTTONDOWN,
339                                  hwnd, pt.x, pt.y, data, time, extra_info, injected_flags );
340     }
341     if (flags & MOUSEEVENTF_LEFTUP)
342     {
343         key_state_table[VK_LBUTTON] &= ~0x80;
344         queue_raw_mouse_message( GetSystemMetrics(SM_SWAPBUTTON) ? WM_RBUTTONUP : WM_LBUTTONUP,
345                                  hwnd, pt.x, pt.y, data, time, extra_info, injected_flags );
346     }
347     if (flags & MOUSEEVENTF_RIGHTDOWN)
348     {
349         key_state_table[VK_RBUTTON] |= 0xc0;
350         queue_raw_mouse_message( GetSystemMetrics(SM_SWAPBUTTON) ? WM_LBUTTONDOWN : WM_RBUTTONDOWN,
351                                  hwnd, pt.x, pt.y, data, time, extra_info, injected_flags );
352     }
353     if (flags & MOUSEEVENTF_RIGHTUP)
354     {
355         key_state_table[VK_RBUTTON] &= ~0x80;
356         queue_raw_mouse_message( GetSystemMetrics(SM_SWAPBUTTON) ? WM_LBUTTONUP : WM_RBUTTONUP,
357                                  hwnd, pt.x, pt.y, data, time, extra_info, injected_flags );
358     }
359     if (flags & MOUSEEVENTF_MIDDLEDOWN)
360     {
361         key_state_table[VK_MBUTTON] |= 0xc0;
362         queue_raw_mouse_message( WM_MBUTTONDOWN, hwnd, pt.x, pt.y, data, time,
363                                  extra_info, injected_flags );
364     }
365     if (flags & MOUSEEVENTF_MIDDLEUP)
366     {
367         key_state_table[VK_MBUTTON] &= ~0x80;
368         queue_raw_mouse_message( WM_MBUTTONUP, hwnd, pt.x, pt.y, data, time,
369                                  extra_info, injected_flags );
370     }
371     if (flags & MOUSEEVENTF_WHEEL)
372     {
373         queue_raw_mouse_message( WM_MOUSEWHEEL, hwnd, pt.x, pt.y, data, time,
374                                  extra_info, injected_flags );
375     }
376     if (flags & MOUSEEVENTF_XDOWN)
377     {
378         key_state_table[VK_XBUTTON1 + data - 1] |= 0xc0;
379         queue_raw_mouse_message( WM_XBUTTONDOWN, hwnd, pt.x, pt.y, data, time,
380                                  extra_info, injected_flags );
381     }
382     if (flags & MOUSEEVENTF_XUP)
383     {
384         key_state_table[VK_XBUTTON1 + data - 1] &= ~0x80;
385         queue_raw_mouse_message( WM_XBUTTONUP, hwnd, pt.x, pt.y, data, time,
386                                  extra_info, injected_flags );
387     }
388 }
389
390
391 #ifdef SONAME_LIBXCURSOR
392
393 /***********************************************************************
394  *              create_cursor_image
395  *
396  * Create an XcursorImage from a CURSORICONINFO
397  */
398 static XcursorImage *create_cursor_image( CURSORICONINFO *ptr )
399 {
400     int x, xmax;
401     int y, ymax;
402     int and_size, xor_size;
403     unsigned char *and_bits, *and_ptr, *xor_bits, *xor_ptr;
404     int and_width_bytes, xor_width_bytes;
405     XcursorPixel *pixel_ptr;
406     XcursorImage *image;
407
408     ymax = (ptr->nHeight > 32) ? 32 : ptr->nHeight;
409     xmax = (ptr->nWidth > 32) ? 32 : ptr->nWidth;
410
411     and_width_bytes = xmax / 8;
412     xor_width_bytes = and_width_bytes * ptr->bBitsPerPixel;
413
414     and_size = ptr->nWidth * ptr->nHeight / 8;
415     and_ptr = and_bits = (unsigned char *)(ptr + 1);
416
417     xor_size = xor_width_bytes * ptr->nHeight;
418     xor_ptr = xor_bits = and_ptr + and_size;
419
420     image = pXcursorImageCreate( xmax, ymax );
421     pixel_ptr = image->pixels;
422
423     /* On windows, to calculate the color for a pixel, first an AND is done
424      * with the background and the "and" bitmap, then an XOR with the "xor"
425      * bitmap. This means that when the data in the "and" bitmap is 0, the
426      * pixel will get the color as specified in the "xor" bitmap.
427      * However, if the data in the "and" bitmap is 1, the result will be the
428      * background XOR'ed with the value in the "xor" bitmap. In case the "xor"
429      * data is completely black (0x000000) the pixel will become transparent,
430      * in case it's white (0xffffff) the pixel will become the inverse of the
431      * background color.
432      *
433      * Since we can't support inverting colors, we map the grayscale value of
434      * the "xor" data to the alpha channel, and xor the the color with either
435      * black or white.
436      */
437     for (y = 0; y < ymax; ++y)
438     {
439         and_ptr = and_bits + (y * and_width_bytes);
440         xor_ptr = xor_bits + (y * xor_width_bytes);
441
442         for (x = 0; x < xmax; ++x)
443         {
444             /* Xcursor pixel data is in ARGB format, with A in the high byte */
445             switch (ptr->bBitsPerPixel)
446             {
447                 case 32:
448                     /* BGRA, 8 bits each */
449                     *pixel_ptr = *xor_ptr++;
450                     *pixel_ptr |= *xor_ptr++ << 8;
451                     *pixel_ptr |= *xor_ptr++ << 16;
452                     *pixel_ptr |= *xor_ptr++ << 24;
453                     break;
454
455                 case 24:
456                     /* BGR, 8 bits each */
457                     *pixel_ptr = *xor_ptr++;
458                     *pixel_ptr |= *xor_ptr++ << 8;
459                     *pixel_ptr |= *xor_ptr++ << 16;
460                     break;
461
462                 case 16:
463                     /* BGR, 5 red, 6 green, 5 blue */
464                     *pixel_ptr = *xor_ptr * 0x1f;
465                     *pixel_ptr |= (*xor_ptr & 0xe0) << 3;
466                     ++xor_ptr;
467                     *pixel_ptr |= (*xor_ptr & 0x07) << 11;
468                     *pixel_ptr |= (*xor_ptr & 0xf8) << 13;
469                     break;
470
471                 case 1:
472                     if (*xor_ptr & (1 << (7 - (x & 7)))) *pixel_ptr = 0xffffff;
473                     else *pixel_ptr = 0;
474                     if ((x & 7) == 7) ++xor_ptr;
475                     break;
476
477                 default:
478                     FIXME("Currently no support for cursors with %d bits per pixel\n", ptr->bBitsPerPixel);
479                     return 0;
480             }
481
482             if (ptr->bBitsPerPixel != 32)
483             {
484                 /* Alpha channel */
485                 if (~*and_ptr & (1 << (7 - (x & 7)))) *pixel_ptr |= 0xff << 24;
486                 else if (*pixel_ptr)
487                 {
488                     int alpha = (*pixel_ptr & 0xff) * 0.30f
489                             + ((*pixel_ptr & 0xff00) >> 8) * 0.55f
490                             + ((*pixel_ptr & 0xff0000) >> 16) * 0.15f;
491                     *pixel_ptr ^= ((x + y) % 2) ? 0xffffff : 0x000000;
492                     *pixel_ptr |= alpha << 24;
493                 }
494                 if ((x & 7) == 7) ++and_ptr;
495             }
496             ++pixel_ptr;
497         }
498     }
499
500     return image;
501 }
502
503
504 /***********************************************************************
505  *              create_xcursor_cursor
506  *
507  * Use Xcursor to create an X cursor from a Windows one.
508  */
509 static Cursor create_xcursor_cursor( Display *display, CURSORICONINFO *ptr )
510 {
511     Cursor cursor;
512     XcursorImage *image;
513
514     if (!ptr) /* Create an empty cursor */
515     {
516         image = pXcursorImageCreate( 1, 1 );
517         image->xhot = 0;
518         image->yhot = 0;
519         *(image->pixels) = 0;
520         cursor = pXcursorImageLoadCursor( display, image );
521         pXcursorImageDestroy( image );
522
523         return cursor;
524     }
525
526     image = create_cursor_image( ptr );
527     if (!image) return 0;
528
529     /* Make sure hotspot is valid */
530     image->xhot = ptr->ptHotSpot.x;
531     image->yhot = ptr->ptHotSpot.y;
532     if (image->xhot < 0 || image->xhot >= image->width ||
533         image->yhot < 0 || image->yhot >= image->height)
534     {
535         image->xhot = image->width / 2;
536         image->yhot = image->height / 2;
537     }
538
539     image->delay = 0;
540
541     cursor = pXcursorImageLoadCursor( display, image );
542     pXcursorImageDestroy( image );
543
544     return cursor;
545 }
546
547 #endif /* SONAME_LIBXCURSOR */
548
549
550 /***********************************************************************
551  *              create_cursor
552  *
553  * Create an X cursor from a Windows one.
554  */
555 static Cursor create_cursor( Display *display, CURSORICONINFO *ptr )
556 {
557     Pixmap pixmapBits, pixmapMask, pixmapMaskInv = 0, pixmapAll;
558     XColor fg, bg;
559     Cursor cursor = None;
560     POINT hotspot;
561     char *bitMask32 = NULL;
562
563 #ifdef SONAME_LIBXCURSOR
564     if (pXcursorImageLoadCursor) return create_xcursor_cursor( display, ptr );
565 #endif
566
567     if (!ptr)  /* Create an empty cursor */
568     {
569         static const char data[] = { 0 };
570
571         bg.red = bg.green = bg.blue = 0x0000;
572         pixmapBits = XCreateBitmapFromData( display, root_window, data, 1, 1 );
573         if (pixmapBits)
574         {
575             cursor = XCreatePixmapCursor( display, pixmapBits, pixmapBits,
576                                           &bg, &bg, 0, 0 );
577             XFreePixmap( display, pixmapBits );
578         }
579     }
580     else  /* Create the X cursor from the bits */
581     {
582         XImage *image;
583         GC gc;
584
585         TRACE("Bitmap %dx%d planes=%d bpp=%d bytesperline=%d\n",
586             ptr->nWidth, ptr->nHeight, ptr->bPlanes, ptr->bBitsPerPixel,
587             ptr->nWidthBytes);
588
589         /* Create a pixmap and transfer all the bits to it */
590
591         /* NOTE: Following hack works, but only because XFree depth
592          *       1 images really use 1 bit/pixel (and so the same layout
593          *       as the Windows cursor data). Perhaps use a more generic
594          *       algorithm here.
595          */
596         /* This pixmap will be written with two bitmaps. The first is
597          *  the mask and the second is the image.
598          */
599         if (!(pixmapAll = XCreatePixmap( display, root_window,
600                   ptr->nWidth, ptr->nHeight * 2, 1 )))
601             return 0;
602         if (!(image = XCreateImage( display, visual,
603                 1, ZPixmap, 0, (char *)(ptr + 1), ptr->nWidth,
604                 ptr->nHeight * 2, 16, ptr->nWidthBytes/ptr->bBitsPerPixel)))
605         {
606             XFreePixmap( display, pixmapAll );
607             return 0;
608         }
609         gc = XCreateGC( display, pixmapAll, 0, NULL );
610         XSetGraphicsExposures( display, gc, False );
611         image->byte_order = MSBFirst;
612         image->bitmap_bit_order = MSBFirst;
613         image->bitmap_unit = 16;
614         _XInitImageFuncPtrs(image);
615         if (ptr->bPlanes * ptr->bBitsPerPixel == 1)
616         {
617             /* A plain old white on black cursor. */
618             fg.red = fg.green = fg.blue = 0xffff;
619             bg.red = bg.green = bg.blue = 0x0000;
620             XPutImage( display, pixmapAll, gc, image,
621                 0, 0, 0, 0, ptr->nWidth, ptr->nHeight * 2 );
622         }
623         else
624         {
625             int     rbits, gbits, bbits, red, green, blue;
626             int     rfg, gfg, bfg, rbg, gbg, bbg;
627             int     rscale, gscale, bscale;
628             int     x, y, xmax, ymax, bitIndex, byteIndex, xorIndex;
629             unsigned char *theMask, *theImage, theChar;
630             int     threshold, fgBits, bgBits, bitShifted;
631             BYTE    pXorBits[128];   /* Up to 32x32 icons */
632
633             switch (ptr->bBitsPerPixel)
634             {
635             case 32:
636                 bitMask32 = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
637                                        ptr->nWidth * ptr->nHeight / 8 );
638                 /* Fallthrough */
639             case 24:
640                 rbits = 8;
641                 gbits = 8;
642                 bbits = 8;
643                 threshold = 0x40;
644                 break;
645             case 16:
646                 rbits = 5;
647                 gbits = 6;
648                 bbits = 5;
649                 threshold = 0x40;
650                 break;
651             default:
652                 FIXME("Currently no support for cursors with %d bits per pixel\n",
653                   ptr->bBitsPerPixel);
654                 XFreePixmap( display, pixmapAll );
655                 XFreeGC( display, gc );
656                 image->data = NULL;
657                 XDestroyImage( image );
658                 return 0;
659             }
660             /* The location of the mask. */
661             theMask = (unsigned char *)(ptr + 1);
662             /* The mask should still be 1 bit per pixel. The color image
663              * should immediately follow the mask.
664              */
665             theImage = &theMask[ptr->nWidth/8 * ptr->nHeight];
666             rfg = gfg = bfg = rbg = gbg = bbg = 0;
667             bitIndex = 0;
668             byteIndex = 0;
669             xorIndex = 0;
670             fgBits = 0;
671             bitShifted = 0x01;
672             xmax = (ptr->nWidth > 32) ? 32 : ptr->nWidth;
673             if (ptr->nWidth > 32) {
674                 ERR("Got a %dx%d cursor. Cannot handle larger than 32x32.\n",
675                   ptr->nWidth, ptr->nHeight);
676             }
677             ymax = (ptr->nHeight > 32) ? 32 : ptr->nHeight;
678
679             memset(pXorBits, 0, 128);
680             for (y=0; y<ymax; y++)
681             {
682                 for (x=0; x<xmax; x++)
683                 {
684                         red = green = blue = 0;
685                         switch (ptr->bBitsPerPixel)
686                         {
687                         case 32:
688                             theChar = theImage[byteIndex++];
689                             blue = theChar;
690                             theChar = theImage[byteIndex++];
691                             green = theChar;
692                             theChar = theImage[byteIndex++];
693                             red = theChar;
694                             theChar = theImage[byteIndex++];
695                             /* If the alpha channel is >5% transparent,
696                              * assume that we can add it to the bitMask32.
697                              */
698                             if (theChar > 0x0D)
699                                 *(bitMask32 + (y*xmax+x)/8) |= 1 << (x & 7);
700                             break;
701                         case 24:
702                             theChar = theImage[byteIndex++];
703                             blue = theChar;
704                             theChar = theImage[byteIndex++];
705                             green = theChar;
706                             theChar = theImage[byteIndex++];
707                             red = theChar;
708                             break;
709                         case 16:
710                             theChar = theImage[byteIndex++];
711                             blue = theChar & 0x1F;
712                             green = (theChar & 0xE0) >> 5;
713                             theChar = theImage[byteIndex++];
714                             green |= (theChar & 0x07) << 3;
715                             red = (theChar & 0xF8) >> 3;
716                             break;
717                         }
718
719                     if (red+green+blue > threshold)
720                     {
721                         rfg += red;
722                         gfg += green;
723                         bfg += blue;
724                         fgBits++;
725                         pXorBits[xorIndex] |= bitShifted;
726                     }
727                     else
728                     {
729                         rbg += red;
730                         gbg += green;
731                         bbg += blue;
732                     }
733                     if (x%8 == 7)
734                     {
735                         bitShifted = 0x01;
736                         xorIndex++;
737                     }
738                     else
739                         bitShifted = bitShifted << 1;
740                 }
741             }
742             rscale = 1 << (16 - rbits);
743             gscale = 1 << (16 - gbits);
744             bscale = 1 << (16 - bbits);
745             if (fgBits)
746             {
747                 fg.red   = rfg * rscale / fgBits;
748                 fg.green = gfg * gscale / fgBits;
749                 fg.blue  = bfg * bscale / fgBits;
750             }
751             else fg.red = fg.green = fg.blue = 0;
752             bgBits = xmax * ymax - fgBits;
753             if (bgBits)
754             {
755                 bg.red   = rbg * rscale / bgBits;
756                 bg.green = gbg * gscale / bgBits;
757                 bg.blue  = bbg * bscale / bgBits;
758             }
759             else bg.red = bg.green = bg.blue = 0;
760             pixmapBits = XCreateBitmapFromData( display, root_window, (char *)pXorBits, xmax, ymax );
761             if (!pixmapBits)
762             {
763                 HeapFree( GetProcessHeap(), 0, bitMask32 );
764                 XFreePixmap( display, pixmapAll );
765                 XFreeGC( display, gc );
766                 image->data = NULL;
767                 XDestroyImage( image );
768                 return 0;
769             }
770
771             /* Put the mask. */
772             XPutImage( display, pixmapAll, gc, image,
773                    0, 0, 0, 0, ptr->nWidth, ptr->nHeight );
774             XSetFunction( display, gc, GXcopy );
775             /* Put the image */
776             XCopyArea( display, pixmapBits, pixmapAll, gc,
777                        0, 0, xmax, ymax, 0, ptr->nHeight );
778             XFreePixmap( display, pixmapBits );
779         }
780         image->data = NULL;
781         XDestroyImage( image );
782
783         /* Now create the 2 pixmaps for bits and mask */
784
785         pixmapBits = XCreatePixmap( display, root_window, ptr->nWidth, ptr->nHeight, 1 );
786         if (ptr->bBitsPerPixel != 32)
787         {
788             pixmapMaskInv = XCreatePixmap( display, root_window, ptr->nWidth, ptr->nHeight, 1 );
789             pixmapMask = XCreatePixmap( display, root_window, ptr->nWidth, ptr->nHeight, 1 );
790
791             /* Make sure everything went OK so far */
792             if (pixmapBits && pixmapMask && pixmapMaskInv)
793             {
794                 /* We have to do some magic here, as cursors are not fully
795                  * compatible between Windows and X11. Under X11, there are
796                  * only 3 possible color cursor: black, white and masked. So
797                  * we map the 4th Windows color (invert the bits on the screen)
798                  * to black and an additional white bit on an other place
799                  * (+1,+1). This require some boolean arithmetic:
800                  *
801                  *         Windows          |          X11
802                  * And    Xor      Result   |   Bits     Mask     Result
803                  *  0      0     black      |    0        1     background
804                  *  0      1     white      |    1        1     foreground
805                  *  1      0     no change  |    X        0     no change
806                  *  1      1     inverted   |    0        1     background
807                  *
808                  * which gives:
809                  *  Bits = not 'And' and 'Xor' or 'And2' and 'Xor2'
810                  *  Mask = not 'And' or 'Xor' or 'And2' and 'Xor2'
811                  *
812                  * FIXME: apparently some servers do support 'inverted' color.
813                  * I don't know if it's correct per the X spec, but maybe we
814                  * ought to take advantage of it.  -- AJ
815                  */
816                 XSetFunction( display, gc, GXcopy );
817                 XCopyArea( display, pixmapAll, pixmapBits, gc,
818                            0, 0, ptr->nWidth, ptr->nHeight, 0, 0 );
819                 XCopyArea( display, pixmapAll, pixmapMask, gc,
820                            0, 0, ptr->nWidth, ptr->nHeight, 0, 0 );
821                 XCopyArea( display, pixmapAll, pixmapMaskInv, gc,
822                            0, 0, ptr->nWidth, ptr->nHeight, 0, 0 );
823                 XSetFunction( display, gc, GXand );
824                 XCopyArea( display, pixmapAll, pixmapMaskInv, gc,
825                            0, ptr->nHeight, ptr->nWidth, ptr->nHeight, 0, 0 );
826                 XSetFunction( display, gc, GXandReverse );
827                 XCopyArea( display, pixmapAll, pixmapBits, gc,
828                            0, ptr->nHeight, ptr->nWidth, ptr->nHeight, 0, 0 );
829                 XSetFunction( display, gc, GXorReverse );
830                 XCopyArea( display, pixmapAll, pixmapMask, gc,
831                            0, ptr->nHeight, ptr->nWidth, ptr->nHeight, 0, 0 );
832                 /* Additional white */
833                 XSetFunction( display, gc, GXor );
834                 XCopyArea( display, pixmapMaskInv, pixmapMask, gc,
835                            0, 0, ptr->nWidth, ptr->nHeight, 1, 1 );
836                 XCopyArea( display, pixmapMaskInv, pixmapBits, gc,
837                            0, 0, ptr->nWidth, ptr->nHeight, 1, 1 );
838                 XSetFunction( display, gc, GXcopy );
839             }
840         }
841         else
842         {
843             pixmapMask = XCreateBitmapFromData( display, root_window,
844                                                 bitMask32, ptr->nWidth,
845                                                 ptr->nHeight );
846             HeapFree( GetProcessHeap(), 0, bitMask32 );
847         }
848
849         /* Make sure hotspot is valid */
850         hotspot.x = ptr->ptHotSpot.x;
851         hotspot.y = ptr->ptHotSpot.y;
852         if (hotspot.x < 0 || hotspot.x >= ptr->nWidth ||
853             hotspot.y < 0 || hotspot.y >= ptr->nHeight)
854         {
855             hotspot.x = ptr->nWidth / 2;
856             hotspot.y = ptr->nHeight / 2;
857         }
858
859         if (pixmapBits && pixmapMask)
860             cursor = XCreatePixmapCursor( display, pixmapBits, pixmapMask,
861                                           &fg, &bg, hotspot.x, hotspot.y );
862
863         /* Now free everything */
864
865         if (pixmapAll) XFreePixmap( display, pixmapAll );
866         if (pixmapBits) XFreePixmap( display, pixmapBits );
867         if (pixmapMask) XFreePixmap( display, pixmapMask );
868         if (pixmapMaskInv) XFreePixmap( display, pixmapMaskInv );
869         XFreeGC( display, gc );
870     }
871     return cursor;
872 }
873
874
875 /***********************************************************************
876  *              SetCursor (X11DRV.@)
877  */
878 void X11DRV_SetCursor( CURSORICONINFO *lpCursor )
879 {
880     struct x11drv_thread_data *data = x11drv_thread_data();
881     Cursor cursor;
882
883     if (lpCursor)
884         TRACE("%ux%u, planes %u, bpp %u\n",
885               lpCursor->nWidth, lpCursor->nHeight, lpCursor->bPlanes, lpCursor->bBitsPerPixel);
886     else
887         TRACE("NULL\n");
888
889     /* set the same cursor for all top-level windows of the current thread */
890
891     wine_tsx11_lock();
892     cursor = create_cursor( data->display, lpCursor );
893     if (cursor)
894     {
895         if (data->cursor) XFreeCursor( data->display, data->cursor );
896         data->cursor = cursor;
897         if (data->cursor_window)
898         {
899             XDefineCursor( data->display, data->cursor_window, cursor );
900             /* Make the change take effect immediately */
901             XFlush( data->display );
902         }
903     }
904     wine_tsx11_unlock();
905 }
906
907 /***********************************************************************
908  *              SetCursorPos (X11DRV.@)
909  */
910 BOOL X11DRV_SetCursorPos( INT x, INT y )
911 {
912     Display *display = thread_display();
913     POINT pt;
914
915     TRACE( "warping to (%d,%d)\n", x, y );
916
917     wine_tsx11_lock();
918     if (cursor_pos.x == x && cursor_pos.y == y)
919     {
920         wine_tsx11_unlock();
921         /* We still need to generate WM_MOUSEMOVE */
922         queue_raw_mouse_message( WM_MOUSEMOVE, NULL, x, y, 0, GetCurrentTime(), 0, 0 );
923         return TRUE;
924     }
925
926     pt.x = x; pt.y = y;
927     clip_point_to_rect( &cursor_clip, &pt);
928     XWarpPointer( display, root_window, root_window, 0, 0, 0, 0,
929                   pt.x - virtual_screen_rect.left, pt.y - virtual_screen_rect.top );
930     XFlush( display ); /* avoids bad mouse lag in games that do their own mouse warping */
931     cursor_pos = pt;
932     wine_tsx11_unlock();
933     return TRUE;
934 }
935
936 /***********************************************************************
937  *              GetCursorPos (X11DRV.@)
938  */
939 BOOL X11DRV_GetCursorPos(LPPOINT pos)
940 {
941     Display *display = thread_display();
942     Window root, child;
943     int rootX, rootY, winX, winY;
944     unsigned int xstate;
945
946     wine_tsx11_lock();
947     if ((GetTickCount() - last_time_modified > 100) &&
948         XQueryPointer( display, root_window, &root, &child,
949                        &rootX, &rootY, &winX, &winY, &xstate ))
950     {
951         update_button_state( xstate );
952         winX += virtual_screen_rect.left;
953         winY += virtual_screen_rect.top;
954         TRACE("pointer at (%d,%d)\n", winX, winY );
955         cursor_pos.x = winX;
956         cursor_pos.y = winY;
957     }
958     *pos = cursor_pos;
959     wine_tsx11_unlock();
960     return TRUE;
961 }
962
963
964 /***********************************************************************
965  *              ClipCursor (X11DRV.@)
966  *
967  * Set the cursor clipping rectangle.
968  */
969 BOOL X11DRV_ClipCursor( LPCRECT clip )
970 {
971     if (!IntersectRect( &cursor_clip, &virtual_screen_rect, clip ))
972         cursor_clip = virtual_screen_rect;
973
974     return TRUE;
975 }
976
977 /***********************************************************************
978  *           X11DRV_ButtonPress
979  */
980 void X11DRV_ButtonPress( HWND hwnd, XEvent *xev )
981 {
982     XButtonEvent *event = &xev->xbutton;
983     int buttonNum = event->button - 1;
984     WORD wData = 0;
985     POINT pt;
986
987     if (buttonNum >= NB_BUTTONS) return;
988     if (!hwnd) return;
989
990     switch (buttonNum)
991     {
992     case 3:
993         wData = WHEEL_DELTA;
994         break;
995     case 4:
996         wData = -WHEEL_DELTA;
997         break;
998     case 5:
999         wData = XBUTTON1;
1000         break;
1001     case 6:
1002         wData = XBUTTON2;
1003         break;
1004     }
1005
1006     update_mouse_state( hwnd, event->window, event->x, event->y, event->state, &pt );
1007
1008     X11DRV_send_mouse_input( hwnd, button_down_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE,
1009                              pt.x, pt.y, wData, EVENT_x11_time_to_win32_time(event->time), 0, 0 );
1010 }
1011
1012
1013 /***********************************************************************
1014  *           X11DRV_ButtonRelease
1015  */
1016 void X11DRV_ButtonRelease( HWND hwnd, XEvent *xev )
1017 {
1018     XButtonEvent *event = &xev->xbutton;
1019     int buttonNum = event->button - 1;
1020     WORD wData = 0;
1021     POINT pt;
1022
1023     if (buttonNum >= NB_BUTTONS || !button_up_flags[buttonNum]) return;
1024     if (!hwnd) return;
1025
1026     switch (buttonNum)
1027     {
1028     case 5:
1029         wData = XBUTTON1;
1030         break;
1031     case 6:
1032         wData = XBUTTON2;
1033         break;
1034     }
1035
1036     update_mouse_state( hwnd, event->window, event->x, event->y, event->state, &pt );
1037
1038     X11DRV_send_mouse_input( hwnd, button_up_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE,
1039                              pt.x, pt.y, wData, EVENT_x11_time_to_win32_time(event->time), 0, 0 );
1040 }
1041
1042
1043 /***********************************************************************
1044  *           X11DRV_MotionNotify
1045  */
1046 void X11DRV_MotionNotify( HWND hwnd, XEvent *xev )
1047 {
1048     XMotionEvent *event = &xev->xmotion;
1049     POINT pt;
1050
1051     TRACE("hwnd %p, event->is_hint %d\n", hwnd, event->is_hint);
1052
1053     if (!hwnd) return;
1054
1055     update_mouse_state( hwnd, event->window, event->x, event->y, event->state, &pt );
1056
1057     X11DRV_send_mouse_input( hwnd, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE,
1058                              pt.x, pt.y, 0, EVENT_x11_time_to_win32_time(event->time), 0, 0 );
1059 }
1060
1061
1062 /***********************************************************************
1063  *           X11DRV_EnterNotify
1064  */
1065 void X11DRV_EnterNotify( HWND hwnd, XEvent *xev )
1066 {
1067     XCrossingEvent *event = &xev->xcrossing;
1068     POINT pt;
1069
1070     TRACE("hwnd %p, event->detail %d\n", hwnd, event->detail);
1071
1072     if (!hwnd) return;
1073     if (event->detail == NotifyVirtual || event->detail == NotifyNonlinearVirtual) return;
1074
1075     /* simulate a mouse motion event */
1076     update_mouse_state( hwnd, event->window, event->x, event->y, event->state, &pt );
1077
1078     X11DRV_send_mouse_input( hwnd, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE,
1079                              pt.x, pt.y, 0, EVENT_x11_time_to_win32_time(event->time), 0, 0 );
1080 }