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