mshtml: Remove not used argument of nsACString_GetData.
[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             wine_tsx11_lock();
287             if (cursor_pos.x == x && cursor_pos.y == y &&
288                 (flags & ~(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE)))
289                 flags &= ~MOUSEEVENTF_MOVE;
290             wine_tsx11_unlock();
291         }
292     }
293     else if (flags & MOUSEEVENTF_MOVE)
294     {
295         int accel[3], xMult = 1, yMult = 1;
296
297         /* dx and dy can be negative numbers for relative movements */
298         SystemParametersInfoW(SPI_GETMOUSE, 0, accel, 0);
299
300         if (abs(x) > accel[0] && accel[2] != 0)
301         {
302             xMult = 2;
303             if ((abs(x) > accel[1]) && (accel[2] == 2)) xMult = 4;
304         }
305         if (abs(y) > accel[0] && accel[2] != 0)
306         {
307             yMult = 2;
308             if ((abs(y) > accel[1]) && (accel[2] == 2)) yMult = 4;
309         }
310
311         wine_tsx11_lock();
312         pt.x = cursor_pos.x + (long)x * xMult;
313         pt.y = cursor_pos.y + (long)y * yMult;
314         wine_tsx11_unlock();
315     }
316     else
317     {
318         wine_tsx11_lock();
319         pt = cursor_pos;
320         wine_tsx11_unlock();
321     }
322
323     if (flags & MOUSEEVENTF_MOVE)
324     {
325         queue_raw_mouse_message( WM_MOUSEMOVE, hwnd, pt.x, pt.y, data, time,
326                                  extra_info, injected_flags );
327         if ((injected_flags & LLMHF_INJECTED) &&
328             ((flags & MOUSEEVENTF_ABSOLUTE) || x || y))  /* we have to actually move the cursor */
329         {
330             X11DRV_SetCursorPos( pt.x, pt.y );
331         }
332         else
333         {
334             wine_tsx11_lock();
335             clip_point_to_rect( &cursor_clip, &pt);
336             cursor_pos = pt;
337             wine_tsx11_unlock();
338         }
339     }
340     if (flags & MOUSEEVENTF_LEFTDOWN)
341     {
342         key_state_table[VK_LBUTTON] |= 0xc0;
343         queue_raw_mouse_message( GetSystemMetrics(SM_SWAPBUTTON) ? WM_RBUTTONDOWN : WM_LBUTTONDOWN,
344                                  hwnd, pt.x, pt.y, data, time, extra_info, injected_flags );
345     }
346     if (flags & MOUSEEVENTF_LEFTUP)
347     {
348         key_state_table[VK_LBUTTON] &= ~0x80;
349         queue_raw_mouse_message( GetSystemMetrics(SM_SWAPBUTTON) ? WM_RBUTTONUP : WM_LBUTTONUP,
350                                  hwnd, pt.x, pt.y, data, time, extra_info, injected_flags );
351     }
352     if (flags & MOUSEEVENTF_RIGHTDOWN)
353     {
354         key_state_table[VK_RBUTTON] |= 0xc0;
355         queue_raw_mouse_message( GetSystemMetrics(SM_SWAPBUTTON) ? WM_LBUTTONDOWN : WM_RBUTTONDOWN,
356                                  hwnd, pt.x, pt.y, data, time, extra_info, injected_flags );
357     }
358     if (flags & MOUSEEVENTF_RIGHTUP)
359     {
360         key_state_table[VK_RBUTTON] &= ~0x80;
361         queue_raw_mouse_message( GetSystemMetrics(SM_SWAPBUTTON) ? WM_LBUTTONUP : WM_RBUTTONUP,
362                                  hwnd, pt.x, pt.y, data, time, extra_info, injected_flags );
363     }
364     if (flags & MOUSEEVENTF_MIDDLEDOWN)
365     {
366         key_state_table[VK_MBUTTON] |= 0xc0;
367         queue_raw_mouse_message( WM_MBUTTONDOWN, hwnd, pt.x, pt.y, data, time,
368                                  extra_info, injected_flags );
369     }
370     if (flags & MOUSEEVENTF_MIDDLEUP)
371     {
372         key_state_table[VK_MBUTTON] &= ~0x80;
373         queue_raw_mouse_message( WM_MBUTTONUP, hwnd, pt.x, pt.y, data, time,
374                                  extra_info, injected_flags );
375     }
376     if (flags & MOUSEEVENTF_WHEEL)
377     {
378         queue_raw_mouse_message( WM_MOUSEWHEEL, hwnd, pt.x, pt.y, data, time,
379                                  extra_info, injected_flags );
380     }
381     if (flags & MOUSEEVENTF_XDOWN)
382     {
383         key_state_table[VK_XBUTTON1 + data - 1] |= 0xc0;
384         queue_raw_mouse_message( WM_XBUTTONDOWN, hwnd, pt.x, pt.y, data, time,
385                                  extra_info, injected_flags );
386     }
387     if (flags & MOUSEEVENTF_XUP)
388     {
389         key_state_table[VK_XBUTTON1 + data - 1] &= ~0x80;
390         queue_raw_mouse_message( WM_XBUTTONUP, hwnd, pt.x, pt.y, data, time,
391                                  extra_info, injected_flags );
392     }
393 }
394
395
396 #ifdef SONAME_LIBXCURSOR
397
398 /***********************************************************************
399  *              create_cursor_image
400  *
401  * Create an XcursorImage from a CURSORICONINFO
402  */
403 static XcursorImage *create_cursor_image( CURSORICONINFO *ptr )
404 {
405     int x, xmax;
406     int y, ymax;
407     int and_size, xor_size;
408     unsigned char *and_bits, *and_ptr, *xor_bits, *xor_ptr;
409     int and_width_bytes, xor_width_bytes;
410     XcursorPixel *pixel_ptr;
411     XcursorImage *image;
412     BOOL alpha_zero = TRUE;
413
414     ymax = (ptr->nHeight > 32) ? 32 : ptr->nHeight;
415     xmax = (ptr->nWidth > 32) ? 32 : ptr->nWidth;
416
417     and_width_bytes = xmax / 8;
418     xor_width_bytes = and_width_bytes * ptr->bBitsPerPixel;
419
420     and_size = ptr->nWidth * ptr->nHeight / 8;
421     and_ptr = and_bits = (unsigned char *)(ptr + 1);
422
423     xor_size = xor_width_bytes * ptr->nHeight;
424     xor_ptr = xor_bits = and_ptr + and_size;
425
426     image = pXcursorImageCreate( xmax, ymax );
427     pixel_ptr = image->pixels;
428
429     /* Generally 32 bit bitmaps have an alpha channel which is used in favor
430      * of the AND mask. However, if all pixels have alpha = 0x00, the bitmap
431      * is treated like one without alpha and the masks are used. As soon as
432      * one pixel has alpha != 0x00, and the mask ignored as described in the
433      * docs.
434      *
435      * This is most likely for applications which create the bitmaps with
436      * CreateDIBitmap, which creates a device dependent bitmap, so the format
437      * that arrives when loading depends on the screen's bpp. Apps that were
438      * written at 8 / 16 bpp times do not know about the 32 bit alpha, so
439      * they would get a completely transparent cursor on 32 bit displays.
440      *
441      * Non-32 bit bitmaps always use the AND mask
442      */
443     if(ptr->bBitsPerPixel == 32)
444     {
445         for (y = 0; alpha_zero && y < ymax; ++y)
446         {
447             xor_ptr = xor_bits + (y * xor_width_bytes);
448             for (x = 0; x < xmax; ++x)
449             {
450                 if (xor_ptr[3] != 0x00)
451                 {
452                     alpha_zero = FALSE;
453                     break;
454                 }
455                 xor_ptr+=4;
456             }
457         }
458     }
459
460     /* On windows, to calculate the color for a pixel, first an AND is done
461      * with the background and the "and" bitmap, then an XOR with the "xor"
462      * bitmap. This means that when the data in the "and" bitmap is 0, the
463      * pixel will get the color as specified in the "xor" bitmap.
464      * However, if the data in the "and" bitmap is 1, the result will be the
465      * background XOR'ed with the value in the "xor" bitmap. In case the "xor"
466      * data is completely black (0x000000) the pixel will become transparent,
467      * in case it's white (0xffffff) the pixel will become the inverse of the
468      * background color.
469      *
470      * Since we can't support inverting colors, we map the grayscale value of
471      * the "xor" data to the alpha channel, and xor the color with either
472      * black or white.
473      */
474     for (y = 0; y < ymax; ++y)
475     {
476         and_ptr = and_bits + (y * and_width_bytes);
477         xor_ptr = xor_bits + (y * xor_width_bytes);
478
479         for (x = 0; x < xmax; ++x)
480         {
481             /* Xcursor pixel data is in ARGB format, with A in the high byte */
482             switch (ptr->bBitsPerPixel)
483             {
484                 case 32:
485                     /* BGRA, 8 bits each */
486                     *pixel_ptr = *xor_ptr++;
487                     *pixel_ptr |= *xor_ptr++ << 8;
488                     *pixel_ptr |= *xor_ptr++ << 16;
489                     *pixel_ptr |= *xor_ptr++ << 24;
490                     break;
491
492                 case 24:
493                     /* BGR, 8 bits each */
494                     *pixel_ptr = *xor_ptr++;
495                     *pixel_ptr |= *xor_ptr++ << 8;
496                     *pixel_ptr |= *xor_ptr++ << 16;
497                     break;
498
499                 case 16:
500                     /* BGR, 5 red, 6 green, 5 blue */
501                     *pixel_ptr = *xor_ptr * 0x1f;
502                     *pixel_ptr |= (*xor_ptr & 0xe0) << 3;
503                     ++xor_ptr;
504                     *pixel_ptr |= (*xor_ptr & 0x07) << 11;
505                     *pixel_ptr |= (*xor_ptr & 0xf8) << 13;
506                     break;
507
508                 case 1:
509                     if (*xor_ptr & (1 << (7 - (x & 7)))) *pixel_ptr = 0xffffff;
510                     else *pixel_ptr = 0;
511                     if ((x & 7) == 7) ++xor_ptr;
512                     break;
513
514                 default:
515                     FIXME("Currently no support for cursors with %d bits per pixel\n", ptr->bBitsPerPixel);
516                     return 0;
517             }
518
519             if (alpha_zero)
520             {
521                 /* Alpha channel */
522                 if (~*and_ptr & (1 << (7 - (x & 7)))) *pixel_ptr |= 0xff << 24;
523                 else if (*pixel_ptr)
524                 {
525                     int alpha = (*pixel_ptr & 0xff) * 0.30f
526                             + ((*pixel_ptr & 0xff00) >> 8) * 0.55f
527                             + ((*pixel_ptr & 0xff0000) >> 16) * 0.15f;
528                     *pixel_ptr ^= ((x + y) % 2) ? 0xffffff : 0x000000;
529                     *pixel_ptr |= alpha << 24;
530                 }
531                 if ((x & 7) == 7) ++and_ptr;
532             }
533             ++pixel_ptr;
534         }
535     }
536
537     return image;
538 }
539
540
541 /***********************************************************************
542  *              create_xcursor_cursor
543  *
544  * Use Xcursor to create an X cursor from a Windows one.
545  */
546 static Cursor create_xcursor_cursor( Display *display, CURSORICONINFO *ptr )
547 {
548     Cursor cursor;
549     XcursorImage *image;
550
551     if (!ptr) /* Create an empty cursor */
552     {
553         image = pXcursorImageCreate( 1, 1 );
554         image->xhot = 0;
555         image->yhot = 0;
556         *(image->pixels) = 0;
557         cursor = pXcursorImageLoadCursor( display, image );
558         pXcursorImageDestroy( image );
559
560         return cursor;
561     }
562
563     image = create_cursor_image( ptr );
564     if (!image) return 0;
565
566     /* Make sure hotspot is valid */
567     image->xhot = ptr->ptHotSpot.x;
568     image->yhot = ptr->ptHotSpot.y;
569     if (image->xhot < 0 || image->xhot >= image->width ||
570         image->yhot < 0 || image->yhot >= image->height)
571     {
572         image->xhot = image->width / 2;
573         image->yhot = image->height / 2;
574     }
575
576     image->delay = 0;
577
578     cursor = pXcursorImageLoadCursor( display, image );
579     pXcursorImageDestroy( image );
580
581     return cursor;
582 }
583
584 #endif /* SONAME_LIBXCURSOR */
585
586
587 /***********************************************************************
588  *              create_cursor
589  *
590  * Create an X cursor from a Windows one.
591  */
592 static Cursor create_cursor( Display *display, CURSORICONINFO *ptr )
593 {
594     Pixmap pixmapBits, pixmapMask, pixmapMaskInv = 0, pixmapAll;
595     XColor fg, bg;
596     Cursor cursor = None;
597     POINT hotspot;
598     char *bitMask32 = NULL;
599
600 #ifdef SONAME_LIBXCURSOR
601     if (pXcursorImageLoadCursor) return create_xcursor_cursor( display, ptr );
602 #endif
603
604     if (!ptr)  /* Create an empty cursor */
605     {
606         static const char data[] = { 0 };
607
608         bg.red = bg.green = bg.blue = 0x0000;
609         pixmapBits = XCreateBitmapFromData( display, root_window, data, 1, 1 );
610         if (pixmapBits)
611         {
612             cursor = XCreatePixmapCursor( display, pixmapBits, pixmapBits,
613                                           &bg, &bg, 0, 0 );
614             XFreePixmap( display, pixmapBits );
615         }
616     }
617     else  /* Create the X cursor from the bits */
618     {
619         XImage *image;
620         GC gc;
621
622         TRACE("Bitmap %dx%d planes=%d bpp=%d bytesperline=%d\n",
623             ptr->nWidth, ptr->nHeight, ptr->bPlanes, ptr->bBitsPerPixel,
624             ptr->nWidthBytes);
625
626         /* Create a pixmap and transfer all the bits to it */
627
628         /* NOTE: Following hack works, but only because XFree depth
629          *       1 images really use 1 bit/pixel (and so the same layout
630          *       as the Windows cursor data). Perhaps use a more generic
631          *       algorithm here.
632          */
633         /* This pixmap will be written with two bitmaps. The first is
634          *  the mask and the second is the image.
635          */
636         if (!(pixmapAll = XCreatePixmap( display, root_window,
637                   ptr->nWidth, ptr->nHeight * 2, 1 )))
638             return 0;
639         if (!(image = XCreateImage( display, visual,
640                 1, ZPixmap, 0, (char *)(ptr + 1), ptr->nWidth,
641                 ptr->nHeight * 2, 16, ptr->nWidthBytes/ptr->bBitsPerPixel)))
642         {
643             XFreePixmap( display, pixmapAll );
644             return 0;
645         }
646         gc = XCreateGC( display, pixmapAll, 0, NULL );
647         XSetGraphicsExposures( display, gc, False );
648         image->byte_order = MSBFirst;
649         image->bitmap_bit_order = MSBFirst;
650         image->bitmap_unit = 16;
651         _XInitImageFuncPtrs(image);
652         if (ptr->bPlanes * ptr->bBitsPerPixel == 1)
653         {
654             /* A plain old white on black cursor. */
655             fg.red = fg.green = fg.blue = 0xffff;
656             bg.red = bg.green = bg.blue = 0x0000;
657             XPutImage( display, pixmapAll, gc, image,
658                 0, 0, 0, 0, ptr->nWidth, ptr->nHeight * 2 );
659         }
660         else
661         {
662             int     rbits, gbits, bbits, red, green, blue;
663             int     rfg, gfg, bfg, rbg, gbg, bbg;
664             int     rscale, gscale, bscale;
665             int     x, y, xmax, ymax, bitIndex, byteIndex, xorIndex;
666             unsigned char *theMask, *theImage, theChar;
667             int     threshold, fgBits, bgBits, bitShifted;
668             BYTE    pXorBits[128];   /* Up to 32x32 icons */
669
670             switch (ptr->bBitsPerPixel)
671             {
672             case 32:
673                 bitMask32 = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
674                                        ptr->nWidth * ptr->nHeight / 8 );
675                 /* Fallthrough */
676             case 24:
677                 rbits = 8;
678                 gbits = 8;
679                 bbits = 8;
680                 threshold = 0x40;
681                 break;
682             case 16:
683                 rbits = 5;
684                 gbits = 6;
685                 bbits = 5;
686                 threshold = 0x40;
687                 break;
688             default:
689                 FIXME("Currently no support for cursors with %d bits per pixel\n",
690                   ptr->bBitsPerPixel);
691                 XFreePixmap( display, pixmapAll );
692                 XFreeGC( display, gc );
693                 image->data = NULL;
694                 XDestroyImage( image );
695                 return 0;
696             }
697             /* The location of the mask. */
698             theMask = (unsigned char *)(ptr + 1);
699             /* The mask should still be 1 bit per pixel. The color image
700              * should immediately follow the mask.
701              */
702             theImage = &theMask[ptr->nWidth/8 * ptr->nHeight];
703             rfg = gfg = bfg = rbg = gbg = bbg = 0;
704             bitIndex = 0;
705             byteIndex = 0;
706             xorIndex = 0;
707             fgBits = 0;
708             bitShifted = 0x01;
709             xmax = (ptr->nWidth > 32) ? 32 : ptr->nWidth;
710             if (ptr->nWidth > 32) {
711                 ERR("Got a %dx%d cursor. Cannot handle larger than 32x32.\n",
712                   ptr->nWidth, ptr->nHeight);
713             }
714             ymax = (ptr->nHeight > 32) ? 32 : ptr->nHeight;
715
716             memset(pXorBits, 0, 128);
717             for (y=0; y<ymax; y++)
718             {
719                 for (x=0; x<xmax; x++)
720                 {
721                         red = green = blue = 0;
722                         switch (ptr->bBitsPerPixel)
723                         {
724                         case 32:
725                             theChar = theImage[byteIndex++];
726                             blue = theChar;
727                             theChar = theImage[byteIndex++];
728                             green = theChar;
729                             theChar = theImage[byteIndex++];
730                             red = theChar;
731                             theChar = theImage[byteIndex++];
732                             /* If the alpha channel is >5% transparent,
733                              * assume that we can add it to the bitMask32.
734                              */
735                             if (theChar > 0x0D)
736                                 *(bitMask32 + (y*xmax+x)/8) |= 1 << (x & 7);
737                             break;
738                         case 24:
739                             theChar = theImage[byteIndex++];
740                             blue = theChar;
741                             theChar = theImage[byteIndex++];
742                             green = theChar;
743                             theChar = theImage[byteIndex++];
744                             red = theChar;
745                             break;
746                         case 16:
747                             theChar = theImage[byteIndex++];
748                             blue = theChar & 0x1F;
749                             green = (theChar & 0xE0) >> 5;
750                             theChar = theImage[byteIndex++];
751                             green |= (theChar & 0x07) << 3;
752                             red = (theChar & 0xF8) >> 3;
753                             break;
754                         }
755
756                     if (red+green+blue > threshold)
757                     {
758                         rfg += red;
759                         gfg += green;
760                         bfg += blue;
761                         fgBits++;
762                         pXorBits[xorIndex] |= bitShifted;
763                     }
764                     else
765                     {
766                         rbg += red;
767                         gbg += green;
768                         bbg += blue;
769                     }
770                     if (x%8 == 7)
771                     {
772                         bitShifted = 0x01;
773                         xorIndex++;
774                     }
775                     else
776                         bitShifted = bitShifted << 1;
777                 }
778             }
779             rscale = 1 << (16 - rbits);
780             gscale = 1 << (16 - gbits);
781             bscale = 1 << (16 - bbits);
782             if (fgBits)
783             {
784                 fg.red   = rfg * rscale / fgBits;
785                 fg.green = gfg * gscale / fgBits;
786                 fg.blue  = bfg * bscale / fgBits;
787             }
788             else fg.red = fg.green = fg.blue = 0;
789             bgBits = xmax * ymax - fgBits;
790             if (bgBits)
791             {
792                 bg.red   = rbg * rscale / bgBits;
793                 bg.green = gbg * gscale / bgBits;
794                 bg.blue  = bbg * bscale / bgBits;
795             }
796             else bg.red = bg.green = bg.blue = 0;
797             pixmapBits = XCreateBitmapFromData( display, root_window, (char *)pXorBits, xmax, ymax );
798             if (!pixmapBits)
799             {
800                 HeapFree( GetProcessHeap(), 0, bitMask32 );
801                 XFreePixmap( display, pixmapAll );
802                 XFreeGC( display, gc );
803                 image->data = NULL;
804                 XDestroyImage( image );
805                 return 0;
806             }
807
808             /* Put the mask. */
809             XPutImage( display, pixmapAll, gc, image,
810                    0, 0, 0, 0, ptr->nWidth, ptr->nHeight );
811             XSetFunction( display, gc, GXcopy );
812             /* Put the image */
813             XCopyArea( display, pixmapBits, pixmapAll, gc,
814                        0, 0, xmax, ymax, 0, ptr->nHeight );
815             XFreePixmap( display, pixmapBits );
816         }
817         image->data = NULL;
818         XDestroyImage( image );
819
820         /* Now create the 2 pixmaps for bits and mask */
821
822         pixmapBits = XCreatePixmap( display, root_window, ptr->nWidth, ptr->nHeight, 1 );
823         if (ptr->bBitsPerPixel != 32)
824         {
825             pixmapMaskInv = XCreatePixmap( display, root_window, ptr->nWidth, ptr->nHeight, 1 );
826             pixmapMask = XCreatePixmap( display, root_window, ptr->nWidth, ptr->nHeight, 1 );
827
828             /* Make sure everything went OK so far */
829             if (pixmapBits && pixmapMask && pixmapMaskInv)
830             {
831                 /* We have to do some magic here, as cursors are not fully
832                  * compatible between Windows and X11. Under X11, there are
833                  * only 3 possible color cursor: black, white and masked. So
834                  * we map the 4th Windows color (invert the bits on the screen)
835                  * to black and an additional white bit on an other place
836                  * (+1,+1). This require some boolean arithmetic:
837                  *
838                  *         Windows          |          X11
839                  * And    Xor      Result   |   Bits     Mask     Result
840                  *  0      0     black      |    0        1     background
841                  *  0      1     white      |    1        1     foreground
842                  *  1      0     no change  |    X        0     no change
843                  *  1      1     inverted   |    0        1     background
844                  *
845                  * which gives:
846                  *  Bits = not 'And' and 'Xor' or 'And2' and 'Xor2'
847                  *  Mask = not 'And' or 'Xor' or 'And2' and 'Xor2'
848                  *
849                  * FIXME: apparently some servers do support 'inverted' color.
850                  * I don't know if it's correct per the X spec, but maybe we
851                  * ought to take advantage of it.  -- AJ
852                  */
853                 XSetFunction( display, gc, GXcopy );
854                 XCopyArea( display, pixmapAll, pixmapBits, gc,
855                            0, 0, ptr->nWidth, ptr->nHeight, 0, 0 );
856                 XCopyArea( display, pixmapAll, pixmapMask, gc,
857                            0, 0, ptr->nWidth, ptr->nHeight, 0, 0 );
858                 XCopyArea( display, pixmapAll, pixmapMaskInv, gc,
859                            0, 0, ptr->nWidth, ptr->nHeight, 0, 0 );
860                 XSetFunction( display, gc, GXand );
861                 XCopyArea( display, pixmapAll, pixmapMaskInv, gc,
862                            0, ptr->nHeight, ptr->nWidth, ptr->nHeight, 0, 0 );
863                 XSetFunction( display, gc, GXandReverse );
864                 XCopyArea( display, pixmapAll, pixmapBits, gc,
865                            0, ptr->nHeight, ptr->nWidth, ptr->nHeight, 0, 0 );
866                 XSetFunction( display, gc, GXorReverse );
867                 XCopyArea( display, pixmapAll, pixmapMask, gc,
868                            0, ptr->nHeight, ptr->nWidth, ptr->nHeight, 0, 0 );
869                 /* Additional white */
870                 XSetFunction( display, gc, GXor );
871                 XCopyArea( display, pixmapMaskInv, pixmapMask, gc,
872                            0, 0, ptr->nWidth, ptr->nHeight, 1, 1 );
873                 XCopyArea( display, pixmapMaskInv, pixmapBits, gc,
874                            0, 0, ptr->nWidth, ptr->nHeight, 1, 1 );
875                 XSetFunction( display, gc, GXcopy );
876             }
877         }
878         else
879         {
880             pixmapMask = XCreateBitmapFromData( display, root_window,
881                                                 bitMask32, ptr->nWidth,
882                                                 ptr->nHeight );
883             HeapFree( GetProcessHeap(), 0, bitMask32 );
884         }
885
886         /* Make sure hotspot is valid */
887         hotspot.x = ptr->ptHotSpot.x;
888         hotspot.y = ptr->ptHotSpot.y;
889         if (hotspot.x < 0 || hotspot.x >= ptr->nWidth ||
890             hotspot.y < 0 || hotspot.y >= ptr->nHeight)
891         {
892             hotspot.x = ptr->nWidth / 2;
893             hotspot.y = ptr->nHeight / 2;
894         }
895
896         if (pixmapBits && pixmapMask)
897             cursor = XCreatePixmapCursor( display, pixmapBits, pixmapMask,
898                                           &fg, &bg, hotspot.x, hotspot.y );
899
900         /* Now free everything */
901
902         if (pixmapAll) XFreePixmap( display, pixmapAll );
903         if (pixmapBits) XFreePixmap( display, pixmapBits );
904         if (pixmapMask) XFreePixmap( display, pixmapMask );
905         if (pixmapMaskInv) XFreePixmap( display, pixmapMaskInv );
906         XFreeGC( display, gc );
907     }
908     return cursor;
909 }
910
911
912 /***********************************************************************
913  *              SetCursor (X11DRV.@)
914  */
915 void X11DRV_SetCursor( CURSORICONINFO *lpCursor )
916 {
917     struct x11drv_thread_data *data = x11drv_thread_data();
918     Cursor cursor;
919
920     if (lpCursor)
921         TRACE("%ux%u, planes %u, bpp %u\n",
922               lpCursor->nWidth, lpCursor->nHeight, lpCursor->bPlanes, lpCursor->bBitsPerPixel);
923     else
924         TRACE("NULL\n");
925
926     /* set the same cursor for all top-level windows of the current thread */
927
928     wine_tsx11_lock();
929     cursor = create_cursor( data->display, lpCursor );
930     if (cursor)
931     {
932         if (data->cursor) XFreeCursor( data->display, data->cursor );
933         data->cursor = cursor;
934         if (data->cursor_window)
935         {
936             XDefineCursor( data->display, data->cursor_window, cursor );
937             /* Make the change take effect immediately */
938             XFlush( data->display );
939         }
940     }
941     wine_tsx11_unlock();
942 }
943
944 /***********************************************************************
945  *              SetCursorPos (X11DRV.@)
946  */
947 BOOL X11DRV_SetCursorPos( INT x, INT y )
948 {
949     Display *display = thread_display();
950     POINT pt;
951
952     TRACE( "warping to (%d,%d)\n", x, y );
953
954     wine_tsx11_lock();
955     if (cursor_pos.x == x && cursor_pos.y == y)
956     {
957         wine_tsx11_unlock();
958         /* We still need to generate WM_MOUSEMOVE */
959         queue_raw_mouse_message( WM_MOUSEMOVE, NULL, x, y, 0, GetCurrentTime(), 0, 0 );
960         return TRUE;
961     }
962
963     pt.x = x; pt.y = y;
964     clip_point_to_rect( &cursor_clip, &pt);
965     XWarpPointer( display, root_window, root_window, 0, 0, 0, 0,
966                   pt.x - virtual_screen_rect.left, pt.y - virtual_screen_rect.top );
967     XFlush( display ); /* avoids bad mouse lag in games that do their own mouse warping */
968     cursor_pos = pt;
969     wine_tsx11_unlock();
970     return TRUE;
971 }
972
973 /***********************************************************************
974  *              GetCursorPos (X11DRV.@)
975  */
976 BOOL X11DRV_GetCursorPos(LPPOINT pos)
977 {
978     Display *display = thread_display();
979     Window root, child;
980     int rootX, rootY, winX, winY;
981     unsigned int xstate;
982
983     wine_tsx11_lock();
984     if ((GetTickCount() - last_time_modified > 100) &&
985         XQueryPointer( display, root_window, &root, &child,
986                        &rootX, &rootY, &winX, &winY, &xstate ))
987     {
988         update_button_state( xstate );
989         winX += virtual_screen_rect.left;
990         winY += virtual_screen_rect.top;
991         TRACE("pointer at (%d,%d)\n", winX, winY );
992         cursor_pos.x = winX;
993         cursor_pos.y = winY;
994     }
995     *pos = cursor_pos;
996     wine_tsx11_unlock();
997     return TRUE;
998 }
999
1000
1001 /***********************************************************************
1002  *              ClipCursor (X11DRV.@)
1003  *
1004  * Set the cursor clipping rectangle.
1005  */
1006 BOOL X11DRV_ClipCursor( LPCRECT clip )
1007 {
1008     if (!IntersectRect( &cursor_clip, &virtual_screen_rect, clip ))
1009         cursor_clip = virtual_screen_rect;
1010
1011     return TRUE;
1012 }
1013
1014 /***********************************************************************
1015  *           X11DRV_ButtonPress
1016  */
1017 void X11DRV_ButtonPress( HWND hwnd, XEvent *xev )
1018 {
1019     XButtonEvent *event = &xev->xbutton;
1020     int buttonNum = event->button - 1;
1021     WORD wData = 0;
1022     POINT pt;
1023
1024     if (buttonNum >= NB_BUTTONS) return;
1025     if (!hwnd) return;
1026
1027     switch (buttonNum)
1028     {
1029     case 3:
1030         wData = WHEEL_DELTA;
1031         break;
1032     case 4:
1033         wData = -WHEEL_DELTA;
1034         break;
1035     case 5:
1036         wData = XBUTTON1;
1037         break;
1038     case 6:
1039         wData = XBUTTON2;
1040         break;
1041     }
1042
1043     update_mouse_state( hwnd, event->window, event->x, event->y, event->state, &pt );
1044
1045     X11DRV_send_mouse_input( hwnd, button_down_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE,
1046                              pt.x, pt.y, wData, EVENT_x11_time_to_win32_time(event->time), 0, 0 );
1047 }
1048
1049
1050 /***********************************************************************
1051  *           X11DRV_ButtonRelease
1052  */
1053 void X11DRV_ButtonRelease( HWND hwnd, XEvent *xev )
1054 {
1055     XButtonEvent *event = &xev->xbutton;
1056     int buttonNum = event->button - 1;
1057     WORD wData = 0;
1058     POINT pt;
1059
1060     if (buttonNum >= NB_BUTTONS || !button_up_flags[buttonNum]) return;
1061     if (!hwnd) return;
1062
1063     switch (buttonNum)
1064     {
1065     case 5:
1066         wData = XBUTTON1;
1067         break;
1068     case 6:
1069         wData = XBUTTON2;
1070         break;
1071     }
1072
1073     update_mouse_state( hwnd, event->window, event->x, event->y, event->state, &pt );
1074
1075     X11DRV_send_mouse_input( hwnd, button_up_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE,
1076                              pt.x, pt.y, wData, EVENT_x11_time_to_win32_time(event->time), 0, 0 );
1077 }
1078
1079
1080 /***********************************************************************
1081  *           X11DRV_MotionNotify
1082  */
1083 void X11DRV_MotionNotify( HWND hwnd, XEvent *xev )
1084 {
1085     XMotionEvent *event = &xev->xmotion;
1086     POINT pt;
1087
1088     TRACE("hwnd %p, event->is_hint %d\n", hwnd, event->is_hint);
1089
1090     if (!hwnd) return;
1091
1092     update_mouse_state( hwnd, event->window, event->x, event->y, event->state, &pt );
1093
1094     X11DRV_send_mouse_input( hwnd, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE,
1095                              pt.x, pt.y, 0, EVENT_x11_time_to_win32_time(event->time), 0, 0 );
1096 }
1097
1098
1099 /***********************************************************************
1100  *           X11DRV_EnterNotify
1101  */
1102 void X11DRV_EnterNotify( HWND hwnd, XEvent *xev )
1103 {
1104     XCrossingEvent *event = &xev->xcrossing;
1105     POINT pt;
1106
1107     TRACE("hwnd %p, event->detail %d\n", hwnd, event->detail);
1108
1109     if (!hwnd) return;
1110     if (event->detail == NotifyVirtual || event->detail == NotifyNonlinearVirtual) return;
1111
1112     /* simulate a mouse motion event */
1113     update_mouse_state( hwnd, event->window, event->x, event->y, event->state, &pt );
1114
1115     X11DRV_send_mouse_input( hwnd, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE,
1116                              pt.x, pt.y, 0, EVENT_x11_time_to_win32_time(event->time), 0, 0 );
1117 }