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