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