explorer: Move screen saver activation to the X11 driver.
[wine.git] / dlls / winex11.drv / mouse.c
blobf737a306a5628c5cb2ef41ae11a39edf10ce4227
1 /*
2 * X11 mouse driver
4 * Copyright 1998 Ulrich Weigand
5 * Copyright 2007 Henri Verbeet
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.
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.
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
22 #include "config.h"
23 #include "wine/port.h"
25 #include <X11/Xlib.h>
26 #include <X11/cursorfont.h>
27 #include <stdarg.h>
28 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
29 #include <X11/extensions/XInput2.h>
30 #endif
32 #ifdef SONAME_LIBXCURSOR
33 # include <X11/Xcursor/Xcursor.h>
34 static void *xcursor_handle;
35 # define MAKE_FUNCPTR(f) static typeof(f) * p##f
36 MAKE_FUNCPTR(XcursorImageCreate);
37 MAKE_FUNCPTR(XcursorImageDestroy);
38 MAKE_FUNCPTR(XcursorImageLoadCursor);
39 MAKE_FUNCPTR(XcursorImagesCreate);
40 MAKE_FUNCPTR(XcursorImagesDestroy);
41 MAKE_FUNCPTR(XcursorImagesLoadCursor);
42 MAKE_FUNCPTR(XcursorLibraryLoadCursor);
43 # undef MAKE_FUNCPTR
44 #endif /* SONAME_LIBXCURSOR */
46 #define NONAMELESSUNION
47 #define OEMRESOURCE
48 #include "windef.h"
49 #include "winbase.h"
50 #include "winreg.h"
52 #include "x11drv.h"
53 #include "wine/server.h"
54 #include "wine/library.h"
55 #include "wine/unicode.h"
56 #include "wine/debug.h"
58 WINE_DEFAULT_DEBUG_CHANNEL(cursor);
60 /**********************************************************************/
62 #ifndef Button6Mask
63 #define Button6Mask (1<<13)
64 #endif
65 #ifndef Button7Mask
66 #define Button7Mask (1<<14)
67 #endif
69 #define NB_BUTTONS 9 /* Windows can handle 5 buttons and the wheel too */
71 static const UINT button_down_flags[NB_BUTTONS] =
73 MOUSEEVENTF_LEFTDOWN,
74 MOUSEEVENTF_MIDDLEDOWN,
75 MOUSEEVENTF_RIGHTDOWN,
76 MOUSEEVENTF_WHEEL,
77 MOUSEEVENTF_WHEEL,
78 MOUSEEVENTF_XDOWN, /* FIXME: horizontal wheel */
79 MOUSEEVENTF_XDOWN,
80 MOUSEEVENTF_XDOWN,
81 MOUSEEVENTF_XDOWN
84 static const UINT button_up_flags[NB_BUTTONS] =
86 MOUSEEVENTF_LEFTUP,
87 MOUSEEVENTF_MIDDLEUP,
88 MOUSEEVENTF_RIGHTUP,
91 MOUSEEVENTF_XUP,
92 MOUSEEVENTF_XUP,
93 MOUSEEVENTF_XUP,
94 MOUSEEVENTF_XUP
97 static const UINT button_down_data[NB_BUTTONS] =
102 WHEEL_DELTA,
103 -WHEEL_DELTA,
104 XBUTTON1,
105 XBUTTON2,
106 XBUTTON1,
107 XBUTTON2
110 static const UINT button_up_data[NB_BUTTONS] =
117 XBUTTON1,
118 XBUTTON2,
119 XBUTTON1,
120 XBUTTON2
123 XContext cursor_context = 0;
125 static HWND cursor_window;
126 static HCURSOR last_cursor;
127 static DWORD last_cursor_change;
128 static RECT clip_rect;
129 static Cursor create_cursor( HANDLE handle );
131 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
132 static BOOL xinput2_available;
133 static BOOL broken_rawevents;
134 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
135 MAKE_FUNCPTR(XIGetClientPointer);
136 MAKE_FUNCPTR(XIFreeDeviceInfo);
137 MAKE_FUNCPTR(XIQueryDevice);
138 MAKE_FUNCPTR(XIQueryVersion);
139 MAKE_FUNCPTR(XISelectEvents);
140 #undef MAKE_FUNCPTR
141 #endif
143 /***********************************************************************
144 * X11DRV_Xcursor_Init
146 * Load the Xcursor library for use.
148 void X11DRV_Xcursor_Init(void)
150 #ifdef SONAME_LIBXCURSOR
151 xcursor_handle = wine_dlopen(SONAME_LIBXCURSOR, RTLD_NOW, NULL, 0);
152 if (!xcursor_handle) /* wine_dlopen failed. */
154 WARN("Xcursor failed to load. Using fallback code.\n");
155 return;
157 #define LOAD_FUNCPTR(f) \
158 p##f = wine_dlsym(xcursor_handle, #f, NULL, 0)
160 LOAD_FUNCPTR(XcursorImageCreate);
161 LOAD_FUNCPTR(XcursorImageDestroy);
162 LOAD_FUNCPTR(XcursorImageLoadCursor);
163 LOAD_FUNCPTR(XcursorImagesCreate);
164 LOAD_FUNCPTR(XcursorImagesDestroy);
165 LOAD_FUNCPTR(XcursorImagesLoadCursor);
166 LOAD_FUNCPTR(XcursorLibraryLoadCursor);
167 #undef LOAD_FUNCPTR
168 #endif /* SONAME_LIBXCURSOR */
172 /***********************************************************************
173 * get_empty_cursor
175 static Cursor get_empty_cursor(void)
177 static Cursor cursor;
178 static const char data[] = { 0 };
180 if (!cursor)
182 XColor bg;
183 Pixmap pixmap;
185 bg.red = bg.green = bg.blue = 0x0000;
186 pixmap = XCreateBitmapFromData( gdi_display, root_window, data, 1, 1 );
187 if (pixmap)
189 Cursor new = XCreatePixmapCursor( gdi_display, pixmap, pixmap, &bg, &bg, 0, 0 );
190 if (InterlockedCompareExchangePointer( (void **)&cursor, (void *)new, 0 ))
191 XFreeCursor( gdi_display, new );
192 XFreePixmap( gdi_display, pixmap );
195 return cursor;
198 /***********************************************************************
199 * set_window_cursor
201 void set_window_cursor( Window window, HCURSOR handle )
203 Cursor cursor, prev;
205 if (!handle) cursor = get_empty_cursor();
206 else if (XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&cursor ))
208 /* try to create it */
209 if (!(cursor = create_cursor( handle ))) return;
211 XLockDisplay( gdi_display );
212 if (!XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&prev ))
214 /* someone else was here first */
215 XFreeCursor( gdi_display, cursor );
216 cursor = prev;
218 else
220 XSaveContext( gdi_display, (XID)handle, cursor_context, (char *)cursor );
221 TRACE( "cursor %p created %lx\n", handle, cursor );
223 XUnlockDisplay( gdi_display );
226 XDefineCursor( gdi_display, window, cursor );
227 /* make the change take effect immediately */
228 XFlush( gdi_display );
231 /***********************************************************************
232 * sync_window_cursor
234 void sync_window_cursor( Window window )
236 HCURSOR cursor;
238 SERVER_START_REQ( set_cursor )
240 req->flags = 0;
241 wine_server_call( req );
242 cursor = reply->prev_count >= 0 ? wine_server_ptr_handle( reply->prev_handle ) : 0;
244 SERVER_END_REQ;
246 set_window_cursor( window, cursor );
249 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
250 /***********************************************************************
251 * update_relative_valuators
253 static void update_relative_valuators(XIAnyClassInfo **valuators, int n_valuators)
255 struct x11drv_thread_data *thread_data = x11drv_thread_data();
256 int i;
258 thread_data->x_rel_valuator.number = -1;
259 thread_data->y_rel_valuator.number = -1;
261 for (i = 0; i < n_valuators; i++)
263 XIValuatorClassInfo *class = (XIValuatorClassInfo *)valuators[i];
264 struct x11drv_valuator_data *valuator_data = NULL;
266 if (valuators[i]->type != XIValuatorClass) continue;
267 if (class->label == x11drv_atom( Rel_X ) ||
268 (!class->label && class->number == 0 && class->mode == XIModeRelative))
270 valuator_data = &thread_data->x_rel_valuator;
272 else if (class->label == x11drv_atom( Rel_Y ) ||
273 (!class->label && class->number == 1 && class->mode == XIModeRelative))
275 valuator_data = &thread_data->y_rel_valuator;
278 if (valuator_data) {
279 valuator_data->number = class->number;
280 valuator_data->min = class->min;
281 valuator_data->max = class->max;
285 #endif
288 /***********************************************************************
289 * enable_xinput2
291 static void enable_xinput2(void)
293 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
294 struct x11drv_thread_data *data = x11drv_thread_data();
295 XIEventMask mask;
296 XIDeviceInfo *pointer_info;
297 unsigned char mask_bits[XIMaskLen(XI_LASTEVENT)];
298 int count;
300 if (!xinput2_available) return;
302 if (data->xi2_state == xi_unknown)
304 int major = 2, minor = 0;
305 if (!pXIQueryVersion( data->display, &major, &minor )) data->xi2_state = xi_disabled;
306 else
308 data->xi2_state = xi_unavailable;
309 WARN( "X Input 2 not available\n" );
312 if (data->xi2_state == xi_unavailable) return;
313 if (!pXIGetClientPointer( data->display, None, &data->xi2_core_pointer )) return;
315 mask.mask = mask_bits;
316 mask.mask_len = sizeof(mask_bits);
317 mask.deviceid = XIAllDevices;
318 memset( mask_bits, 0, sizeof(mask_bits) );
319 XISetMask( mask_bits, XI_DeviceChanged );
320 XISetMask( mask_bits, XI_RawMotion );
321 XISetMask( mask_bits, XI_ButtonPress );
323 pXISelectEvents( data->display, DefaultRootWindow( data->display ), &mask, 1 );
325 pointer_info = pXIQueryDevice( data->display, data->xi2_core_pointer, &count );
326 update_relative_valuators( pointer_info->classes, pointer_info->num_classes );
327 pXIFreeDeviceInfo( pointer_info );
329 /* This device info list is only used to find the initial current slave if
330 * no XI_DeviceChanged events happened. If any hierarchy change occurred that
331 * might be relevant here (eg. user switching mice after (un)plugging), a
332 * XI_DeviceChanged event will point us to the right slave. So this list is
333 * safe to be obtained statically at enable_xinput2() time.
335 if (data->xi2_devices) pXIFreeDeviceInfo( data->xi2_devices );
336 data->xi2_devices = pXIQueryDevice( data->display, XIAllDevices, &data->xi2_device_count );
337 data->xi2_current_slave = 0;
339 data->xi2_state = xi_enabled;
340 #endif
343 /***********************************************************************
344 * disable_xinput2
346 static void disable_xinput2(void)
348 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
349 struct x11drv_thread_data *data = x11drv_thread_data();
350 XIEventMask mask;
352 if (data->xi2_state != xi_enabled) return;
354 TRACE( "disabling\n" );
355 data->xi2_state = xi_disabled;
357 mask.mask = NULL;
358 mask.mask_len = 0;
359 mask.deviceid = XIAllDevices;
361 pXISelectEvents( data->display, DefaultRootWindow( data->display ), &mask, 1 );
362 pXIFreeDeviceInfo( data->xi2_devices );
363 data->x_rel_valuator.number = -1;
364 data->y_rel_valuator.number = -1;
365 data->xi2_devices = NULL;
366 data->xi2_core_pointer = 0;
367 data->xi2_current_slave = 0;
368 #endif
372 /***********************************************************************
373 * grab_clipping_window
375 * Start a pointer grab on the clip window.
377 static BOOL grab_clipping_window( const RECT *clip )
379 static const WCHAR messageW[] = {'M','e','s','s','a','g','e',0};
380 struct x11drv_thread_data *data = x11drv_thread_data();
381 Window clip_window;
382 HWND msg_hwnd = 0;
383 POINT pos;
385 if (GetWindowThreadProcessId( GetDesktopWindow(), NULL ) == GetCurrentThreadId())
386 return TRUE; /* don't clip in the desktop process */
388 if (!data) return FALSE;
389 if (!(clip_window = init_clip_window())) return TRUE;
391 if (!(msg_hwnd = CreateWindowW( messageW, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0,
392 GetModuleHandleW(0), NULL )))
393 return TRUE;
395 /* enable XInput2 unless we are already clipping */
396 if (!data->clip_hwnd) enable_xinput2();
398 if (data->xi2_state != xi_enabled)
400 WARN( "XInput2 not supported, refusing to clip to %s\n", wine_dbgstr_rect(clip) );
401 DestroyWindow( msg_hwnd );
402 ClipCursor( NULL );
403 return TRUE;
406 TRACE( "clipping to %s win %lx\n", wine_dbgstr_rect(clip), clip_window );
408 if (!data->clip_hwnd) XUnmapWindow( data->display, clip_window );
409 pos = virtual_screen_to_root( clip->left, clip->top );
410 XMoveResizeWindow( data->display, clip_window, pos.x, pos.y,
411 max( 1, clip->right - clip->left ), max( 1, clip->bottom - clip->top ) );
412 XMapWindow( data->display, clip_window );
414 /* if the rectangle is shrinking we may get a pointer warp */
415 if (!data->clip_hwnd || clip->left > clip_rect.left || clip->top > clip_rect.top ||
416 clip->right < clip_rect.right || clip->bottom < clip_rect.bottom)
417 data->warp_serial = NextRequest( data->display );
419 if (!XGrabPointer( data->display, clip_window, False,
420 PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
421 GrabModeAsync, GrabModeAsync, clip_window, None, CurrentTime ))
422 clipping_cursor = TRUE;
424 if (!clipping_cursor)
426 disable_xinput2();
427 DestroyWindow( msg_hwnd );
428 return FALSE;
430 clip_rect = *clip;
431 if (!data->clip_hwnd) sync_window_cursor( clip_window );
432 InterlockedExchangePointer( (void **)&cursor_window, msg_hwnd );
433 data->clip_hwnd = msg_hwnd;
434 SendMessageW( GetDesktopWindow(), WM_X11DRV_CLIP_CURSOR, 0, (LPARAM)msg_hwnd );
435 return TRUE;
438 /***********************************************************************
439 * ungrab_clipping_window
441 * Release the pointer grab on the clip window.
443 void ungrab_clipping_window(void)
445 Display *display = thread_init_display();
446 Window clip_window = init_clip_window();
448 if (!clip_window) return;
450 TRACE( "no longer clipping\n" );
451 XUnmapWindow( display, clip_window );
452 clipping_cursor = FALSE;
453 SendMessageW( GetDesktopWindow(), WM_X11DRV_CLIP_CURSOR, 0, 0 );
456 /***********************************************************************
457 * reset_clipping_window
459 * Forcibly reset the window clipping on external events.
461 void reset_clipping_window(void)
463 ungrab_clipping_window();
464 ClipCursor( NULL ); /* make sure the clip rectangle is reset too */
467 BOOL CDECL X11DRV_ClipCursor( const RECT *clip );
469 /***********************************************************************
470 * clip_cursor_notify
472 * Notification function called upon receiving a WM_X11DRV_CLIP_CURSOR.
474 LRESULT clip_cursor_notify( HWND hwnd, HWND new_clip_hwnd )
476 struct x11drv_thread_data *data = x11drv_init_thread_data();
478 if (hwnd == GetDesktopWindow()) /* change the clip window stored in the desktop process */
480 static HWND clip_hwnd;
482 HWND prev = clip_hwnd;
483 clip_hwnd = new_clip_hwnd;
484 if (prev || new_clip_hwnd) TRACE( "clip hwnd changed from %p to %p\n", prev, new_clip_hwnd );
485 if (prev) SendNotifyMessageW( prev, WM_X11DRV_CLIP_CURSOR, 0, 0 );
487 else if (hwnd == data->clip_hwnd) /* this is a notification that clipping has been reset */
489 TRACE( "clip hwnd reset from %p\n", hwnd );
490 data->clip_hwnd = 0;
491 data->clip_reset = GetTickCount();
492 disable_xinput2();
493 DestroyWindow( hwnd );
495 else if (hwnd == GetForegroundWindow()) /* request to clip */
497 RECT clip;
499 GetClipCursor( &clip );
500 X11DRV_ClipCursor( &clip );
502 return 0;
505 /***********************************************************************
506 * clip_fullscreen_window
508 * Turn on clipping if the active window is fullscreen.
510 BOOL clip_fullscreen_window( HWND hwnd, BOOL reset )
512 struct x11drv_win_data *data;
513 struct x11drv_thread_data *thread_data;
514 RECT rect;
515 DWORD style;
516 BOOL fullscreen;
518 if (hwnd == GetDesktopWindow()) return FALSE;
519 style = GetWindowLongW( hwnd, GWL_STYLE );
520 if (!(style & WS_VISIBLE)) return FALSE;
521 if ((style & (WS_POPUP | WS_CHILD)) == WS_CHILD) return FALSE;
522 /* maximized windows don't count as full screen */
523 if ((style & WS_MAXIMIZE) && (style & WS_CAPTION) == WS_CAPTION) return FALSE;
524 if (!(data = get_win_data( hwnd ))) return FALSE;
525 fullscreen = is_window_rect_fullscreen( &data->whole_rect );
526 release_win_data( data );
527 if (!fullscreen) return FALSE;
528 if (!(thread_data = x11drv_thread_data())) return FALSE;
529 if (GetTickCount() - thread_data->clip_reset < 1000) return FALSE;
530 if (!reset && clipping_cursor && thread_data->clip_hwnd) return FALSE; /* already clipping */
531 rect = get_primary_monitor_rect();
532 if (!grab_fullscreen)
534 RECT virtual_rect = get_virtual_screen_rect();
535 if (!EqualRect( &rect, &virtual_rect )) return FALSE;
536 if (root_window != DefaultRootWindow( gdi_display )) return FALSE;
538 TRACE( "win %p clipping fullscreen\n", hwnd );
539 return grab_clipping_window( &rect );
543 /***********************************************************************
544 * is_old_motion_event
546 static BOOL is_old_motion_event( unsigned long serial )
548 struct x11drv_thread_data *thread_data = x11drv_thread_data();
550 if (!thread_data->warp_serial) return FALSE;
551 if ((long)(serial - thread_data->warp_serial) < 0) return TRUE;
552 thread_data->warp_serial = 0; /* we caught up now */
553 return FALSE;
557 /***********************************************************************
558 * send_mouse_input
560 * Update the various window states on a mouse event.
562 static void send_mouse_input( HWND hwnd, Window window, unsigned int state, INPUT *input )
564 struct x11drv_win_data *data;
565 POINT pt;
567 input->type = INPUT_MOUSE;
569 if (!hwnd)
571 struct x11drv_thread_data *thread_data = x11drv_thread_data();
572 HWND clip_hwnd = thread_data->clip_hwnd;
574 if (!clip_hwnd) return;
575 if (thread_data->clip_window != window) return;
576 if (InterlockedExchangePointer( (void **)&cursor_window, clip_hwnd ) != clip_hwnd ||
577 input->u.mi.time - last_cursor_change > 100)
579 sync_window_cursor( window );
580 last_cursor_change = input->u.mi.time;
582 input->u.mi.dx += clip_rect.left;
583 input->u.mi.dy += clip_rect.top;
584 __wine_send_input( hwnd, input );
585 return;
588 if (window != root_window)
590 pt.x = input->u.mi.dx;
591 pt.y = input->u.mi.dy;
593 else pt = root_to_virtual_screen( input->u.mi.dx, input->u.mi.dy );
595 if (!(data = get_win_data( hwnd ))) return;
597 if (window == data->whole_window)
599 pt.x += data->whole_rect.left - data->client_rect.left;
600 pt.y += data->whole_rect.top - data->client_rect.top;
603 if (GetWindowLongW( data->hwnd, GWL_EXSTYLE ) & WS_EX_LAYOUTRTL)
604 pt.x = data->client_rect.right - data->client_rect.left - 1 - pt.x;
605 MapWindowPoints( hwnd, 0, &pt, 1 );
607 if (InterlockedExchangePointer( (void **)&cursor_window, hwnd ) != hwnd ||
608 input->u.mi.time - last_cursor_change > 100)
610 sync_window_cursor( data->whole_window );
611 last_cursor_change = input->u.mi.time;
613 release_win_data( data );
615 if (hwnd != GetDesktopWindow())
617 hwnd = GetAncestor( hwnd, GA_ROOT );
618 if ((input->u.mi.dwFlags & (MOUSEEVENTF_LEFTDOWN|MOUSEEVENTF_RIGHTDOWN)) && hwnd == GetForegroundWindow())
619 clip_fullscreen_window( hwnd, FALSE );
622 /* update the wine server Z-order */
624 if (hwnd != x11drv_thread_data()->grab_hwnd &&
625 /* ignore event if a button is pressed, since the mouse is then grabbed too */
626 !(state & (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask|Button6Mask|Button7Mask)))
628 RECT rect;
629 SetRect( &rect, pt.x, pt.y, pt.x + 1, pt.y + 1 );
631 SERVER_START_REQ( update_window_zorder )
633 req->window = wine_server_user_handle( hwnd );
634 req->rect.left = rect.left;
635 req->rect.top = rect.top;
636 req->rect.right = rect.right;
637 req->rect.bottom = rect.bottom;
638 wine_server_call( req );
640 SERVER_END_REQ;
643 input->u.mi.dx = pt.x;
644 input->u.mi.dy = pt.y;
645 __wine_send_input( hwnd, input );
648 #ifdef SONAME_LIBXCURSOR
650 /***********************************************************************
651 * create_xcursor_frame
653 * Use Xcursor to create a frame of an X cursor from a Windows one.
655 static XcursorImage *create_xcursor_frame( HDC hdc, const ICONINFOEXW *iinfo, HANDLE icon,
656 HBITMAP hbmColor, unsigned char *color_bits, int color_size,
657 HBITMAP hbmMask, unsigned char *mask_bits, int mask_size,
658 int width, int height, int istep )
660 XcursorImage *image, *ret = NULL;
661 DWORD delay_jiffies, num_steps;
662 int x, y, i;
663 BOOL has_alpha = FALSE;
664 XcursorPixel *ptr;
666 image = pXcursorImageCreate( width, height );
667 if (!image)
669 ERR("X11 failed to produce a cursor frame!\n");
670 return NULL;
673 image->xhot = iinfo->xHotspot;
674 image->yhot = iinfo->yHotspot;
676 image->delay = 100; /* fallback delay, 100 ms */
677 if (GetCursorFrameInfo(icon, 0x0 /* unknown parameter */, istep, &delay_jiffies, &num_steps) != 0)
678 image->delay = (100 * delay_jiffies) / 6; /* convert jiffies (1/60s) to milliseconds */
679 else
680 WARN("Failed to retrieve animated cursor frame-rate for frame %d.\n", istep);
682 /* draw the cursor frame to a temporary buffer then copy it into the XcursorImage */
683 memset( color_bits, 0x00, color_size );
684 SelectObject( hdc, hbmColor );
685 if (!DrawIconEx( hdc, 0, 0, icon, width, height, istep, NULL, DI_NORMAL ))
687 TRACE("Could not draw frame %d (walk past end of frames).\n", istep);
688 goto cleanup;
690 memcpy( image->pixels, color_bits, color_size );
692 /* check if the cursor frame was drawn with an alpha channel */
693 for (i = 0, ptr = image->pixels; i < width * height; i++, ptr++)
694 if ((has_alpha = (*ptr & 0xff000000) != 0)) break;
696 /* if no alpha channel was drawn then generate it from the mask */
697 if (!has_alpha)
699 unsigned int width_bytes = (width + 31) / 32 * 4;
701 /* draw the cursor mask to a temporary buffer */
702 memset( mask_bits, 0xFF, mask_size );
703 SelectObject( hdc, hbmMask );
704 if (!DrawIconEx( hdc, 0, 0, icon, width, height, istep, NULL, DI_MASK ))
706 ERR("Failed to draw frame mask %d.\n", istep);
707 goto cleanup;
709 /* use the buffer to directly modify the XcursorImage alpha channel */
710 for (y = 0, ptr = image->pixels; y < height; y++)
711 for (x = 0; x < width; x++, ptr++)
712 if (!((mask_bits[y * width_bytes + x / 8] << (x % 8)) & 0x80))
713 *ptr |= 0xff000000;
715 ret = image;
717 cleanup:
718 if (ret == NULL) pXcursorImageDestroy( image );
719 return ret;
722 /***********************************************************************
723 * create_xcursor_cursor
725 * Use Xcursor to create an X cursor from a Windows one.
727 static Cursor create_xcursor_cursor( HDC hdc, const ICONINFOEXW *iinfo, HANDLE icon, int width, int height )
729 unsigned char *color_bits, *mask_bits;
730 HBITMAP hbmColor = 0, hbmMask = 0;
731 DWORD nFrames, delay_jiffies, i;
732 int color_size, mask_size;
733 BITMAPINFO *info = NULL;
734 XcursorImages *images;
735 XcursorImage **imgs;
736 Cursor cursor = 0;
738 /* Retrieve the number of frames to render */
739 if (!GetCursorFrameInfo(icon, 0x0 /* unknown parameter */, 0, &delay_jiffies, &nFrames)) return 0;
740 if (!(imgs = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(XcursorImage*)*nFrames ))) return 0;
742 /* Allocate all of the resources necessary to obtain a cursor frame */
743 if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto cleanup;
744 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
745 info->bmiHeader.biWidth = width;
746 info->bmiHeader.biHeight = -height;
747 info->bmiHeader.biPlanes = 1;
748 info->bmiHeader.biCompression = BI_RGB;
749 info->bmiHeader.biXPelsPerMeter = 0;
750 info->bmiHeader.biYPelsPerMeter = 0;
751 info->bmiHeader.biClrUsed = 0;
752 info->bmiHeader.biClrImportant = 0;
753 info->bmiHeader.biBitCount = 32;
754 color_size = width * height * 4;
755 info->bmiHeader.biSizeImage = color_size;
756 hbmColor = CreateDIBSection( hdc, info, DIB_RGB_COLORS, (VOID **) &color_bits, NULL, 0);
757 if (!hbmColor)
759 ERR("Failed to create DIB section for cursor color data!\n");
760 goto cleanup;
762 info->bmiHeader.biBitCount = 1;
763 info->bmiColors[0].rgbRed = 0;
764 info->bmiColors[0].rgbGreen = 0;
765 info->bmiColors[0].rgbBlue = 0;
766 info->bmiColors[0].rgbReserved = 0;
767 info->bmiColors[1].rgbRed = 0xff;
768 info->bmiColors[1].rgbGreen = 0xff;
769 info->bmiColors[1].rgbBlue = 0xff;
770 info->bmiColors[1].rgbReserved = 0;
772 mask_size = ((width + 31) / 32 * 4) * height; /* width_bytes * height */
773 info->bmiHeader.biSizeImage = mask_size;
774 hbmMask = CreateDIBSection( hdc, info, DIB_RGB_COLORS, (VOID **) &mask_bits, NULL, 0);
775 if (!hbmMask)
777 ERR("Failed to create DIB section for cursor mask data!\n");
778 goto cleanup;
781 /* Create an XcursorImage for each frame of the cursor */
782 for (i=0; i<nFrames; i++)
784 imgs[i] = create_xcursor_frame( hdc, iinfo, icon,
785 hbmColor, color_bits, color_size,
786 hbmMask, mask_bits, mask_size,
787 width, height, i );
788 if (!imgs[i]) goto cleanup;
791 /* Build an X cursor out of all of the frames */
792 if (!(images = pXcursorImagesCreate( nFrames ))) goto cleanup;
793 for (images->nimage = 0; images->nimage < nFrames; images->nimage++)
794 images->images[images->nimage] = imgs[images->nimage];
795 cursor = pXcursorImagesLoadCursor( gdi_display, images );
796 pXcursorImagesDestroy( images ); /* Note: this frees each individual frame (calls XcursorImageDestroy) */
797 HeapFree( GetProcessHeap(), 0, imgs );
798 imgs = NULL;
800 cleanup:
801 if (imgs)
803 /* Failed to produce a cursor, free previously allocated frames */
804 for (i=0; i<nFrames && imgs[i]; i++)
805 pXcursorImageDestroy( imgs[i] );
806 HeapFree( GetProcessHeap(), 0, imgs );
808 /* Cleanup all of the resources used to obtain the frame data */
809 if (hbmColor) DeleteObject( hbmColor );
810 if (hbmMask) DeleteObject( hbmMask );
811 HeapFree( GetProcessHeap(), 0, info );
812 return cursor;
815 #endif /* SONAME_LIBXCURSOR */
818 struct system_cursors
820 WORD id;
821 const char *names[8];
824 static const struct system_cursors user32_cursors[] =
826 { OCR_NORMAL, { "left_ptr" }},
827 { OCR_IBEAM, { "xterm", "text" }},
828 { OCR_WAIT, { "watch", "wait" }},
829 { OCR_CROSS, { "cross" }},
830 { OCR_UP, { "center_ptr" }},
831 { OCR_SIZE, { "fleur", "size_all" }},
832 { OCR_SIZEALL, { "fleur", "size_all" }},
833 { OCR_ICON, { "icon" }},
834 { OCR_SIZENWSE, { "top_left_corner", "nw-resize" }},
835 { OCR_SIZENESW, { "top_right_corner", "ne-resize" }},
836 { OCR_SIZEWE, { "h_double_arrow", "size_hor", "ew-resize" }},
837 { OCR_SIZENS, { "v_double_arrow", "size_ver", "ns-resize" }},
838 { OCR_NO, { "not-allowed", "forbidden", "no-drop" }},
839 { OCR_HAND, { "hand2", "pointer", "pointing-hand" }},
840 { OCR_APPSTARTING, { "left_ptr_watch" }},
841 { OCR_HELP, { "question_arrow", "help" }},
842 { 0 }
845 static const struct system_cursors comctl32_cursors[] =
847 { 102, { "move", "dnd-move" }},
848 { 104, { "copy", "dnd-copy" }},
849 { 105, { "left_ptr" }},
850 { 106, { "col-resize", "split_v" }},
851 { 107, { "col-resize", "split_v" }},
852 { 108, { "hand2", "pointer", "pointing-hand" }},
853 { 135, { "row-resize", "split_h" }},
854 { 0 }
857 static const struct system_cursors ole32_cursors[] =
859 { 1, { "no-drop", "dnd-no-drop" }},
860 { 2, { "move", "dnd-move" }},
861 { 3, { "copy", "dnd-copy" }},
862 { 4, { "alias", "dnd-link" }},
863 { 0 }
866 static const struct system_cursors riched20_cursors[] =
868 { 105, { "hand2", "pointer", "pointing-hand" }},
869 { 107, { "right_ptr" }},
870 { 109, { "copy", "dnd-copy" }},
871 { 110, { "move", "dnd-move" }},
872 { 111, { "no-drop", "dnd-no-drop" }},
873 { 0 }
876 static const struct
878 const struct system_cursors *cursors;
879 WCHAR name[16];
880 } module_cursors[] =
882 { user32_cursors, {'u','s','e','r','3','2','.','d','l','l',0} },
883 { comctl32_cursors, {'c','o','m','c','t','l','3','2','.','d','l','l',0} },
884 { ole32_cursors, {'o','l','e','3','2','.','d','l','l',0} },
885 { riched20_cursors, {'r','i','c','h','e','d','2','0','.','d','l','l',0} }
888 struct cursor_font_fallback
890 const char *name;
891 unsigned int shape;
894 static const struct cursor_font_fallback fallbacks[] =
896 { "X_cursor", XC_X_cursor },
897 { "arrow", XC_arrow },
898 { "based_arrow_down", XC_based_arrow_down },
899 { "based_arrow_up", XC_based_arrow_up },
900 { "boat", XC_boat },
901 { "bogosity", XC_bogosity },
902 { "bottom_left_corner", XC_bottom_left_corner },
903 { "bottom_right_corner", XC_bottom_right_corner },
904 { "bottom_side", XC_bottom_side },
905 { "bottom_tee", XC_bottom_tee },
906 { "box_spiral", XC_box_spiral },
907 { "center_ptr", XC_center_ptr },
908 { "circle", XC_circle },
909 { "clock", XC_clock },
910 { "coffee_mug", XC_coffee_mug },
911 { "col-resize", XC_sb_h_double_arrow },
912 { "cross", XC_cross },
913 { "cross_reverse", XC_cross_reverse },
914 { "crosshair", XC_crosshair },
915 { "diamond_cross", XC_diamond_cross },
916 { "dot", XC_dot },
917 { "dotbox", XC_dotbox },
918 { "double_arrow", XC_double_arrow },
919 { "draft_large", XC_draft_large },
920 { "draft_small", XC_draft_small },
921 { "draped_box", XC_draped_box },
922 { "exchange", XC_exchange },
923 { "fleur", XC_fleur },
924 { "gobbler", XC_gobbler },
925 { "gumby", XC_gumby },
926 { "h_double_arrow", XC_sb_h_double_arrow },
927 { "hand1", XC_hand1 },
928 { "hand2", XC_hand2 },
929 { "heart", XC_heart },
930 { "icon", XC_icon },
931 { "iron_cross", XC_iron_cross },
932 { "left_ptr", XC_left_ptr },
933 { "left_side", XC_left_side },
934 { "left_tee", XC_left_tee },
935 { "leftbutton", XC_leftbutton },
936 { "ll_angle", XC_ll_angle },
937 { "lr_angle", XC_lr_angle },
938 { "man", XC_man },
939 { "middlebutton", XC_middlebutton },
940 { "mouse", XC_mouse },
941 { "pencil", XC_pencil },
942 { "pirate", XC_pirate },
943 { "plus", XC_plus },
944 { "question_arrow", XC_question_arrow },
945 { "right_ptr", XC_right_ptr },
946 { "right_side", XC_right_side },
947 { "right_tee", XC_right_tee },
948 { "rightbutton", XC_rightbutton },
949 { "row-resize", XC_sb_v_double_arrow },
950 { "rtl_logo", XC_rtl_logo },
951 { "sailboat", XC_sailboat },
952 { "sb_down_arrow", XC_sb_down_arrow },
953 { "sb_h_double_arrow", XC_sb_h_double_arrow },
954 { "sb_left_arrow", XC_sb_left_arrow },
955 { "sb_right_arrow", XC_sb_right_arrow },
956 { "sb_up_arrow", XC_sb_up_arrow },
957 { "sb_v_double_arrow", XC_sb_v_double_arrow },
958 { "shuttle", XC_shuttle },
959 { "sizing", XC_sizing },
960 { "spider", XC_spider },
961 { "spraycan", XC_spraycan },
962 { "star", XC_star },
963 { "target", XC_target },
964 { "tcross", XC_tcross },
965 { "top_left_arrow", XC_top_left_arrow },
966 { "top_left_corner", XC_top_left_corner },
967 { "top_right_corner", XC_top_right_corner },
968 { "top_side", XC_top_side },
969 { "top_tee", XC_top_tee },
970 { "trek", XC_trek },
971 { "ul_angle", XC_ul_angle },
972 { "umbrella", XC_umbrella },
973 { "ur_angle", XC_ur_angle },
974 { "v_double_arrow", XC_sb_v_double_arrow },
975 { "watch", XC_watch },
976 { "xterm", XC_xterm }
979 static int fallback_cmp( const void *key, const void *member )
981 const struct cursor_font_fallback *fallback = member;
982 return strcmp( key, fallback->name );
985 static int find_fallback_shape( const char *name )
987 struct cursor_font_fallback *fallback;
989 if ((fallback = bsearch( name, fallbacks, ARRAY_SIZE( fallbacks ),
990 sizeof(*fallback), fallback_cmp )))
991 return fallback->shape;
992 return -1;
995 /***********************************************************************
996 * create_xcursor_system_cursor
998 * Create an X cursor for a system cursor.
1000 static Cursor create_xcursor_system_cursor( const ICONINFOEXW *info )
1002 static const WCHAR idW[] = {'%','h','u',0};
1003 const struct system_cursors *cursors;
1004 unsigned int i;
1005 Cursor cursor = 0;
1006 HMODULE module;
1007 HKEY key;
1008 const char * const *names = NULL;
1009 WCHAR *p, name[MAX_PATH * 2], valueW[64];
1010 char valueA[64];
1011 DWORD ret;
1013 if (!info->szModName[0]) return 0;
1015 p = strrchrW( info->szModName, '\\' );
1016 strcpyW( name, p ? p + 1 : info->szModName );
1017 p = name + strlenW( name );
1018 *p++ = ',';
1019 if (info->szResName[0]) strcpyW( p, info->szResName );
1020 else sprintfW( p, idW, info->wResID );
1021 valueA[0] = 0;
1023 /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver\Cursors */
1024 if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\X11 Driver\\Cursors", &key ))
1026 DWORD size = sizeof(valueW);
1027 ret = RegQueryValueExW( key, name, NULL, NULL, (BYTE *)valueW, &size );
1028 RegCloseKey( key );
1029 if (!ret)
1031 if (!valueW[0]) return 0; /* force standard cursor */
1032 if (!WideCharToMultiByte( CP_UNIXCP, 0, valueW, -1, valueA, sizeof(valueA), NULL, NULL ))
1033 valueA[0] = 0;
1034 goto done;
1038 if (info->szResName[0]) goto done; /* only integer resources are supported here */
1039 if (!(module = GetModuleHandleW( info->szModName ))) goto done;
1041 for (i = 0; i < ARRAY_SIZE( module_cursors ); i++)
1042 if (GetModuleHandleW( module_cursors[i].name ) == module) break;
1043 if (i == ARRAY_SIZE( module_cursors )) goto done;
1045 cursors = module_cursors[i].cursors;
1046 for (i = 0; cursors[i].id; i++)
1047 if (cursors[i].id == info->wResID)
1049 strcpy( valueA, cursors[i].names[0] );
1050 names = cursors[i].names;
1051 break;
1054 done:
1055 if (valueA[0])
1057 #ifdef SONAME_LIBXCURSOR
1058 if (pXcursorLibraryLoadCursor)
1060 if (!names)
1061 cursor = pXcursorLibraryLoadCursor( gdi_display, valueA );
1062 else
1063 while (*names && !cursor) cursor = pXcursorLibraryLoadCursor( gdi_display, *names++ );
1065 #endif
1066 if (!cursor)
1068 int shape = find_fallback_shape( valueA );
1069 if (shape != -1) cursor = XCreateFontCursor( gdi_display, shape );
1071 if (!cursor) WARN( "no system cursor found for %s mapped to %s\n",
1072 debugstr_w(name), debugstr_a(valueA) );
1074 else WARN( "no system cursor found for %s\n", debugstr_w(name) );
1075 return cursor;
1079 /***********************************************************************
1080 * create_xlib_monochrome_cursor
1082 * Create a monochrome X cursor from a Windows one.
1084 static Cursor create_xlib_monochrome_cursor( HDC hdc, const ICONINFOEXW *icon, int width, int height )
1086 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1087 BITMAPINFO *info = (BITMAPINFO *)buffer;
1088 const int and_y = 0;
1089 const int xor_y = height;
1090 unsigned int width_bytes = (width + 31) / 32 * 4;
1091 unsigned char *mask_bits = NULL;
1092 GC gc;
1093 XColor fg, bg;
1094 XVisualInfo vis = default_visual;
1095 Pixmap src_pixmap, bits_pixmap, mask_pixmap;
1096 struct gdi_image_bits bits;
1097 Cursor cursor = 0;
1099 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1100 info->bmiHeader.biWidth = width;
1101 info->bmiHeader.biHeight = -height * 2;
1102 info->bmiHeader.biPlanes = 1;
1103 info->bmiHeader.biBitCount = 1;
1104 info->bmiHeader.biCompression = BI_RGB;
1105 info->bmiHeader.biSizeImage = width_bytes * height * 2;
1106 info->bmiHeader.biXPelsPerMeter = 0;
1107 info->bmiHeader.biYPelsPerMeter = 0;
1108 info->bmiHeader.biClrUsed = 0;
1109 info->bmiHeader.biClrImportant = 0;
1111 if (!(mask_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
1112 if (!GetDIBits( hdc, icon->hbmMask, 0, height * 2, mask_bits, info, DIB_RGB_COLORS )) goto done;
1114 vis.depth = 1;
1115 bits.ptr = mask_bits;
1116 bits.free = NULL;
1117 bits.is_copy = TRUE;
1118 if (!(src_pixmap = create_pixmap_from_image( hdc, &vis, info, &bits, DIB_RGB_COLORS ))) goto done;
1120 bits_pixmap = XCreatePixmap( gdi_display, root_window, width, height, 1 );
1121 mask_pixmap = XCreatePixmap( gdi_display, root_window, width, height, 1 );
1122 gc = XCreateGC( gdi_display, src_pixmap, 0, NULL );
1123 XSetGraphicsExposures( gdi_display, gc, False );
1125 /* We have to do some magic here, as cursors are not fully
1126 * compatible between Windows and X11. Under X11, there are
1127 * only 3 possible color cursor: black, white and masked. So
1128 * we map the 4th Windows color (invert the bits on the screen)
1129 * to black and an additional white bit on another place
1130 * (+1,+1). This require some boolean arithmetic:
1132 * Windows | X11
1133 * And Xor Result | Bits Mask Result
1134 * 0 0 black | 0 1 background
1135 * 0 1 white | 1 1 foreground
1136 * 1 0 no change | X 0 no change
1137 * 1 1 inverted | 0 1 background
1139 * which gives:
1140 * Bits = not 'And' and 'Xor' or 'And2' and 'Xor2'
1141 * Mask = not 'And' or 'Xor' or 'And2' and 'Xor2'
1143 XSetFunction( gdi_display, gc, GXcopy );
1144 XCopyArea( gdi_display, src_pixmap, bits_pixmap, gc, 0, and_y, width, height, 0, 0 );
1145 XCopyArea( gdi_display, src_pixmap, mask_pixmap, gc, 0, and_y, width, height, 0, 0 );
1146 XSetFunction( gdi_display, gc, GXandReverse );
1147 XCopyArea( gdi_display, src_pixmap, bits_pixmap, gc, 0, xor_y, width, height, 0, 0 );
1148 XSetFunction( gdi_display, gc, GXorReverse );
1149 XCopyArea( gdi_display, src_pixmap, mask_pixmap, gc, 0, xor_y, width, height, 0, 0 );
1150 /* additional white */
1151 XSetFunction( gdi_display, gc, GXand );
1152 XCopyArea( gdi_display, src_pixmap, src_pixmap, gc, 0, xor_y, width, height, 0, and_y );
1153 XSetFunction( gdi_display, gc, GXor );
1154 XCopyArea( gdi_display, src_pixmap, mask_pixmap, gc, 0, and_y, width, height, 1, 1 );
1155 XCopyArea( gdi_display, src_pixmap, bits_pixmap, gc, 0, and_y, width, height, 1, 1 );
1156 XFreeGC( gdi_display, gc );
1158 fg.red = fg.green = fg.blue = 0xffff;
1159 bg.red = bg.green = bg.blue = 0;
1160 cursor = XCreatePixmapCursor( gdi_display, bits_pixmap, mask_pixmap,
1161 &fg, &bg, icon->xHotspot, icon->yHotspot );
1162 XFreePixmap( gdi_display, src_pixmap );
1163 XFreePixmap( gdi_display, bits_pixmap );
1164 XFreePixmap( gdi_display, mask_pixmap );
1166 done:
1167 HeapFree( GetProcessHeap(), 0, mask_bits );
1168 return cursor;
1171 /***********************************************************************
1172 * create_xlib_load_mono_cursor
1174 * Create a monochrome X cursor from a color Windows one by trying to load the monochrome resource.
1176 static Cursor create_xlib_load_mono_cursor( HDC hdc, HANDLE handle, int width, int height )
1178 Cursor cursor = None;
1179 HANDLE mono;
1180 ICONINFOEXW info;
1181 BITMAP bm;
1183 if (!(mono = CopyImage( handle, IMAGE_CURSOR, width, height, LR_MONOCHROME | LR_COPYFROMRESOURCE )))
1184 return None;
1186 info.cbSize = sizeof(info);
1187 if (GetIconInfoExW( mono, &info ))
1189 if (!info.hbmColor)
1191 GetObjectW( info.hbmMask, sizeof(bm), &bm );
1192 bm.bmHeight = max( 1, bm.bmHeight / 2 );
1193 /* make sure hotspot is valid */
1194 if (info.xHotspot >= bm.bmWidth || info.yHotspot >= bm.bmHeight)
1196 info.xHotspot = bm.bmWidth / 2;
1197 info.yHotspot = bm.bmHeight / 2;
1199 cursor = create_xlib_monochrome_cursor( hdc, &info, bm.bmWidth, bm.bmHeight );
1201 else DeleteObject( info.hbmColor );
1202 DeleteObject( info.hbmMask );
1204 DestroyCursor( mono );
1205 return cursor;
1208 /***********************************************************************
1209 * create_xlib_color_cursor
1211 * Create a color X cursor from a Windows one.
1213 static Cursor create_xlib_color_cursor( HDC hdc, const ICONINFOEXW *icon, int width, int height )
1215 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1216 BITMAPINFO *info = (BITMAPINFO *)buffer;
1217 XColor fg, bg;
1218 Cursor cursor = None;
1219 XVisualInfo vis = default_visual;
1220 Pixmap xor_pixmap, mask_pixmap;
1221 struct gdi_image_bits bits;
1222 unsigned int *color_bits = NULL, *ptr;
1223 unsigned char *mask_bits = NULL, *xor_bits = NULL;
1224 int i, x, y;
1225 BOOL has_alpha = FALSE;
1226 int rfg, gfg, bfg, rbg, gbg, bbg, fgBits, bgBits;
1227 unsigned int width_bytes = (width + 31) / 32 * 4;
1229 info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1230 info->bmiHeader.biWidth = width;
1231 info->bmiHeader.biHeight = -height;
1232 info->bmiHeader.biPlanes = 1;
1233 info->bmiHeader.biBitCount = 1;
1234 info->bmiHeader.biCompression = BI_RGB;
1235 info->bmiHeader.biSizeImage = width_bytes * height;
1236 info->bmiHeader.biXPelsPerMeter = 0;
1237 info->bmiHeader.biYPelsPerMeter = 0;
1238 info->bmiHeader.biClrUsed = 0;
1239 info->bmiHeader.biClrImportant = 0;
1241 if (!(mask_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
1242 if (!GetDIBits( hdc, icon->hbmMask, 0, height, mask_bits, info, DIB_RGB_COLORS )) goto done;
1244 info->bmiHeader.biBitCount = 32;
1245 info->bmiHeader.biSizeImage = width * height * 4;
1246 if (!(color_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
1247 if (!(xor_bits = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, width_bytes * height ))) goto done;
1248 GetDIBits( hdc, icon->hbmColor, 0, height, color_bits, info, DIB_RGB_COLORS );
1250 /* compute fg/bg color and xor bitmap based on average of the color values */
1252 rfg = gfg = bfg = rbg = gbg = bbg = fgBits = 0;
1253 for (y = 0, ptr = color_bits; y < height; y++)
1255 for (x = 0; x < width; x++, ptr++)
1257 int red = (*ptr >> 16) & 0xff;
1258 int green = (*ptr >> 8) & 0xff;
1259 int blue = (*ptr >> 0) & 0xff;
1260 if (red + green + blue > 0x40)
1262 rfg += red;
1263 gfg += green;
1264 bfg += blue;
1265 fgBits++;
1266 xor_bits[y * width_bytes + x / 8] |= 0x80 >> (x % 8);
1268 else
1270 rbg += red;
1271 gbg += green;
1272 bbg += blue;
1276 if (fgBits)
1278 fg.red = rfg * 257 / fgBits;
1279 fg.green = gfg * 257 / fgBits;
1280 fg.blue = bfg * 257 / fgBits;
1282 else fg.red = fg.green = fg.blue = 0;
1283 bgBits = width * height - fgBits;
1284 if (bgBits)
1286 bg.red = rbg * 257 / bgBits;
1287 bg.green = gbg * 257 / bgBits;
1288 bg.blue = bbg * 257 / bgBits;
1290 else bg.red = bg.green = bg.blue = 0;
1292 info->bmiHeader.biBitCount = 1;
1293 info->bmiHeader.biClrUsed = 0;
1294 info->bmiHeader.biSizeImage = width_bytes * height;
1296 /* generate mask from the alpha channel if we have one */
1298 for (i = 0, ptr = color_bits; i < width * height; i++, ptr++)
1299 if ((has_alpha = (*ptr & 0xff000000) != 0)) break;
1301 if (has_alpha)
1303 memset( mask_bits, 0, width_bytes * height );
1304 for (y = 0, ptr = color_bits; y < height; y++)
1305 for (x = 0; x < width; x++, ptr++)
1306 if ((*ptr >> 24) > 25) /* more than 10% alpha */
1307 mask_bits[y * width_bytes + x / 8] |= 0x80 >> (x % 8);
1309 else /* invert the mask */
1311 unsigned int j;
1313 ptr = (unsigned int *)mask_bits;
1314 for (j = 0; j < info->bmiHeader.biSizeImage / sizeof(*ptr); j++, ptr++) *ptr ^= ~0u;
1317 vis.depth = 1;
1318 bits.ptr = xor_bits;
1319 bits.free = NULL;
1320 bits.is_copy = TRUE;
1321 if (!(xor_pixmap = create_pixmap_from_image( hdc, &vis, info, &bits, DIB_RGB_COLORS ))) goto done;
1323 bits.ptr = mask_bits;
1324 mask_pixmap = create_pixmap_from_image( hdc, &vis, info, &bits, DIB_RGB_COLORS );
1326 if (mask_pixmap)
1328 cursor = XCreatePixmapCursor( gdi_display, xor_pixmap, mask_pixmap,
1329 &fg, &bg, icon->xHotspot, icon->yHotspot );
1330 XFreePixmap( gdi_display, mask_pixmap );
1332 XFreePixmap( gdi_display, xor_pixmap );
1334 done:
1335 HeapFree( GetProcessHeap(), 0, color_bits );
1336 HeapFree( GetProcessHeap(), 0, xor_bits );
1337 HeapFree( GetProcessHeap(), 0, mask_bits );
1338 return cursor;
1341 /***********************************************************************
1342 * create_cursor
1344 * Create an X cursor from a Windows one.
1346 static Cursor create_cursor( HANDLE handle )
1348 Cursor cursor = 0;
1349 ICONINFOEXW info;
1350 BITMAP bm;
1351 HDC hdc;
1353 if (!handle) return get_empty_cursor();
1355 info.cbSize = sizeof(info);
1356 if (!GetIconInfoExW( handle, &info )) return 0;
1358 if (use_system_cursors && (cursor = create_xcursor_system_cursor( &info )))
1360 DeleteObject( info.hbmColor );
1361 DeleteObject( info.hbmMask );
1362 return cursor;
1365 GetObjectW( info.hbmMask, sizeof(bm), &bm );
1366 if (!info.hbmColor) bm.bmHeight = max( 1, bm.bmHeight / 2 );
1368 /* make sure hotspot is valid */
1369 if (info.xHotspot >= bm.bmWidth || info.yHotspot >= bm.bmHeight)
1371 info.xHotspot = bm.bmWidth / 2;
1372 info.yHotspot = bm.bmHeight / 2;
1375 hdc = CreateCompatibleDC( 0 );
1377 if (info.hbmColor)
1379 #ifdef SONAME_LIBXCURSOR
1380 if (pXcursorImagesLoadCursor)
1381 cursor = create_xcursor_cursor( hdc, &info, handle, bm.bmWidth, bm.bmHeight );
1382 #endif
1383 if (!cursor) cursor = create_xlib_load_mono_cursor( hdc, handle, bm.bmWidth, bm.bmHeight );
1384 if (!cursor) cursor = create_xlib_color_cursor( hdc, &info, bm.bmWidth, bm.bmHeight );
1385 DeleteObject( info.hbmColor );
1387 else
1389 cursor = create_xlib_monochrome_cursor( hdc, &info, bm.bmWidth, bm.bmHeight );
1392 DeleteObject( info.hbmMask );
1393 DeleteDC( hdc );
1394 return cursor;
1397 /***********************************************************************
1398 * DestroyCursorIcon (X11DRV.@)
1400 void CDECL X11DRV_DestroyCursorIcon( HCURSOR handle )
1402 Cursor cursor;
1404 if (!XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&cursor ))
1406 TRACE( "%p xid %lx\n", handle, cursor );
1407 XFreeCursor( gdi_display, cursor );
1408 XDeleteContext( gdi_display, (XID)handle, cursor_context );
1412 /***********************************************************************
1413 * SetCursor (X11DRV.@)
1415 void CDECL X11DRV_SetCursor( HCURSOR handle )
1417 if (InterlockedExchangePointer( (void **)&last_cursor, handle ) != handle ||
1418 GetTickCount() - last_cursor_change > 100)
1420 last_cursor_change = GetTickCount();
1421 if (cursor_window) SendNotifyMessageW( cursor_window, WM_X11DRV_SET_CURSOR, 0, (LPARAM)handle );
1425 /***********************************************************************
1426 * SetCursorPos (X11DRV.@)
1428 BOOL CDECL X11DRV_SetCursorPos( INT x, INT y )
1430 struct x11drv_thread_data *data = x11drv_init_thread_data();
1431 POINT pos = virtual_screen_to_root( x, y );
1433 XWarpPointer( data->display, root_window, root_window, 0, 0, 0, 0, pos.x, pos.y );
1434 data->warp_serial = NextRequest( data->display );
1435 XNoOp( data->display );
1436 XFlush( data->display ); /* avoids bad mouse lag in games that do their own mouse warping */
1437 TRACE( "warped to %d,%d serial %lu\n", x, y, data->warp_serial );
1438 return TRUE;
1441 /***********************************************************************
1442 * GetCursorPos (X11DRV.@)
1444 BOOL CDECL X11DRV_GetCursorPos(LPPOINT pos)
1446 Display *display = thread_init_display();
1447 Window root, child;
1448 int rootX, rootY, winX, winY;
1449 unsigned int xstate;
1450 BOOL ret;
1452 ret = XQueryPointer( display, root_window, &root, &child, &rootX, &rootY, &winX, &winY, &xstate );
1453 if (ret)
1455 POINT old = *pos;
1456 *pos = root_to_virtual_screen( winX, winY );
1457 TRACE( "pointer at %s server pos %s\n", wine_dbgstr_point(pos), wine_dbgstr_point(&old) );
1459 return ret;
1462 /***********************************************************************
1463 * ClipCursor (X11DRV.@)
1465 BOOL CDECL X11DRV_ClipCursor( LPCRECT clip )
1467 RECT virtual_rect = get_virtual_screen_rect();
1469 if (!clip) clip = &virtual_rect;
1471 if (grab_pointer)
1473 HWND foreground = GetForegroundWindow();
1474 DWORD tid, pid;
1476 /* forward request to the foreground window if it's in a different thread */
1477 tid = GetWindowThreadProcessId( foreground, &pid );
1478 if (tid && tid != GetCurrentThreadId() && pid == GetCurrentProcessId())
1480 TRACE( "forwarding clip request to %p\n", foreground );
1481 SendNotifyMessageW( foreground, WM_X11DRV_CLIP_CURSOR, 0, 0 );
1482 return TRUE;
1485 /* we are clipping if the clip rectangle is smaller than the screen */
1486 if (clip->left > virtual_rect.left || clip->right < virtual_rect.right ||
1487 clip->top > virtual_rect.top || clip->bottom < virtual_rect.bottom)
1489 if (grab_clipping_window( clip )) return TRUE;
1491 else /* if currently clipping, check if we should switch to fullscreen clipping */
1493 struct x11drv_thread_data *data = x11drv_thread_data();
1494 if (data && data->clip_hwnd)
1496 if (EqualRect( clip, &clip_rect ) || clip_fullscreen_window( foreground, TRUE ))
1497 return TRUE;
1501 ungrab_clipping_window();
1502 return TRUE;
1505 /***********************************************************************
1506 * move_resize_window
1508 void move_resize_window( HWND hwnd, int dir )
1510 Display *display = thread_display();
1511 DWORD pt;
1512 POINT pos;
1513 int button = 0;
1514 XEvent xev;
1515 Window win, root, child;
1516 unsigned int xstate;
1518 if (!(win = X11DRV_get_whole_window( hwnd ))) return;
1520 pt = GetMessagePos();
1521 pos = virtual_screen_to_root( (short)LOWORD( pt ), (short)HIWORD( pt ) );
1523 if (GetKeyState( VK_LBUTTON ) & 0x8000) button = 1;
1524 else if (GetKeyState( VK_MBUTTON ) & 0x8000) button = 2;
1525 else if (GetKeyState( VK_RBUTTON ) & 0x8000) button = 3;
1527 TRACE( "hwnd %p/%lx, pos %s, dir %d, button %d\n", hwnd, win, wine_dbgstr_point(&pos), dir, button );
1529 xev.xclient.type = ClientMessage;
1530 xev.xclient.window = win;
1531 xev.xclient.message_type = x11drv_atom(_NET_WM_MOVERESIZE);
1532 xev.xclient.serial = 0;
1533 xev.xclient.display = display;
1534 xev.xclient.send_event = True;
1535 xev.xclient.format = 32;
1536 xev.xclient.data.l[0] = pos.x; /* x coord */
1537 xev.xclient.data.l[1] = pos.y; /* y coord */
1538 xev.xclient.data.l[2] = dir; /* direction */
1539 xev.xclient.data.l[3] = button; /* button */
1540 xev.xclient.data.l[4] = 0; /* unused */
1542 /* need to ungrab the pointer that may have been automatically grabbed
1543 * with a ButtonPress event */
1544 XUngrabPointer( display, CurrentTime );
1545 XSendEvent(display, root_window, False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
1547 /* try to detect the end of the size/move by polling for the mouse button to be released */
1548 /* (some apps don't like it if we return before the size/move is done) */
1550 if (!button) return;
1551 SendMessageW( hwnd, WM_ENTERSIZEMOVE, 0, 0 );
1553 for (;;)
1555 MSG msg;
1556 INPUT input;
1557 int x, y, rootX, rootY;
1559 if (!XQueryPointer( display, root_window, &root, &child, &rootX, &rootY, &x, &y, &xstate )) break;
1561 if (!(xstate & (Button1Mask << (button - 1))))
1563 /* fake a button release event */
1564 pos = root_to_virtual_screen( x, y );
1565 input.type = INPUT_MOUSE;
1566 input.u.mi.dx = pos.x;
1567 input.u.mi.dy = pos.y;
1568 input.u.mi.mouseData = button_up_data[button - 1];
1569 input.u.mi.dwFlags = button_up_flags[button - 1] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
1570 input.u.mi.time = GetTickCount();
1571 input.u.mi.dwExtraInfo = 0;
1572 __wine_send_input( hwnd, &input );
1575 while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE ))
1577 if (!CallMsgFilterW( &msg, MSGF_SIZE ))
1579 TranslateMessage( &msg );
1580 DispatchMessageW( &msg );
1584 if (!(xstate & (Button1Mask << (button - 1)))) break;
1585 MsgWaitForMultipleObjects( 0, NULL, FALSE, 100, QS_ALLINPUT );
1588 TRACE( "hwnd %p/%lx done\n", hwnd, win );
1589 SendMessageW( hwnd, WM_EXITSIZEMOVE, 0, 0 );
1593 /***********************************************************************
1594 * X11DRV_ButtonPress
1596 BOOL X11DRV_ButtonPress( HWND hwnd, XEvent *xev )
1598 XButtonEvent *event = &xev->xbutton;
1599 int buttonNum = event->button - 1;
1600 INPUT input;
1602 if (buttonNum >= NB_BUTTONS) return FALSE;
1604 TRACE( "hwnd %p/%lx button %u pos %d,%d\n", hwnd, event->window, buttonNum, event->x, event->y );
1606 input.u.mi.dx = event->x;
1607 input.u.mi.dy = event->y;
1608 input.u.mi.mouseData = button_down_data[buttonNum];
1609 input.u.mi.dwFlags = button_down_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
1610 input.u.mi.time = EVENT_x11_time_to_win32_time( event->time );
1611 input.u.mi.dwExtraInfo = 0;
1613 update_user_time( event->time );
1614 send_mouse_input( hwnd, event->window, event->state, &input );
1615 return TRUE;
1619 /***********************************************************************
1620 * X11DRV_ButtonRelease
1622 BOOL X11DRV_ButtonRelease( HWND hwnd, XEvent *xev )
1624 XButtonEvent *event = &xev->xbutton;
1625 int buttonNum = event->button - 1;
1626 INPUT input;
1628 if (buttonNum >= NB_BUTTONS || !button_up_flags[buttonNum]) return FALSE;
1630 TRACE( "hwnd %p/%lx button %u pos %d,%d\n", hwnd, event->window, buttonNum, event->x, event->y );
1632 input.u.mi.dx = event->x;
1633 input.u.mi.dy = event->y;
1634 input.u.mi.mouseData = button_up_data[buttonNum];
1635 input.u.mi.dwFlags = button_up_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
1636 input.u.mi.time = EVENT_x11_time_to_win32_time( event->time );
1637 input.u.mi.dwExtraInfo = 0;
1639 send_mouse_input( hwnd, event->window, event->state, &input );
1640 return TRUE;
1644 /***********************************************************************
1645 * X11DRV_MotionNotify
1647 BOOL X11DRV_MotionNotify( HWND hwnd, XEvent *xev )
1649 XMotionEvent *event = &xev->xmotion;
1650 INPUT input;
1652 TRACE( "hwnd %p/%lx pos %d,%d is_hint %d serial %lu\n",
1653 hwnd, event->window, event->x, event->y, event->is_hint, event->serial );
1655 input.u.mi.dx = event->x;
1656 input.u.mi.dy = event->y;
1657 input.u.mi.mouseData = 0;
1658 input.u.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
1659 input.u.mi.time = EVENT_x11_time_to_win32_time( event->time );
1660 input.u.mi.dwExtraInfo = 0;
1662 if (!hwnd && is_old_motion_event( event->serial ))
1664 TRACE( "pos %d,%d old serial %lu, ignoring\n", input.u.mi.dx, input.u.mi.dy, event->serial );
1665 return FALSE;
1667 send_mouse_input( hwnd, event->window, event->state, &input );
1668 return TRUE;
1672 /***********************************************************************
1673 * X11DRV_EnterNotify
1675 BOOL X11DRV_EnterNotify( HWND hwnd, XEvent *xev )
1677 XCrossingEvent *event = &xev->xcrossing;
1678 INPUT input;
1680 TRACE( "hwnd %p/%lx pos %d,%d detail %d\n", hwnd, event->window, event->x, event->y, event->detail );
1682 if (event->detail == NotifyVirtual) return FALSE;
1683 if (hwnd == x11drv_thread_data()->grab_hwnd) return FALSE;
1685 /* simulate a mouse motion event */
1686 input.u.mi.dx = event->x;
1687 input.u.mi.dy = event->y;
1688 input.u.mi.mouseData = 0;
1689 input.u.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
1690 input.u.mi.time = EVENT_x11_time_to_win32_time( event->time );
1691 input.u.mi.dwExtraInfo = 0;
1693 if (is_old_motion_event( event->serial ))
1695 TRACE( "pos %d,%d old serial %lu, ignoring\n", input.u.mi.dx, input.u.mi.dy, event->serial );
1696 return FALSE;
1698 send_mouse_input( hwnd, event->window, event->state, &input );
1699 return TRUE;
1702 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
1704 /***********************************************************************
1705 * X11DRV_DeviceChanged
1707 static BOOL X11DRV_DeviceChanged( XGenericEventCookie *xev )
1709 XIDeviceChangedEvent *event = xev->data;
1710 struct x11drv_thread_data *data = x11drv_thread_data();
1712 if (event->deviceid != data->xi2_core_pointer) return FALSE;
1713 if (event->reason != XISlaveSwitch) return FALSE;
1715 update_relative_valuators( event->classes, event->num_classes );
1716 data->xi2_current_slave = event->sourceid;
1717 return TRUE;
1720 /***********************************************************************
1721 * X11DRV_RawMotion
1723 static BOOL X11DRV_RawMotion( XGenericEventCookie *xev )
1725 XIRawEvent *event = xev->data;
1726 const double *values = event->valuators.values;
1727 RECT virtual_rect;
1728 INPUT input;
1729 int i;
1730 double dx = 0, dy = 0, val;
1731 struct x11drv_thread_data *thread_data = x11drv_thread_data();
1732 struct x11drv_valuator_data *x_rel, *y_rel;
1734 if (thread_data->x_rel_valuator.number < 0 || thread_data->y_rel_valuator.number < 0) return FALSE;
1735 if (!event->valuators.mask_len) return FALSE;
1736 if (thread_data->xi2_state != xi_enabled) return FALSE;
1738 /* If there is no slave currently detected, no previous motion nor device
1739 * change events were received. Look it up now on the device list in this
1740 * case.
1742 if (!thread_data->xi2_current_slave)
1744 XIDeviceInfo *devices = thread_data->xi2_devices;
1746 for (i = 0; i < thread_data->xi2_device_count; i++)
1748 if (devices[i].use != XISlavePointer) continue;
1749 if (devices[i].deviceid != event->deviceid) continue;
1750 if (devices[i].attachment != thread_data->xi2_core_pointer) continue;
1751 thread_data->xi2_current_slave = event->deviceid;
1752 break;
1756 if (event->deviceid != thread_data->xi2_current_slave) return FALSE;
1758 x_rel = &thread_data->x_rel_valuator;
1759 y_rel = &thread_data->y_rel_valuator;
1761 input.u.mi.mouseData = 0;
1762 input.u.mi.dwFlags = MOUSEEVENTF_MOVE;
1763 input.u.mi.time = EVENT_x11_time_to_win32_time( event->time );
1764 input.u.mi.dwExtraInfo = 0;
1765 input.u.mi.dx = 0;
1766 input.u.mi.dy = 0;
1768 virtual_rect = get_virtual_screen_rect();
1770 for (i = 0; i <= max ( x_rel->number, y_rel->number ); i++)
1772 if (!XIMaskIsSet( event->valuators.mask, i )) continue;
1773 val = *values++;
1774 if (i == x_rel->number)
1776 input.u.mi.dx = dx = val;
1777 if (x_rel->min < x_rel->max)
1778 input.u.mi.dx = val * (virtual_rect.right - virtual_rect.left)
1779 / (x_rel->max - x_rel->min);
1781 if (i == y_rel->number)
1783 input.u.mi.dy = dy = val;
1784 if (y_rel->min < y_rel->max)
1785 input.u.mi.dy = val * (virtual_rect.bottom - virtual_rect.top)
1786 / (y_rel->max - y_rel->min);
1790 if (broken_rawevents && is_old_motion_event( xev->serial ))
1792 TRACE( "pos %d,%d old serial %lu, ignoring\n", input.u.mi.dx, input.u.mi.dy, xev->serial );
1793 return FALSE;
1796 TRACE( "pos %d,%d (event %f,%f)\n", input.u.mi.dx, input.u.mi.dy, dx, dy );
1798 input.type = INPUT_MOUSE;
1799 __wine_send_input( 0, &input );
1800 return TRUE;
1803 #endif /* HAVE_X11_EXTENSIONS_XINPUT2_H */
1806 /***********************************************************************
1807 * X11DRV_XInput2_Init
1809 void X11DRV_XInput2_Init(void)
1811 #if defined(SONAME_LIBXI) && defined(HAVE_X11_EXTENSIONS_XINPUT2_H)
1812 int event, error;
1813 void *libxi_handle = wine_dlopen( SONAME_LIBXI, RTLD_NOW, NULL, 0 );
1815 if (!libxi_handle)
1817 WARN( "couldn't load %s\n", SONAME_LIBXI );
1818 return;
1820 #define LOAD_FUNCPTR(f) \
1821 if (!(p##f = wine_dlsym( libxi_handle, #f, NULL, 0))) \
1823 WARN("Failed to load %s.\n", #f); \
1824 return; \
1827 LOAD_FUNCPTR(XIGetClientPointer);
1828 LOAD_FUNCPTR(XIFreeDeviceInfo);
1829 LOAD_FUNCPTR(XIQueryDevice);
1830 LOAD_FUNCPTR(XIQueryVersion);
1831 LOAD_FUNCPTR(XISelectEvents);
1832 #undef LOAD_FUNCPTR
1834 xinput2_available = XQueryExtension( gdi_display, "XInputExtension", &xinput2_opcode, &event, &error );
1836 /* Until version 1.10.4 rawinput was broken in XOrg, see
1837 * https://bugs.freedesktop.org/show_bug.cgi?id=30068 */
1838 broken_rawevents = strstr(XServerVendor( gdi_display ), "X.Org") &&
1839 XVendorRelease( gdi_display ) < 11004000;
1841 #else
1842 TRACE( "X Input 2 support not compiled in.\n" );
1843 #endif
1847 /***********************************************************************
1848 * X11DRV_GenericEvent
1850 BOOL X11DRV_GenericEvent( HWND hwnd, XEvent *xev )
1852 BOOL ret = FALSE;
1853 #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
1854 XGenericEventCookie *event = &xev->xcookie;
1856 if (!event->data) return FALSE;
1857 if (event->extension != xinput2_opcode) return FALSE;
1859 switch (event->evtype)
1861 case XI_DeviceChanged:
1862 ret = X11DRV_DeviceChanged( event );
1863 break;
1864 case XI_RawMotion:
1865 ret = X11DRV_RawMotion( event );
1866 break;
1868 default:
1869 TRACE( "Unhandled event %#x\n", event->evtype );
1870 break;
1872 #endif
1873 return ret;