mouse.c 65.4 KB
Newer Older
1
/*
2
 * X11 mouse driver
3
 *
4
 * Copyright 1998 Ulrich Weigand
5
 * Copyright 2007 Henri Verbeet
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 23
 */

#include "config.h"

24
#include <math.h>
25
#include <dlfcn.h>
26
#include <X11/Xlib.h>
27
#include <X11/cursorfont.h>
28
#include <stdarg.h>
29 30 31
#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
#include <X11/extensions/XInput2.h>
#endif
32

33
#ifdef SONAME_LIBXCURSOR
34 35 36 37 38 39
# include <X11/Xcursor/Xcursor.h>
static void *xcursor_handle;
# define MAKE_FUNCPTR(f) static typeof(f) * p##f
MAKE_FUNCPTR(XcursorImageCreate);
MAKE_FUNCPTR(XcursorImageDestroy);
MAKE_FUNCPTR(XcursorImageLoadCursor);
40 41 42
MAKE_FUNCPTR(XcursorImagesCreate);
MAKE_FUNCPTR(XcursorImagesDestroy);
MAKE_FUNCPTR(XcursorImagesLoadCursor);
43
MAKE_FUNCPTR(XcursorLibraryLoadCursor);
44
# undef MAKE_FUNCPTR
45
#endif /* SONAME_LIBXCURSOR */
46

47
#define NONAMELESSUNION
48
#define OEMRESOURCE
49
#include "windef.h"
50
#include "winbase.h"
51
#include "winreg.h"
52

53
#include "x11drv.h"
54
#include "wine/server.h"
55
#include "wine/unicode.h"
56
#include "wine/debug.h"
57

58
WINE_DEFAULT_DEBUG_CHANNEL(cursor);
59

60 61
/**********************************************************************/

62 63 64 65 66 67 68
#ifndef Button6Mask
#define Button6Mask (1<<13)
#endif
#ifndef Button7Mask
#define Button7Mask (1<<14)
#endif

69
#define NB_BUTTONS   9     /* Windows can handle 5 buttons and the wheel too */
70 71 72 73 74 75 76

static const UINT button_down_flags[NB_BUTTONS] =
{
    MOUSEEVENTF_LEFTDOWN,
    MOUSEEVENTF_MIDDLEDOWN,
    MOUSEEVENTF_RIGHTDOWN,
    MOUSEEVENTF_WHEEL,
77
    MOUSEEVENTF_WHEEL,
78 79
    MOUSEEVENTF_HWHEEL,
    MOUSEEVENTF_HWHEEL,
80 81
    MOUSEEVENTF_XDOWN,
    MOUSEEVENTF_XDOWN
82 83 84 85 86 87 88 89
};

static const UINT button_up_flags[NB_BUTTONS] =
{
    MOUSEEVENTF_LEFTUP,
    MOUSEEVENTF_MIDDLEUP,
    MOUSEEVENTF_RIGHTUP,
    0,
90
    0,
91 92
    0,
    0,
93
    MOUSEEVENTF_XUP,
94
    MOUSEEVENTF_XUP
95 96
};

97 98 99 100 101 102 103
static const UINT button_down_data[NB_BUTTONS] =
{
    0,
    0,
    0,
    WHEEL_DELTA,
    -WHEEL_DELTA,
104 105
    -WHEEL_DELTA,
    WHEEL_DELTA,
106 107 108 109 110 111 112 113 114 115 116
    XBUTTON1,
    XBUTTON2
};

static const UINT button_up_data[NB_BUTTONS] =
{
    0,
    0,
    0,
    0,
    0,
117 118
    0,
    0,
119 120 121 122
    XBUTTON1,
    XBUTTON2
};

123 124
XContext cursor_context = 0;

125
static HWND cursor_window;
126 127
static HCURSOR last_cursor;
static DWORD last_cursor_change;
128 129 130
static RECT last_clip_rect;
static HWND last_clip_foreground_window;
static BOOL last_clip_refused;
131
static RECT clip_rect;
132
static Cursor create_cursor( HANDLE handle );
133

134 135
#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
static BOOL xinput2_available;
136
static BOOL broken_rawevents;
137
#define MAKE_FUNCPTR(f) static typeof(f) * p##f
138
MAKE_FUNCPTR(XIGetClientPointer);
139 140 141 142 143 144
MAKE_FUNCPTR(XIFreeDeviceInfo);
MAKE_FUNCPTR(XIQueryDevice);
MAKE_FUNCPTR(XIQueryVersion);
MAKE_FUNCPTR(XISelectEvents);
#undef MAKE_FUNCPTR
#endif
145 146 147 148 149 150 151 152

/***********************************************************************
 *		X11DRV_Xcursor_Init
 *
 * Load the Xcursor library for use.
 */
void X11DRV_Xcursor_Init(void)
{
153
#ifdef SONAME_LIBXCURSOR
154 155
    xcursor_handle = dlopen(SONAME_LIBXCURSOR, RTLD_NOW);
    if (!xcursor_handle)
156 157 158 159
    {
        WARN("Xcursor failed to load.  Using fallback code.\n");
        return;
    }
160
#define LOAD_FUNCPTR(f) p##f = dlsym(xcursor_handle, #f)
161 162 163 164

    LOAD_FUNCPTR(XcursorImageCreate);
    LOAD_FUNCPTR(XcursorImageDestroy);
    LOAD_FUNCPTR(XcursorImageLoadCursor);
165 166 167
    LOAD_FUNCPTR(XcursorImagesCreate);
    LOAD_FUNCPTR(XcursorImagesDestroy);
    LOAD_FUNCPTR(XcursorImagesLoadCursor);
168
    LOAD_FUNCPTR(XcursorLibraryLoadCursor);
169
#undef LOAD_FUNCPTR
170
#endif /* SONAME_LIBXCURSOR */
171 172 173
}


174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
/***********************************************************************
 *		get_empty_cursor
 */
static Cursor get_empty_cursor(void)
{
    static Cursor cursor;
    static const char data[] = { 0 };

    if (!cursor)
    {
        XColor bg;
        Pixmap pixmap;

        bg.red = bg.green = bg.blue = 0x0000;
        pixmap = XCreateBitmapFromData( gdi_display, root_window, data, 1, 1 );
        if (pixmap)
        {
191 192 193
            Cursor new = XCreatePixmapCursor( gdi_display, pixmap, pixmap, &bg, &bg, 0, 0 );
            if (InterlockedCompareExchangePointer( (void **)&cursor, (void *)new, 0 ))
                XFreeCursor( gdi_display, new );
194 195 196 197 198 199
            XFreePixmap( gdi_display, pixmap );
        }
    }
    return cursor;
}

200 201 202
/***********************************************************************
 *		set_window_cursor
 */
203
void set_window_cursor( Window window, HCURSOR handle )
204
{
205
    Cursor cursor, prev;
206

207
    if (!handle) cursor = get_empty_cursor();
208
    else if (XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&cursor ))
209
    {
210 211 212
        /* try to create it */
        if (!(cursor = create_cursor( handle ))) return;

213
        XLockDisplay( gdi_display );
214 215 216 217 218 219 220 221 222 223 224
        if (!XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&prev ))
        {
            /* someone else was here first */
            XFreeCursor( gdi_display, cursor );
            cursor = prev;
        }
        else
        {
            XSaveContext( gdi_display, (XID)handle, cursor_context, (char *)cursor );
            TRACE( "cursor %p created %lx\n", handle, cursor );
        }
225
        XUnlockDisplay( gdi_display );
226
    }
227

228
    XDefineCursor( gdi_display, window, cursor );
229 230
    /* make the change take effect immediately */
    XFlush( gdi_display );
231 232
}

233 234 235
/***********************************************************************
 *              sync_window_cursor
 */
236
void sync_window_cursor( Window window )
237 238 239 240 241 242 243 244 245 246 247
{
    HCURSOR cursor;

    SERVER_START_REQ( set_cursor )
    {
        req->flags = 0;
        wine_server_call( req );
        cursor = reply->prev_count >= 0 ? wine_server_ptr_handle( reply->prev_handle ) : 0;
    }
    SERVER_END_REQ;

248
    set_window_cursor( window, cursor );
249 250
}

251
#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
252 253 254 255 256 257 258 259
/***********************************************************************
 *              update_relative_valuators
 */
static void update_relative_valuators(XIAnyClassInfo **valuators, int n_valuators)
{
    struct x11drv_thread_data *thread_data = x11drv_thread_data();
    int i;

260 261
    thread_data->x_valuator.number = -1;
    thread_data->y_valuator.number = -1;
262 263 264 265 266 267 268

    for (i = 0; i < n_valuators; i++)
    {
        XIValuatorClassInfo *class = (XIValuatorClassInfo *)valuators[i];
        if (valuators[i]->type != XIValuatorClass) continue;
        if (class->label == x11drv_atom( Rel_X ) ||
            (!class->label && class->number == 0 && class->mode == XIModeRelative))
269
            thread_data->x_valuator = *class;
270 271
        else if (class->label == x11drv_atom( Rel_Y ) ||
                 (!class->label && class->number == 1 && class->mode == XIModeRelative))
272
            thread_data->y_valuator = *class;
273
    }
274 275 276

    thread_data->x_valuator.value = 0;
    thread_data->y_valuator.value = 0;
277 278 279
}


280 281 282 283 284 285 286
/***********************************************************************
 *              enable_xinput2
 */
static void enable_xinput2(void)
{
    struct x11drv_thread_data *data = x11drv_thread_data();
    XIEventMask mask;
287
    XIDeviceInfo *pointer_info;
288
    unsigned char mask_bits[XIMaskLen(XI_LASTEVENT)];
289
    int count;
290 291 292 293 294 295 296 297 298 299 300 301 302 303

    if (!xinput2_available) return;

    if (data->xi2_state == xi_unknown)
    {
        int major = 2, minor = 0;
        if (!pXIQueryVersion( data->display, &major, &minor )) data->xi2_state = xi_disabled;
        else
        {
            data->xi2_state = xi_unavailable;
            WARN( "X Input 2 not available\n" );
        }
    }
    if (data->xi2_state == xi_unavailable) return;
304
    if (!pXIGetClientPointer( data->display, None, &data->xi2_core_pointer )) return;
305 306 307

    mask.mask     = mask_bits;
    mask.mask_len = sizeof(mask_bits);
308
    mask.deviceid = XIAllDevices;
309
    memset( mask_bits, 0, sizeof(mask_bits) );
310
    XISetMask( mask_bits, XI_DeviceChanged );
311
    XISetMask( mask_bits, XI_RawMotion );
312
    XISetMask( mask_bits, XI_ButtonPress );
313

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    pXISelectEvents( data->display, DefaultRootWindow( data->display ), &mask, 1 );

    pointer_info = pXIQueryDevice( data->display, data->xi2_core_pointer, &count );
    update_relative_valuators( pointer_info->classes, pointer_info->num_classes );
    pXIFreeDeviceInfo( pointer_info );

    /* This device info list is only used to find the initial current slave if
     * no XI_DeviceChanged events happened. If any hierarchy change occurred that
     * might be relevant here (eg. user switching mice after (un)plugging), a
     * XI_DeviceChanged event will point us to the right slave. So this list is
     * safe to be obtained statically at enable_xinput2() time.
     */
    if (data->xi2_devices) pXIFreeDeviceInfo( data->xi2_devices );
    data->xi2_devices = pXIQueryDevice( data->display, XIAllDevices, &data->xi2_device_count );
    data->xi2_current_slave = 0;

    data->xi2_state = xi_enabled;
331 332
}

333 334
#endif

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
/***********************************************************************
 *              disable_xinput2
 */
static void disable_xinput2(void)
{
#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
    struct x11drv_thread_data *data = x11drv_thread_data();
    XIEventMask mask;

    if (data->xi2_state != xi_enabled) return;

    TRACE( "disabling\n" );
    data->xi2_state = xi_disabled;

    mask.mask = NULL;
    mask.mask_len = 0;
351
    mask.deviceid = XIAllDevices;
352

353 354
    pXISelectEvents( data->display, DefaultRootWindow( data->display ), &mask, 1 );
    pXIFreeDeviceInfo( data->xi2_devices );
355 356
    data->x_valuator.number = -1;
    data->y_valuator.number = -1;
357 358
    data->x_valuator.value = 0;
    data->y_valuator.value = 0;
359
    data->xi2_devices = NULL;
360 361
    data->xi2_core_pointer = 0;
    data->xi2_current_slave = 0;
362 363 364
#endif
}

365

366 367 368 369 370
/***********************************************************************
 *		grab_clipping_window
 *
 * Start a pointer grab on the clip window.
 */
371
static BOOL grab_clipping_window( const RECT *clip )
372
{
373
#if HAVE_X11_EXTENSIONS_XINPUT2_H
374
    static const WCHAR messageW[] = {'M','e','s','s','a','g','e',0};
375 376
    struct x11drv_thread_data *data = x11drv_thread_data();
    Window clip_window;
377
    HWND msg_hwnd = 0;
378
    POINT pos;
379

380 381 382
    if (GetWindowThreadProcessId( GetDesktopWindow(), NULL ) == GetCurrentThreadId())
        return TRUE;  /* don't clip in the desktop process */

383 384
    if (!data) return FALSE;
    if (!(clip_window = init_clip_window())) return TRUE;
385

386 387 388 389
    if (!(msg_hwnd = CreateWindowW( messageW, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0,
                                    GetModuleHandleW(0), NULL )))
        return TRUE;

390 391 392
    if (keyboard_grabbed)
    {
        WARN( "refusing to clip to %s\n", wine_dbgstr_rect(clip) );
393 394 395
        last_clip_refused = TRUE;
        last_clip_foreground_window = GetForegroundWindow();
        last_clip_rect = *clip;
396 397
        return FALSE;
    }
398 399 400 401
    else
    {
        last_clip_refused = FALSE;
    }
402

403 404
    /* enable XInput2 unless we are already clipping */
    if (!data->clip_hwnd) enable_xinput2();
405

406
    if (data->xi2_state != xi_enabled)
407 408
    {
        WARN( "XInput2 not supported, refusing to clip to %s\n", wine_dbgstr_rect(clip) );
409
        DestroyWindow( msg_hwnd );
410 411 412
        ClipCursor( NULL );
        return TRUE;
    }
413

414
    TRACE( "clipping to %s win %lx\n", wine_dbgstr_rect(clip), clip_window );
415

416
    if (!data->clip_hwnd) XUnmapWindow( data->display, clip_window );
417 418
    pos = virtual_screen_to_root( clip->left, clip->top );
    XMoveResizeWindow( data->display, clip_window, pos.x, pos.y,
419
                       max( 1, clip->right - clip->left ), max( 1, clip->bottom - clip->top ) );
420
    XMapWindow( data->display, clip_window );
421 422

    /* if the rectangle is shrinking we may get a pointer warp */
423
    if (!data->clip_hwnd || clip->left > clip_rect.left || clip->top > clip_rect.top ||
424 425 426
        clip->right < clip_rect.right || clip->bottom < clip_rect.bottom)
        data->warp_serial = NextRequest( data->display );

427 428 429
    if (!XGrabPointer( data->display, clip_window, False,
                       PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
                       GrabModeAsync, GrabModeAsync, clip_window, None, CurrentTime ))
430
        clipping_cursor = TRUE;
431 432 433

    if (!clipping_cursor)
    {
434
        disable_xinput2();
435
        DestroyWindow( msg_hwnd );
436 437
        return FALSE;
    }
438
    clip_rect = *clip;
439
    if (!data->clip_hwnd) sync_window_cursor( clip_window );
440
    InterlockedExchangePointer( (void **)&cursor_window, msg_hwnd );
441
    data->clip_hwnd = msg_hwnd;
442
    SendNotifyMessageW( GetDesktopWindow(), WM_X11DRV_CLIP_CURSOR_NOTIFY, 0, (LPARAM)msg_hwnd );
443
    return TRUE;
444 445 446 447
#else
    WARN( "XInput2 was not available at compile time\n" );
    return FALSE;
#endif
448 449 450 451 452 453 454
}

/***********************************************************************
 *		ungrab_clipping_window
 *
 * Release the pointer grab on the clip window.
 */
455
void ungrab_clipping_window(void)
456 457 458 459 460 461 462 463
{
    Display *display = thread_init_display();
    Window clip_window = init_clip_window();

    if (!clip_window) return;

    TRACE( "no longer clipping\n" );
    XUnmapWindow( display, clip_window );
464
    if (clipping_cursor) XUngrabPointer( display, CurrentTime );
465
    clipping_cursor = FALSE;
466
    SendNotifyMessageW( GetDesktopWindow(), WM_X11DRV_CLIP_CURSOR_NOTIFY, 0, 0 );
467 468
}

469 470 471 472 473 474 475 476 477 478 479
/***********************************************************************
 *		reset_clipping_window
 *
 * Forcibly reset the window clipping on external events.
 */
void reset_clipping_window(void)
{
    ungrab_clipping_window();
    ClipCursor( NULL );  /* make sure the clip rectangle is reset too */
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493
/***********************************************************************
 *      retry_grab_clipping_window
 *
 * Restore the current clip rectangle or retry the last one if it has
 * been refused because of an active keyboard grab.
 */
void retry_grab_clipping_window(void)
{
    if (clipping_cursor)
        ClipCursor( &clip_rect );
    else if (last_clip_refused && GetForegroundWindow() == last_clip_foreground_window)
        ClipCursor( &last_clip_rect );
}

494 495 496
/***********************************************************************
 *             clip_cursor_notify
 *
497
 * Notification function called upon receiving a WM_X11DRV_CLIP_CURSOR_NOTIFY.
498
 */
499
LRESULT clip_cursor_notify( HWND hwnd, HWND prev_clip_hwnd, HWND new_clip_hwnd )
500
{
501
    struct x11drv_thread_data *data = x11drv_init_thread_data();
502 503 504 505 506 507 508 509

    if (hwnd == GetDesktopWindow())  /* change the clip window stored in the desktop process */
    {
        static HWND clip_hwnd;

        HWND prev = clip_hwnd;
        clip_hwnd = new_clip_hwnd;
        if (prev || new_clip_hwnd) TRACE( "clip hwnd changed from %p to %p\n", prev, new_clip_hwnd );
510
        if (prev) SendNotifyMessageW( prev, WM_X11DRV_CLIP_CURSOR_NOTIFY, (WPARAM)prev, 0 );
511 512 513
    }
    else if (hwnd == data->clip_hwnd)  /* this is a notification that clipping has been reset */
    {
514
        TRACE( "clip hwnd reset from %p\n", hwnd );
515
        data->clip_hwnd = 0;
516
        data->clip_reset = GetTickCount();
517 518 519
        disable_xinput2();
        DestroyWindow( hwnd );
    }
520 521 522 523 524 525 526 527
    else if (prev_clip_hwnd)
    {
        /* This is a notification send by the desktop window to an old
         * dangling clip window.
         */
        TRACE( "destroying old clip hwnd %p\n", prev_clip_hwnd );
        DestroyWindow( prev_clip_hwnd );
    }
528 529 530
    return 0;
}

531 532 533 534 535
/***********************************************************************
 *		clip_fullscreen_window
 *
 * Turn on clipping if the active window is fullscreen.
 */
536
BOOL clip_fullscreen_window( HWND hwnd, BOOL reset )
537 538
{
    struct x11drv_win_data *data;
539
    struct x11drv_thread_data *thread_data;
540 541
    MONITORINFO monitor_info;
    HMONITOR monitor;
542
    DWORD style;
543
    BOOL fullscreen;
544 545 546 547 548 549 550

    if (hwnd == GetDesktopWindow()) return FALSE;
    style = GetWindowLongW( hwnd, GWL_STYLE );
    if (!(style & WS_VISIBLE)) return FALSE;
    if ((style & (WS_POPUP | WS_CHILD)) == WS_CHILD) return FALSE;
    /* maximized windows don't count as full screen */
    if ((style & WS_MAXIMIZE) && (style & WS_CAPTION) == WS_CAPTION) return FALSE;
551
    if (!(data = get_win_data( hwnd ))) return FALSE;
552
    fullscreen = is_window_rect_full_screen( &data->whole_rect );
553 554
    release_win_data( data );
    if (!fullscreen) return FALSE;
555 556
    if (!(thread_data = x11drv_thread_data())) return FALSE;
    if (GetTickCount() - thread_data->clip_reset < 1000) return FALSE;
557
    if (!reset && clipping_cursor && thread_data->clip_hwnd) return FALSE;  /* already clipping */
558 559 560 561 562

    monitor = MonitorFromWindow( hwnd, MONITOR_DEFAULTTONEAREST );
    if (!monitor) return FALSE;
    monitor_info.cbSize = sizeof(monitor_info);
    if (!GetMonitorInfoW( monitor, &monitor_info )) return FALSE;
563 564
    if (!grab_fullscreen)
    {
565
        RECT virtual_rect = get_virtual_screen_rect();
566
        if (!EqualRect( &monitor_info.rcMonitor, &virtual_rect )) return FALSE;
567
        if (is_virtual_desktop()) return FALSE;
568
    }
569
    TRACE( "win %p clipping fullscreen\n", hwnd );
570
    return grab_clipping_window( &monitor_info.rcMonitor );
571 572
}

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

/***********************************************************************
 *		is_old_motion_event
 */
static BOOL is_old_motion_event( unsigned long serial )
{
    struct x11drv_thread_data *thread_data = x11drv_thread_data();

    if (!thread_data->warp_serial) return FALSE;
    if ((long)(serial - thread_data->warp_serial) < 0) return TRUE;
    thread_data->warp_serial = 0;  /* we caught up now */
    return FALSE;
}


588 589 590 591 592
/***********************************************************************
 *		map_event_coords
 *
 * Map the input event coordinates so they're relative to the desktop.
 */
593
static void map_event_coords( HWND hwnd, Window window, Window event_root, int x_root, int y_root, INPUT *input )
594
{
595 596
    struct x11drv_thread_data *thread_data;
    struct x11drv_win_data *data;
597 598
    POINT pt = { input->u.mi.dx, input->u.mi.dy };

599 600
    TRACE( "hwnd %p, window %lx, event_root %lx, x_root %d, y_root %d, input %p\n", hwnd, window, event_root,
           x_root, y_root, input );
601

602 603 604 605 606 607 608 609 610
    if (!hwnd)
    {
        thread_data = x11drv_thread_data();
        if (!thread_data->clip_hwnd) return;
        if (thread_data->clip_window != window) return;
        pt.x += clip_rect.left;
        pt.y += clip_rect.top;
    }
    else if ((data = get_win_data( hwnd )))
611
    {
612
        if (window == root_window) pt = root_to_virtual_screen( pt.x, pt.y );
613
        else if (event_root == root_window) pt = root_to_virtual_screen( x_root, y_root );
614
        else
615
        {
616 617 618 619 620
            if (window == data->whole_window)
            {
                pt.x += data->whole_rect.left - data->client_rect.left;
                pt.y += data->whole_rect.top - data->client_rect.top;
            }
621

622 623 624 625 626
            if (GetWindowLongW( hwnd, GWL_EXSTYLE ) & WS_EX_LAYOUTRTL)
                pt.x = data->client_rect.right - data->client_rect.left - 1 - pt.x;
            MapWindowPoints( hwnd, 0, &pt, 1 );
        }
        release_win_data( data );
627
    }
628 629 630

    TRACE( "mapped %s to %s\n", wine_dbgstr_point( (POINT *)&input->u.mi.dx ), wine_dbgstr_point( &pt ) );

631 632
    input->u.mi.dx = pt.x;
    input->u.mi.dy = pt.y;
633 634
}

635
/***********************************************************************
636
 *		send_mouse_input
637 638 639
 *
 * Update the various window states on a mouse event.
 */
640
static void send_mouse_input( HWND hwnd, Window window, unsigned int state, INPUT *input )
641
{
642
    struct x11drv_win_data *data;
643 644

    input->type = INPUT_MOUSE;
645

646
    if (!hwnd)
647
    {
648
        struct x11drv_thread_data *thread_data = x11drv_thread_data();
649
        HWND clip_hwnd = thread_data->clip_hwnd;
650

651
        if (!clip_hwnd) return;
652
        if (thread_data->clip_window != window) return;
653
        if (InterlockedExchangePointer( (void **)&cursor_window, clip_hwnd ) != clip_hwnd ||
654
            input->u.mi.time - last_cursor_change > 100)
655 656
        {
            sync_window_cursor( window );
657
            last_cursor_change = input->u.mi.time;
658
        }
659
        __wine_send_input( hwnd, input, NULL );
660
        return;
661 662
    }

663
    if (!(data = get_win_data( hwnd ))) return;
664
    if (InterlockedExchangePointer( (void **)&cursor_window, hwnd ) != hwnd ||
665
        input->u.mi.time - last_cursor_change > 100)
666
    {
667
        sync_window_cursor( data->whole_window );
668
        last_cursor_change = input->u.mi.time;
669
    }
670
    release_win_data( data );
671

672 673 674 675
    if (hwnd != GetDesktopWindow())
    {
        hwnd = GetAncestor( hwnd, GA_ROOT );
        if ((input->u.mi.dwFlags & (MOUSEEVENTF_LEFTDOWN|MOUSEEVENTF_RIGHTDOWN)) && hwnd == GetForegroundWindow())
676
            clip_fullscreen_window( hwnd, FALSE );
677
    }
678 679 680

    /* update the wine server Z-order */

681
    if (hwnd != x11drv_thread_data()->grab_hwnd &&
682
        /* ignore event if a button is pressed, since the mouse is then grabbed too */
683
        !(state & (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask|Button6Mask|Button7Mask)))
684
    {
685
        RECT rect = { input->u.mi.dx, input->u.mi.dy, input->u.mi.dx + 1, input->u.mi.dy + 1 };
686

687 688
        SERVER_START_REQ( update_window_zorder )
        {
689
            req->window      = wine_server_user_handle( hwnd );
690 691 692 693
            req->rect.left   = rect.left;
            req->rect.top    = rect.top;
            req->rect.right  = rect.right;
            req->rect.bottom = rect.bottom;
694 695 696 697
            wine_server_call( req );
        }
        SERVER_END_REQ;
    }
698

699
    __wine_send_input( hwnd, input, NULL );
700 701
}

702
#ifdef SONAME_LIBXCURSOR
703 704

/***********************************************************************
705
 *              create_xcursor_frame
706
 *
707
 * Use Xcursor to create a frame of an X cursor from a Windows one.
708
 */
709
static XcursorImage *create_xcursor_frame( HDC hdc, const ICONINFOEXW *iinfo, HANDLE icon,
710 711 712
                                           HBITMAP hbmColor, unsigned char *color_bits, int color_size,
                                           HBITMAP hbmMask, unsigned char *mask_bits, int mask_size,
                                           int width, int height, int istep )
713
{
714
    XcursorImage *image, *ret = NULL;
715
    DWORD delay_jiffies, num_steps;
716 717
    int x, y, i;
    BOOL has_alpha = FALSE;
718
    XcursorPixel *ptr;
719

720 721
    image = pXcursorImageCreate( width, height );
    if (!image)
722
    {
723
        ERR("X11 failed to produce a cursor frame!\n");
724
        return NULL;
725 726 727 728
    }

    image->xhot = iinfo->xHotspot;
    image->yhot = iinfo->yHotspot;
729 730

    image->delay = 100; /* fallback delay, 100 ms */
731
    if (GetCursorFrameInfo(icon, 0x0 /* unknown parameter */, istep, &delay_jiffies, &num_steps) != 0)
732 733
        image->delay = (100 * delay_jiffies) / 6; /* convert jiffies (1/60s) to milliseconds */
    else
734
        WARN("Failed to retrieve animated cursor frame-rate for frame %d.\n", istep);
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767

    /* draw the cursor frame to a temporary buffer then copy it into the XcursorImage */
    memset( color_bits, 0x00, color_size );
    SelectObject( hdc, hbmColor );
    if (!DrawIconEx( hdc, 0, 0, icon, width, height, istep, NULL, DI_NORMAL ))
    {
        TRACE("Could not draw frame %d (walk past end of frames).\n", istep);
        goto cleanup;
    }
    memcpy( image->pixels, color_bits, color_size );

    /* check if the cursor frame was drawn with an alpha channel */
    for (i = 0, ptr = image->pixels; i < width * height; i++, ptr++)
        if ((has_alpha = (*ptr & 0xff000000) != 0)) break;

    /* if no alpha channel was drawn then generate it from the mask */
    if (!has_alpha)
    {
        unsigned int width_bytes = (width + 31) / 32 * 4;

        /* draw the cursor mask to a temporary buffer */
        memset( mask_bits, 0xFF, mask_size );
        SelectObject( hdc, hbmMask );
        if (!DrawIconEx( hdc, 0, 0, icon, width, height, istep, NULL, DI_MASK ))
        {
            ERR("Failed to draw frame mask %d.\n", istep);
            goto cleanup;
        }
        /* use the buffer to directly modify the XcursorImage alpha channel */
        for (y = 0, ptr = image->pixels; y < height; y++)
            for (x = 0; x < width; x++, ptr++)
                if (!((mask_bits[y * width_bytes + x / 8] << (x % 8)) & 0x80))
                    *ptr |= 0xff000000;
768
    }
769
    ret = image;
770

771 772 773 774
cleanup:
    if (ret == NULL) pXcursorImageDestroy( image );
    return ret;
}
775

776 777 778 779 780
/***********************************************************************
 *              create_xcursor_cursor
 *
 * Use Xcursor to create an X cursor from a Windows one.
 */
781
static Cursor create_xcursor_cursor( HDC hdc, const ICONINFOEXW *iinfo, HANDLE icon, int width, int height )
782 783 784
{
    unsigned char *color_bits, *mask_bits;
    HBITMAP hbmColor = 0, hbmMask = 0;
785
    DWORD nFrames, delay_jiffies, i;
786 787 788
    int color_size, mask_size;
    BITMAPINFO *info = NULL;
    XcursorImages *images;
789
    XcursorImage **imgs;
790 791
    Cursor cursor = 0;

792 793 794
    /* Retrieve the number of frames to render */
    if (!GetCursorFrameInfo(icon, 0x0 /* unknown parameter */, 0, &delay_jiffies, &nFrames)) return 0;
    if (!(imgs = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(XcursorImage*)*nFrames ))) return 0;
795 796 797

    /* Allocate all of the resources necessary to obtain a cursor frame */
    if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) goto cleanup;
798 799 800 801 802 803 804 805 806
    info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info->bmiHeader.biWidth = width;
    info->bmiHeader.biHeight = -height;
    info->bmiHeader.biPlanes = 1;
    info->bmiHeader.biCompression = BI_RGB;
    info->bmiHeader.biXPelsPerMeter = 0;
    info->bmiHeader.biYPelsPerMeter = 0;
    info->bmiHeader.biClrUsed = 0;
    info->bmiHeader.biClrImportant = 0;
807 808 809 810 811 812 813 814 815 816
    info->bmiHeader.biBitCount = 32;
    color_size = width * height * 4;
    info->bmiHeader.biSizeImage = color_size;
    hbmColor = CreateDIBSection( hdc, info, DIB_RGB_COLORS, (VOID **) &color_bits, NULL, 0);
    if (!hbmColor)
    {
        ERR("Failed to create DIB section for cursor color data!\n");
        goto cleanup;
    }
    info->bmiHeader.biBitCount = 1;
817 818 819 820 821 822 823 824 825
    info->bmiColors[0].rgbRed      = 0;
    info->bmiColors[0].rgbGreen    = 0;
    info->bmiColors[0].rgbBlue     = 0;
    info->bmiColors[0].rgbReserved = 0;
    info->bmiColors[1].rgbRed      = 0xff;
    info->bmiColors[1].rgbGreen    = 0xff;
    info->bmiColors[1].rgbBlue     = 0xff;
    info->bmiColors[1].rgbReserved = 0;

826 827 828 829 830 831 832 833
    mask_size = ((width + 31) / 32 * 4) * height; /* width_bytes * height */
    info->bmiHeader.biSizeImage = mask_size;
    hbmMask = CreateDIBSection( hdc, info, DIB_RGB_COLORS, (VOID **) &mask_bits, NULL, 0);
    if (!hbmMask)
    {
        ERR("Failed to create DIB section for cursor mask data!\n");
        goto cleanup;
    }
834

835
    /* Create an XcursorImage for each frame of the cursor */
836
    for (i=0; i<nFrames; i++)
837
    {
838 839 840 841 842
        imgs[i] = create_xcursor_frame( hdc, iinfo, icon,
                                        hbmColor, color_bits, color_size,
                                        hbmMask, mask_bits, mask_size,
                                        width, height, i );
        if (!imgs[i]) goto cleanup;
843
    }
844

845 846 847 848 849 850 851 852 853 854 855 856 857
    /* Build an X cursor out of all of the frames */
    if (!(images = pXcursorImagesCreate( nFrames ))) goto cleanup;
    for (images->nimage = 0; images->nimage < nFrames; images->nimage++)
        images->images[images->nimage] = imgs[images->nimage];
    cursor = pXcursorImagesLoadCursor( gdi_display, images );
    pXcursorImagesDestroy( images ); /* Note: this frees each individual frame (calls XcursorImageDestroy) */
    HeapFree( GetProcessHeap(), 0, imgs );
    imgs = NULL;

cleanup:
    if (imgs)
    {
        /* Failed to produce a cursor, free previously allocated frames */
858 859
        for (i=0; i<nFrames && imgs[i]; i++)
            pXcursorImageDestroy( imgs[i] );
860 861 862 863 864 865
        HeapFree( GetProcessHeap(), 0, imgs );
    }
    /* Cleanup all of the resources used to obtain the frame data */
    if (hbmColor) DeleteObject( hbmColor );
    if (hbmMask) DeleteObject( hbmMask );
    HeapFree( GetProcessHeap(), 0, info );
866 867 868
    return cursor;
}

869 870
#endif /* SONAME_LIBXCURSOR */

871 872 873 874

struct system_cursors
{
    WORD id;
875
    const char *names[8];
876 877 878 879
};

static const struct system_cursors user32_cursors[] =
{
880 881 882 883 884 885 886 887 888 889
    { OCR_NORMAL,      { "left_ptr" }},
    { OCR_IBEAM,       { "xterm", "text" }},
    { OCR_WAIT,        { "watch", "wait" }},
    { OCR_CROSS,       { "cross" }},
    { OCR_UP,          { "center_ptr" }},
    { OCR_SIZE,        { "fleur", "size_all" }},
    { OCR_SIZEALL,     { "fleur", "size_all" }},
    { OCR_ICON,        { "icon" }},
    { OCR_SIZENWSE,    { "top_left_corner", "nw-resize" }},
    { OCR_SIZENESW,    { "top_right_corner", "ne-resize" }},
890 891
    { OCR_SIZEWE,      { "h_double_arrow", "size_hor", "ew-resize" }},
    { OCR_SIZENS,      { "v_double_arrow", "size_ver", "ns-resize" }},
892 893 894 895
    { OCR_NO,          { "not-allowed", "forbidden", "no-drop" }},
    { OCR_HAND,        { "hand2", "pointer", "pointing-hand" }},
    { OCR_APPSTARTING, { "left_ptr_watch" }},
    { OCR_HELP,        { "question_arrow", "help" }},
896 897 898 899 900
    { 0 }
};

static const struct system_cursors comctl32_cursors[] =
{
901 902 903 904 905 906 907
    { 102, { "move", "dnd-move" }},
    { 104, { "copy", "dnd-copy" }},
    { 105, { "left_ptr" }},
    { 106, { "col-resize", "split_v" }},
    { 107, { "col-resize", "split_v" }},
    { 108, { "hand2", "pointer", "pointing-hand" }},
    { 135, { "row-resize", "split_h" }},
908 909 910 911 912
    { 0 }
};

static const struct system_cursors ole32_cursors[] =
{
913 914 915 916
    { 1, { "no-drop", "dnd-no-drop" }},
    { 2, { "move", "dnd-move" }},
    { 3, { "copy", "dnd-copy" }},
    { 4, { "alias", "dnd-link" }},
917 918 919 920 921
    { 0 }
};

static const struct system_cursors riched20_cursors[] =
{
922 923 924 925 926
    { 105, { "hand2", "pointer", "pointing-hand" }},
    { 107, { "right_ptr" }},
    { 109, { "copy", "dnd-copy" }},
    { 110, { "move", "dnd-move" }},
    { 111, { "no-drop", "dnd-no-drop" }},
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    { 0 }
};

static const struct
{
    const struct system_cursors *cursors;
    WCHAR name[16];
} module_cursors[] =
{
    { user32_cursors, {'u','s','e','r','3','2','.','d','l','l',0} },
    { comctl32_cursors, {'c','o','m','c','t','l','3','2','.','d','l','l',0} },
    { ole32_cursors, {'o','l','e','3','2','.','d','l','l',0} },
    { riched20_cursors, {'r','i','c','h','e','d','2','0','.','d','l','l',0} }
};

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
struct cursor_font_fallback
{
    const char  *name;
    unsigned int shape;
};

static const struct cursor_font_fallback fallbacks[] =
{
    { "X_cursor",            XC_X_cursor },
    { "arrow",               XC_arrow },
    { "based_arrow_down",    XC_based_arrow_down },
    { "based_arrow_up",      XC_based_arrow_up },
    { "boat",                XC_boat },
    { "bogosity",            XC_bogosity },
    { "bottom_left_corner",  XC_bottom_left_corner },
    { "bottom_right_corner", XC_bottom_right_corner },
    { "bottom_side",         XC_bottom_side },
    { "bottom_tee",          XC_bottom_tee },
    { "box_spiral",          XC_box_spiral },
    { "center_ptr",          XC_center_ptr },
    { "circle",              XC_circle },
    { "clock",               XC_clock },
    { "coffee_mug",          XC_coffee_mug },
965
    { "col-resize",          XC_sb_h_double_arrow },
966 967 968 969 970 971 972 973 974 975 976 977 978 979
    { "cross",               XC_cross },
    { "cross_reverse",       XC_cross_reverse },
    { "crosshair",           XC_crosshair },
    { "diamond_cross",       XC_diamond_cross },
    { "dot",                 XC_dot },
    { "dotbox",              XC_dotbox },
    { "double_arrow",        XC_double_arrow },
    { "draft_large",         XC_draft_large },
    { "draft_small",         XC_draft_small },
    { "draped_box",          XC_draped_box },
    { "exchange",            XC_exchange },
    { "fleur",               XC_fleur },
    { "gobbler",             XC_gobbler },
    { "gumby",               XC_gumby },
980
    { "h_double_arrow",      XC_sb_h_double_arrow },
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    { "hand1",               XC_hand1 },
    { "hand2",               XC_hand2 },
    { "heart",               XC_heart },
    { "icon",                XC_icon },
    { "iron_cross",          XC_iron_cross },
    { "left_ptr",            XC_left_ptr },
    { "left_side",           XC_left_side },
    { "left_tee",            XC_left_tee },
    { "leftbutton",          XC_leftbutton },
    { "ll_angle",            XC_ll_angle },
    { "lr_angle",            XC_lr_angle },
    { "man",                 XC_man },
    { "middlebutton",        XC_middlebutton },
    { "mouse",               XC_mouse },
    { "pencil",              XC_pencil },
    { "pirate",              XC_pirate },
    { "plus",                XC_plus },
    { "question_arrow",      XC_question_arrow },
    { "right_ptr",           XC_right_ptr },
    { "right_side",          XC_right_side },
    { "right_tee",           XC_right_tee },
    { "rightbutton",         XC_rightbutton },
1003
    { "row-resize",          XC_sb_v_double_arrow },
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    { "rtl_logo",            XC_rtl_logo },
    { "sailboat",            XC_sailboat },
    { "sb_down_arrow",       XC_sb_down_arrow },
    { "sb_h_double_arrow",   XC_sb_h_double_arrow },
    { "sb_left_arrow",       XC_sb_left_arrow },
    { "sb_right_arrow",      XC_sb_right_arrow },
    { "sb_up_arrow",         XC_sb_up_arrow },
    { "sb_v_double_arrow",   XC_sb_v_double_arrow },
    { "shuttle",             XC_shuttle },
    { "sizing",              XC_sizing },
    { "spider",              XC_spider },
    { "spraycan",            XC_spraycan },
    { "star",                XC_star },
    { "target",              XC_target },
    { "tcross",              XC_tcross },
    { "top_left_arrow",      XC_top_left_arrow },
    { "top_left_corner",     XC_top_left_corner },
    { "top_right_corner",    XC_top_right_corner },
    { "top_side",            XC_top_side },
    { "top_tee",             XC_top_tee },
    { "trek",                XC_trek },
    { "ul_angle",            XC_ul_angle },
    { "umbrella",            XC_umbrella },
    { "ur_angle",            XC_ur_angle },
1028
    { "v_double_arrow",      XC_sb_v_double_arrow },
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    { "watch",               XC_watch },
    { "xterm",               XC_xterm }
};

static int fallback_cmp( const void *key, const void *member )
{
    const struct cursor_font_fallback *fallback = member;
    return strcmp( key, fallback->name );
}

static int find_fallback_shape( const char *name )
{
    struct cursor_font_fallback *fallback;

1043
    if ((fallback = bsearch( name, fallbacks, ARRAY_SIZE( fallbacks ),
1044 1045 1046 1047 1048
                             sizeof(*fallback), fallback_cmp )))
        return fallback->shape;
    return -1;
}

1049 1050 1051 1052 1053 1054 1055
/***********************************************************************
 *		create_xcursor_system_cursor
 *
 * Create an X cursor for a system cursor.
 */
static Cursor create_xcursor_system_cursor( const ICONINFOEXW *info )
{
1056
    static const WCHAR idW[] = {'%','h','u',0};
1057 1058 1059 1060
    const struct system_cursors *cursors;
    unsigned int i;
    Cursor cursor = 0;
    HMODULE module;
1061
    HKEY key;
1062
    const char * const *names = NULL;
1063 1064
    WCHAR *p, name[MAX_PATH * 2], valueW[64];
    char valueA[64];
1065
    DWORD ret;
1066

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    if (!info->szModName[0]) return 0;

    p = strrchrW( info->szModName, '\\' );
    strcpyW( name, p ? p + 1 : info->szModName );
    p = name + strlenW( name );
    *p++ = ',';
    if (info->szResName[0]) strcpyW( p, info->szResName );
    else sprintfW( p, idW, info->wResID );
    valueA[0] = 0;

    /* @@ Wine registry key: HKCU\Software\Wine\X11 Driver\Cursors */
    if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\X11 Driver\\Cursors", &key ))
    {
1080
        DWORD size = sizeof(valueW);
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        ret = RegQueryValueExW( key, name, NULL, NULL, (BYTE *)valueW, &size );
        RegCloseKey( key );
        if (!ret)
        {
            if (!valueW[0]) return 0; /* force standard cursor */
            if (!WideCharToMultiByte( CP_UNIXCP, 0, valueW, -1, valueA, sizeof(valueA), NULL, NULL ))
                valueA[0] = 0;
            goto done;
        }
    }

    if (info->szResName[0]) goto done;  /* only integer resources are supported here */
    if (!(module = GetModuleHandleW( info->szModName ))) goto done;
1094

1095
    for (i = 0; i < ARRAY_SIZE( module_cursors ); i++)
1096
        if (GetModuleHandleW( module_cursors[i].name ) == module) break;
1097
    if (i == ARRAY_SIZE( module_cursors )) goto done;
1098 1099

    cursors = module_cursors[i].cursors;
1100 1101 1102
    for (i = 0; cursors[i].id; i++)
        if (cursors[i].id == info->wResID)
        {
1103 1104
            strcpy( valueA, cursors[i].names[0] );
            names = cursors[i].names;
1105 1106
            break;
        }
1107

1108 1109
done:
    if (valueA[0])
1110
    {
1111
#ifdef SONAME_LIBXCURSOR
1112 1113 1114 1115 1116 1117 1118
        if (pXcursorLibraryLoadCursor)
        {
            if (!names)
                cursor = pXcursorLibraryLoadCursor( gdi_display, valueA );
            else
                while (*names && !cursor) cursor = pXcursorLibraryLoadCursor( gdi_display, *names++ );
        }
1119 1120 1121 1122 1123 1124
#endif
        if (!cursor)
        {
            int shape = find_fallback_shape( valueA );
            if (shape != -1) cursor = XCreateFontCursor( gdi_display, shape );
        }
1125 1126
        if (!cursor) WARN( "no system cursor found for %s mapped to %s\n",
                           debugstr_w(name), debugstr_a(valueA) );
1127
    }
1128
    else WARN( "no system cursor found for %s\n", debugstr_w(name) );
1129 1130 1131
    return cursor;
}

1132

1133
/***********************************************************************
1134
 *		create_xlib_monochrome_cursor
1135
 *
1136
 * Create a monochrome X cursor from a Windows one.
1137
 */
1138
static Cursor create_xlib_monochrome_cursor( HDC hdc, const ICONINFOEXW *icon, int width, int height )
1139
{
1140 1141 1142 1143 1144 1145 1146 1147
    char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *info = (BITMAPINFO *)buffer;
    const int and_y = 0;
    const int xor_y = height;
    unsigned int width_bytes = (width + 31) / 32 * 4;
    unsigned char *mask_bits = NULL;
    GC gc;
    XColor fg, bg;
1148
    XVisualInfo vis = default_visual;
1149 1150
    Pixmap src_pixmap, bits_pixmap, mask_pixmap;
    struct gdi_image_bits bits;
1151 1152
    Cursor cursor = 0;

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info->bmiHeader.biWidth = width;
    info->bmiHeader.biHeight = -height * 2;
    info->bmiHeader.biPlanes = 1;
    info->bmiHeader.biBitCount = 1;
    info->bmiHeader.biCompression = BI_RGB;
    info->bmiHeader.biSizeImage = width_bytes * height * 2;
    info->bmiHeader.biXPelsPerMeter = 0;
    info->bmiHeader.biYPelsPerMeter = 0;
    info->bmiHeader.biClrUsed = 0;
    info->bmiHeader.biClrImportant = 0;

    if (!(mask_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
    if (!GetDIBits( hdc, icon->hbmMask, 0, height * 2, mask_bits, info, DIB_RGB_COLORS )) goto done;

    vis.depth = 1;
    bits.ptr = mask_bits;
    bits.free = NULL;
    bits.is_copy = TRUE;
    if (!(src_pixmap = create_pixmap_from_image( hdc, &vis, info, &bits, DIB_RGB_COLORS ))) goto done;
1173

1174 1175 1176 1177
    bits_pixmap = XCreatePixmap( gdi_display, root_window, width, height, 1 );
    mask_pixmap = XCreatePixmap( gdi_display, root_window, width, height, 1 );
    gc = XCreateGC( gdi_display, src_pixmap, 0, NULL );
    XSetGraphicsExposures( gdi_display, gc, False );
1178 1179 1180 1181 1182

    /* We have to do some magic here, as cursors are not fully
     * compatible between Windows and X11. Under X11, there are
     * only 3 possible color cursor: black, white and masked. So
     * we map the 4th Windows color (invert the bits on the screen)
1183
     * to black and an additional white bit on another place
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
     * (+1,+1). This require some boolean arithmetic:
     *
     *         Windows          |          X11
     * And    Xor      Result   |   Bits     Mask     Result
     *  0      0     black      |    0        1     background
     *  0      1     white      |    1        1     foreground
     *  1      0     no change  |    X        0     no change
     *  1      1     inverted   |    0        1     background
     *
     * which gives:
     *  Bits = not 'And' and 'Xor' or 'And2' and 'Xor2'
     *  Mask = not 'And' or 'Xor' or 'And2' and 'Xor2'
     */
1197 1198 1199 1200 1201 1202 1203
    XSetFunction( gdi_display, gc, GXcopy );
    XCopyArea( gdi_display, src_pixmap, bits_pixmap, gc, 0, and_y, width, height, 0, 0 );
    XCopyArea( gdi_display, src_pixmap, mask_pixmap, gc, 0, and_y, width, height, 0, 0 );
    XSetFunction( gdi_display, gc, GXandReverse );
    XCopyArea( gdi_display, src_pixmap, bits_pixmap, gc, 0, xor_y, width, height, 0, 0 );
    XSetFunction( gdi_display, gc, GXorReverse );
    XCopyArea( gdi_display, src_pixmap, mask_pixmap, gc, 0, xor_y, width, height, 0, 0 );
1204
    /* additional white */
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    XSetFunction( gdi_display, gc, GXand );
    XCopyArea( gdi_display, src_pixmap, src_pixmap,  gc, 0, xor_y, width, height, 0, and_y );
    XSetFunction( gdi_display, gc, GXor );
    XCopyArea( gdi_display, src_pixmap, mask_pixmap, gc, 0, and_y, width, height, 1, 1 );
    XCopyArea( gdi_display, src_pixmap, bits_pixmap, gc, 0, and_y, width, height, 1, 1 );
    XFreeGC( gdi_display, gc );

    fg.red = fg.green = fg.blue = 0xffff;
    bg.red = bg.green = bg.blue = 0;
    cursor = XCreatePixmapCursor( gdi_display, bits_pixmap, mask_pixmap,
                                  &fg, &bg, icon->xHotspot, icon->yHotspot );
    XFreePixmap( gdi_display, src_pixmap );
    XFreePixmap( gdi_display, bits_pixmap );
    XFreePixmap( gdi_display, mask_pixmap );
1219 1220

done:
1221
    HeapFree( GetProcessHeap(), 0, mask_bits );
1222 1223 1224
    return cursor;
}

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
/***********************************************************************
 *		create_xlib_load_mono_cursor
 *
 * Create a monochrome X cursor from a color Windows one by trying to load the monochrome resource.
 */
static Cursor create_xlib_load_mono_cursor( HDC hdc, HANDLE handle, int width, int height )
{
    Cursor cursor = None;
    HANDLE mono;
    ICONINFOEXW info;
    BITMAP bm;

    if (!(mono = CopyImage( handle, IMAGE_CURSOR, width, height, LR_MONOCHROME | LR_COPYFROMRESOURCE )))
        return None;

    info.cbSize = sizeof(info);
    if (GetIconInfoExW( mono, &info ))
    {
        if (!info.hbmColor)
        {
            GetObjectW( info.hbmMask, sizeof(bm), &bm );
            bm.bmHeight = max( 1, bm.bmHeight / 2 );
            /* make sure hotspot is valid */
            if (info.xHotspot >= bm.bmWidth || info.yHotspot >= bm.bmHeight)
            {
                info.xHotspot = bm.bmWidth / 2;
                info.yHotspot = bm.bmHeight / 2;
            }
            cursor = create_xlib_monochrome_cursor( hdc, &info, bm.bmWidth, bm.bmHeight );
        }
        else DeleteObject( info.hbmColor );
        DeleteObject( info.hbmMask );
    }
    DestroyCursor( mono );
    return cursor;
}

1262
/***********************************************************************
1263
 *		create_xlib_color_cursor
1264
 *
1265
 * Create a color X cursor from a Windows one.
1266
 */
1267
static Cursor create_xlib_color_cursor( HDC hdc, const ICONINFOEXW *icon, int width, int height )
1268
{
1269 1270
    char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *info = (BITMAPINFO *)buffer;
1271 1272
    XColor fg, bg;
    Cursor cursor = None;
1273
    XVisualInfo vis = default_visual;
1274 1275
    Pixmap xor_pixmap, mask_pixmap;
    struct gdi_image_bits bits;
1276 1277
    unsigned int *color_bits = NULL, *ptr;
    unsigned char *mask_bits = NULL, *xor_bits = NULL;
1278 1279
    int i, x, y;
    BOOL has_alpha = FALSE;
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    int rfg, gfg, bfg, rbg, gbg, bbg, fgBits, bgBits;
    unsigned int width_bytes = (width + 31) / 32 * 4;

    info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info->bmiHeader.biWidth = width;
    info->bmiHeader.biHeight = -height;
    info->bmiHeader.biPlanes = 1;
    info->bmiHeader.biBitCount = 1;
    info->bmiHeader.biCompression = BI_RGB;
    info->bmiHeader.biSizeImage = width_bytes * height;
    info->bmiHeader.biXPelsPerMeter = 0;
    info->bmiHeader.biYPelsPerMeter = 0;
    info->bmiHeader.biClrUsed = 0;
    info->bmiHeader.biClrImportant = 0;
1294

1295 1296
    if (!(mask_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
    if (!GetDIBits( hdc, icon->hbmMask, 0, height, mask_bits, info, DIB_RGB_COLORS )) goto done;
1297

1298 1299 1300 1301 1302
    info->bmiHeader.biBitCount = 32;
    info->bmiHeader.biSizeImage = width * height * 4;
    if (!(color_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto done;
    if (!(xor_bits = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, width_bytes * height ))) goto done;
    GetDIBits( hdc, icon->hbmColor, 0, height, color_bits, info, DIB_RGB_COLORS );
1303

1304
    /* compute fg/bg color and xor bitmap based on average of the color values */
1305

1306 1307 1308 1309
    rfg = gfg = bfg = rbg = gbg = bbg = fgBits = 0;
    for (y = 0, ptr = color_bits; y < height; y++)
    {
        for (x = 0; x < width; x++, ptr++)
1310
        {
1311 1312 1313 1314
            int red   = (*ptr >> 16) & 0xff;
            int green = (*ptr >> 8) & 0xff;
            int blue  = (*ptr >> 0) & 0xff;
            if (red + green + blue > 0x40)
1315
            {
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
                rfg += red;
                gfg += green;
                bfg += blue;
                fgBits++;
                xor_bits[y * width_bytes + x / 8] |= 0x80 >> (x % 8);
            }
            else
            {
                rbg += red;
                gbg += green;
                bbg += blue;
1327
            }
1328
        }
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    }
    if (fgBits)
    {
        fg.red   = rfg * 257 / fgBits;
        fg.green = gfg * 257 / fgBits;
        fg.blue  = bfg * 257 / fgBits;
    }
    else fg.red = fg.green = fg.blue = 0;
    bgBits = width * height - fgBits;
    if (bgBits)
    {
        bg.red   = rbg * 257 / bgBits;
        bg.green = gbg * 257 / bgBits;
        bg.blue  = bbg * 257 / bgBits;
    }
    else bg.red = bg.green = bg.blue = 0;
1345

1346
    info->bmiHeader.biBitCount = 1;
1347
    info->bmiHeader.biClrUsed = 0;
1348 1349 1350 1351 1352 1353
    info->bmiHeader.biSizeImage = width_bytes * height;

    /* generate mask from the alpha channel if we have one */

    for (i = 0, ptr = color_bits; i < width * height; i++, ptr++)
        if ((has_alpha = (*ptr & 0xff000000) != 0)) break;
1354

1355 1356 1357 1358 1359 1360 1361
    if (has_alpha)
    {
        memset( mask_bits, 0, width_bytes * height );
        for (y = 0, ptr = color_bits; y < height; y++)
            for (x = 0; x < width; x++, ptr++)
                if ((*ptr >> 24) > 25) /* more than 10% alpha */
                    mask_bits[y * width_bytes + x / 8] |= 0x80 >> (x % 8);
1362 1363 1364
    }
    else  /* invert the mask */
    {
1365 1366
        unsigned int j;

1367
        ptr = (unsigned int *)mask_bits;
1368
        for (j = 0; j < info->bmiHeader.biSizeImage / sizeof(*ptr); j++, ptr++) *ptr ^= ~0u;
1369
    }
1370

1371 1372 1373 1374 1375
    vis.depth = 1;
    bits.ptr = xor_bits;
    bits.free = NULL;
    bits.is_copy = TRUE;
    if (!(xor_pixmap = create_pixmap_from_image( hdc, &vis, info, &bits, DIB_RGB_COLORS ))) goto done;
1376

1377 1378 1379 1380
    bits.ptr = mask_bits;
    mask_pixmap = create_pixmap_from_image( hdc, &vis, info, &bits, DIB_RGB_COLORS );

    if (mask_pixmap)
1381
    {
1382 1383 1384
        cursor = XCreatePixmapCursor( gdi_display, xor_pixmap, mask_pixmap,
                                      &fg, &bg, icon->xHotspot, icon->yHotspot );
        XFreePixmap( gdi_display, mask_pixmap );
1385
    }
1386
    XFreePixmap( gdi_display, xor_pixmap );
1387 1388 1389 1390 1391

done:
    HeapFree( GetProcessHeap(), 0, color_bits );
    HeapFree( GetProcessHeap(), 0, xor_bits );
    HeapFree( GetProcessHeap(), 0, mask_bits );
1392 1393
    return cursor;
}
1394

1395 1396 1397 1398 1399
/***********************************************************************
 *		create_cursor
 *
 * Create an X cursor from a Windows one.
 */
1400
static Cursor create_cursor( HANDLE handle )
1401
{
1402
    Cursor cursor = 0;
1403
    ICONINFOEXW info;
1404
    BITMAP bm;
1405
    HDC hdc;
1406 1407 1408

    if (!handle) return get_empty_cursor();

1409
    info.cbSize = sizeof(info);
1410
    if (!GetIconInfoExW( handle, &info )) return 0;
1411

1412 1413 1414 1415 1416 1417 1418
    if (use_system_cursors && (cursor = create_xcursor_system_cursor( &info )))
    {
        DeleteObject( info.hbmColor );
        DeleteObject( info.hbmMask );
        return cursor;
    }

1419
    GetObjectW( info.hbmMask, sizeof(bm), &bm );
1420
    if (!info.hbmColor) bm.bmHeight = max( 1, bm.bmHeight / 2 );
1421 1422 1423 1424 1425 1426 1427 1428

    /* make sure hotspot is valid */
    if (info.xHotspot >= bm.bmWidth || info.yHotspot >= bm.bmHeight)
    {
        info.xHotspot = bm.bmWidth / 2;
        info.yHotspot = bm.bmHeight / 2;
    }

1429 1430
    hdc = CreateCompatibleDC( 0 );

1431 1432
    if (info.hbmColor)
    {
1433
#ifdef SONAME_LIBXCURSOR
1434 1435
        if (pXcursorImagesLoadCursor)
            cursor = create_xcursor_cursor( hdc, &info, handle, bm.bmWidth, bm.bmHeight );
1436
#endif
1437
        if (!cursor) cursor = create_xlib_load_mono_cursor( hdc, handle, bm.bmWidth, bm.bmHeight );
1438
        if (!cursor) cursor = create_xlib_color_cursor( hdc, &info, bm.bmWidth, bm.bmHeight );
1439 1440 1441
        DeleteObject( info.hbmColor );
    }
    else
1442
    {
1443
        cursor = create_xlib_monochrome_cursor( hdc, &info, bm.bmWidth, bm.bmHeight );
1444
    }
1445

1446
    DeleteObject( info.hbmMask );
1447
    DeleteDC( hdc );
1448 1449 1450
    return cursor;
}

1451 1452 1453 1454 1455 1456 1457
/***********************************************************************
 *		DestroyCursorIcon (X11DRV.@)
 */
void CDECL X11DRV_DestroyCursorIcon( HCURSOR handle )
{
    Cursor cursor;

1458
    if (!XFindContext( gdi_display, (XID)handle, cursor_context, (char **)&cursor ))
1459 1460 1461 1462 1463 1464
    {
        TRACE( "%p xid %lx\n", handle, cursor );
        XFreeCursor( gdi_display, cursor );
        XDeleteContext( gdi_display, (XID)handle, cursor_context );
    }
}
1465 1466

/***********************************************************************
1467
 *		SetCursor (X11DRV.@)
1468
 */
1469
void CDECL X11DRV_SetCursor( HCURSOR handle )
1470
{
1471 1472 1473 1474
    if (InterlockedExchangePointer( (void **)&last_cursor, handle ) != handle ||
        GetTickCount() - last_cursor_change > 100)
    {
        last_cursor_change = GetTickCount();
1475
        if (cursor_window) SendNotifyMessageW( cursor_window, WM_X11DRV_SET_CURSOR, 0, (LPARAM)handle );
1476
    }
1477 1478 1479
}

/***********************************************************************
1480
 *		SetCursorPos (X11DRV.@)
1481
 */
1482
BOOL CDECL X11DRV_SetCursorPos( INT x, INT y )
1483
{
1484
    struct x11drv_thread_data *data = x11drv_init_thread_data();
1485
    POINT pos = virtual_screen_to_root( x, y );
1486

1487 1488 1489 1490 1491 1492
    if (keyboard_grabbed)
    {
        WARN( "refusing to warp to %u, %u\n", pos.x, pos.y );
        return FALSE;
    }

1493 1494 1495
    if (!clipping_cursor &&
        XGrabPointer( data->display, root_window, False,
                      PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
1496
                      GrabModeAsync, GrabModeAsync, None, None, CurrentTime ) != GrabSuccess)
1497 1498 1499 1500 1501
    {
        WARN( "refusing to warp pointer to %u, %u without exclusive grab\n", pos.x, pos.y );
        return FALSE;
    }

1502
    XWarpPointer( data->display, root_window, root_window, 0, 0, 0, 0, pos.x, pos.y );
1503
    data->warp_serial = NextRequest( data->display );
1504 1505 1506 1507

    if (!clipping_cursor)
        XUngrabPointer( data->display, CurrentTime );

1508
    XNoOp( data->display );
1509
    XFlush( data->display ); /* avoids bad mouse lag in games that do their own mouse warping */
1510
    TRACE( "warped to %d,%d serial %lu\n", x, y, data->warp_serial );
1511
    return TRUE;
1512 1513 1514 1515 1516
}

/***********************************************************************
 *		GetCursorPos (X11DRV.@)
 */
1517
BOOL CDECL X11DRV_GetCursorPos(LPPOINT pos)
1518
{
1519
    Display *display = thread_init_display();
1520 1521 1522
    Window root, child;
    int rootX, rootY, winX, winY;
    unsigned int xstate;
1523
    BOOL ret;
1524

1525 1526
    ret = XQueryPointer( display, root_window, &root, &child, &rootX, &rootY, &winX, &winY, &xstate );
    if (ret)
1527
    {
1528
        POINT old = *pos;
1529
        *pos = root_to_virtual_screen( winX, winY );
1530
        TRACE( "pointer at %s server pos %s\n", wine_dbgstr_point(pos), wine_dbgstr_point(&old) );
1531
    }
1532
    return ret;
1533 1534
}

1535 1536 1537 1538 1539
/***********************************************************************
 *		ClipCursor (X11DRV.@)
 */
BOOL CDECL X11DRV_ClipCursor( LPCRECT clip )
{
1540 1541 1542
    RECT virtual_rect = get_virtual_screen_rect();

    if (!clip) clip = &virtual_rect;
1543

1544
    if (grab_pointer)
1545
    {
1546
        HWND foreground = GetForegroundWindow();
1547 1548 1549 1550 1551 1552 1553
        DWORD tid, pid;

        /* forward request to the foreground window if it's in a different thread */
        tid = GetWindowThreadProcessId( foreground, &pid );
        if (tid && tid != GetCurrentThreadId() && pid == GetCurrentProcessId())
        {
            TRACE( "forwarding clip request to %p\n", foreground );
1554
            SendNotifyMessageW( foreground, WM_X11DRV_CLIP_CURSOR_REQUEST, FALSE, FALSE );
1555 1556
            return TRUE;
        }
1557

1558
        /* we are clipping if the clip rectangle is smaller than the screen */
1559 1560
        if (clip->left > virtual_rect.left || clip->right < virtual_rect.right ||
            clip->top > virtual_rect.top || clip->bottom < virtual_rect.bottom)
1561
        {
1562
            if (grab_clipping_window( clip )) return TRUE;
1563 1564 1565 1566
        }
        else /* if currently clipping, check if we should switch to fullscreen clipping */
        {
            struct x11drv_thread_data *data = x11drv_thread_data();
1567 1568 1569 1570 1571
            if (data && data->clip_hwnd)
            {
                if (EqualRect( clip, &clip_rect ) || clip_fullscreen_window( foreground, TRUE ))
                    return TRUE;
            }
1572
        }
1573
    }
1574
    ungrab_clipping_window();
1575 1576
    return TRUE;
}
1577

1578 1579 1580 1581 1582
/***********************************************************************
 *             clip_cursor_request
 *
 * Function called upon receiving a WM_X11DRV_CLIP_CURSOR_REQUEST.
 */
1583
LRESULT clip_cursor_request( HWND hwnd, BOOL fullscreen, BOOL reset )
1584 1585 1586 1587 1588 1589 1590
{
    RECT clip;

    if (hwnd == GetDesktopWindow())
        WARN( "ignoring clip cursor request on desktop window.\n" );
    else if (hwnd != GetForegroundWindow())
        WARN( "ignoring clip cursor request on non-foreground window.\n" );
1591 1592
    else if (fullscreen)
        clip_fullscreen_window( hwnd, reset );
1593 1594 1595 1596 1597 1598 1599 1600 1601
    else
    {
        GetClipCursor( &clip );
        X11DRV_ClipCursor( &clip );
    }

    return 0;
}

1602 1603 1604
/***********************************************************************
 *           move_resize_window
 */
1605
void move_resize_window( HWND hwnd, int dir )
1606
{
1607
    Display *display = thread_display();
1608
    DWORD pt;
1609 1610
    POINT pos;
    int button = 0;
1611
    XEvent xev;
1612
    Window win, root, child;
1613
    unsigned int xstate;
1614

1615 1616
    if (!(win = X11DRV_get_whole_window( hwnd ))) return;

1617
    pt = GetMessagePos();
1618
    pos = virtual_screen_to_root( (short)LOWORD( pt ), (short)HIWORD( pt ) );
1619 1620 1621 1622 1623

    if (GetKeyState( VK_LBUTTON ) & 0x8000) button = 1;
    else if (GetKeyState( VK_MBUTTON ) & 0x8000) button = 2;
    else if (GetKeyState( VK_RBUTTON ) & 0x8000) button = 3;

1624
    TRACE( "hwnd %p/%lx, pos %s, dir %d, button %d\n", hwnd, win, wine_dbgstr_point(&pos), dir, button );
1625 1626

    xev.xclient.type = ClientMessage;
1627
    xev.xclient.window = win;
1628 1629 1630 1631 1632
    xev.xclient.message_type = x11drv_atom(_NET_WM_MOVERESIZE);
    xev.xclient.serial = 0;
    xev.xclient.display = display;
    xev.xclient.send_event = True;
    xev.xclient.format = 32;
1633 1634
    xev.xclient.data.l[0] = pos.x; /* x coord */
    xev.xclient.data.l[1] = pos.y; /* y coord */
1635 1636 1637 1638 1639 1640 1641 1642
    xev.xclient.data.l[2] = dir; /* direction */
    xev.xclient.data.l[3] = button; /* button */
    xev.xclient.data.l[4] = 0; /* unused */

    /* need to ungrab the pointer that may have been automatically grabbed
     * with a ButtonPress event */
    XUngrabPointer( display, CurrentTime );
    XSendEvent(display, root_window, False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
1643 1644 1645 1646 1647

    /* try to detect the end of the size/move by polling for the mouse button to be released */
    /* (some apps don't like it if we return before the size/move is done) */

    if (!button) return;
1648 1649
    SendMessageW( hwnd, WM_ENTERSIZEMOVE, 0, 0 );

1650 1651 1652 1653
    for (;;)
    {
        MSG msg;
        INPUT input;
1654
        int x, y, rootX, rootY;
1655

1656
        if (!XQueryPointer( display, root_window, &root, &child, &rootX, &rootY, &x, &y, &xstate )) break;
1657 1658 1659 1660

        if (!(xstate & (Button1Mask << (button - 1))))
        {
            /* fake a button release event */
1661
            pos = root_to_virtual_screen( x, y );
1662
            input.type = INPUT_MOUSE;
1663 1664
            input.u.mi.dx          = pos.x;
            input.u.mi.dy          = pos.y;
1665 1666 1667 1668
            input.u.mi.mouseData   = button_up_data[button - 1];
            input.u.mi.dwFlags     = button_up_flags[button - 1] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
            input.u.mi.time        = GetTickCount();
            input.u.mi.dwExtraInfo = 0;
1669
            __wine_send_input( hwnd, &input, NULL );
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
        }

        while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE ))
        {
            if (!CallMsgFilterW( &msg, MSGF_SIZE ))
            {
                TranslateMessage( &msg );
                DispatchMessageW( &msg );
            }
        }

        if (!(xstate & (Button1Mask << (button - 1)))) break;
        MsgWaitForMultipleObjects( 0, NULL, FALSE, 100, QS_ALLINPUT );
    }

1685
    TRACE( "hwnd %p/%lx done\n", hwnd, win );
1686
    SendMessageW( hwnd, WM_EXITSIZEMOVE, 0, 0 );
1687 1688 1689
}


1690 1691 1692
/***********************************************************************
 *           X11DRV_ButtonPress
 */
1693
BOOL X11DRV_ButtonPress( HWND hwnd, XEvent *xev )
1694
{
1695
    XButtonEvent *event = &xev->xbutton;
1696
    int buttonNum = event->button - 1;
1697
    INPUT input;
1698

1699
    if (buttonNum >= NB_BUTTONS) return FALSE;
1700

1701 1702 1703 1704 1705 1706 1707 1708
    TRACE( "hwnd %p/%lx button %u pos %d,%d\n", hwnd, event->window, buttonNum, event->x, event->y );

    input.u.mi.dx          = event->x;
    input.u.mi.dy          = event->y;
    input.u.mi.mouseData   = button_down_data[buttonNum];
    input.u.mi.dwFlags     = button_down_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
    input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
    input.u.mi.dwExtraInfo = 0;
1709

1710
    update_user_time( event->time );
1711
    map_event_coords( hwnd, event->window, event->root, event->x_root, event->y_root, &input );
1712
    send_mouse_input( hwnd, event->window, event->state, &input );
1713
    return TRUE;
1714 1715
}

1716

1717
/***********************************************************************
1718
 *           X11DRV_ButtonRelease
1719
 */
1720
BOOL X11DRV_ButtonRelease( HWND hwnd, XEvent *xev )
1721
{
1722
    XButtonEvent *event = &xev->xbutton;
1723
    int buttonNum = event->button - 1;
1724
    INPUT input;
1725

1726
    if (buttonNum >= NB_BUTTONS || !button_up_flags[buttonNum]) return FALSE;
1727

1728 1729 1730 1731 1732 1733 1734 1735
    TRACE( "hwnd %p/%lx button %u pos %d,%d\n", hwnd, event->window, buttonNum, event->x, event->y );

    input.u.mi.dx          = event->x;
    input.u.mi.dy          = event->y;
    input.u.mi.mouseData   = button_up_data[buttonNum];
    input.u.mi.dwFlags     = button_up_flags[buttonNum] | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
    input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
    input.u.mi.dwExtraInfo = 0;
1736

1737
    map_event_coords( hwnd, event->window, event->root, event->x_root, event->y_root, &input );
1738
    send_mouse_input( hwnd, event->window, event->state, &input );
1739
    return TRUE;
1740
}
1741 1742


1743 1744 1745
/***********************************************************************
 *           X11DRV_MotionNotify
 */
1746
BOOL X11DRV_MotionNotify( HWND hwnd, XEvent *xev )
1747
{
1748
    XMotionEvent *event = &xev->xmotion;
1749
    INPUT input;
1750

1751 1752
    TRACE( "hwnd %p/%lx pos %d,%d is_hint %d serial %lu\n",
           hwnd, event->window, event->x, event->y, event->is_hint, event->serial );
1753

1754 1755 1756 1757 1758 1759 1760
    input.u.mi.dx          = event->x;
    input.u.mi.dy          = event->y;
    input.u.mi.mouseData   = 0;
    input.u.mi.dwFlags     = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
    input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
    input.u.mi.dwExtraInfo = 0;

1761
    if (!hwnd && is_old_motion_event( event->serial ))
1762
    {
1763
        TRACE( "pos %d,%d old serial %lu, ignoring\n", input.u.mi.dx, input.u.mi.dy, event->serial );
1764
        return FALSE;
1765
    }
1766
    map_event_coords( hwnd, event->window, event->root, event->x_root, event->y_root, &input );
1767
    send_mouse_input( hwnd, event->window, event->state, &input );
1768
    return TRUE;
1769 1770 1771 1772 1773 1774
}


/***********************************************************************
 *           X11DRV_EnterNotify
 */
1775
BOOL X11DRV_EnterNotify( HWND hwnd, XEvent *xev )
1776
{
1777
    XCrossingEvent *event = &xev->xcrossing;
1778
    INPUT input;
1779

1780
    TRACE( "hwnd %p/%lx pos %d,%d detail %d\n", hwnd, event->window, event->x, event->y, event->detail );
1781

1782 1783
    if (event->detail == NotifyVirtual) return FALSE;
    if (hwnd == x11drv_thread_data()->grab_hwnd) return FALSE;
1784 1785

    /* simulate a mouse motion event */
1786 1787 1788 1789 1790 1791 1792
    input.u.mi.dx          = event->x;
    input.u.mi.dy          = event->y;
    input.u.mi.mouseData   = 0;
    input.u.mi.dwFlags     = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
    input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
    input.u.mi.dwExtraInfo = 0;

1793 1794 1795
    if (is_old_motion_event( event->serial ))
    {
        TRACE( "pos %d,%d old serial %lu, ignoring\n", input.u.mi.dx, input.u.mi.dy, event->serial );
1796
        return FALSE;
1797
    }
1798
    map_event_coords( hwnd, event->window, event->root, event->x_root, event->y_root, &input );
1799
    send_mouse_input( hwnd, event->window, event->state, &input );
1800
    return TRUE;
1801
}
1802 1803 1804

#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H

1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
/***********************************************************************
 *           X11DRV_DeviceChanged
 */
static BOOL X11DRV_DeviceChanged( XGenericEventCookie *xev )
{
    XIDeviceChangedEvent *event = xev->data;
    struct x11drv_thread_data *data = x11drv_thread_data();

    if (event->deviceid != data->xi2_core_pointer) return FALSE;
    if (event->reason != XISlaveSwitch) return FALSE;

    update_relative_valuators( event->classes, event->num_classes );
    data->xi2_current_slave = event->sourceid;
    return TRUE;
}

1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
static BOOL map_raw_event_coords( XIRawEvent *event, INPUT *input )
{
    struct x11drv_thread_data *thread_data = x11drv_thread_data();
    XIValuatorClassInfo *x = &thread_data->x_valuator, *y = &thread_data->y_valuator;
    double x_value = 0, y_value = 0, x_scale, y_scale;
    const double *values = event->valuators.values;
    RECT virtual_rect;
    int i;

    if (x->number < 0 || y->number < 0) return FALSE;
    if (!event->valuators.mask_len) return FALSE;
    if (thread_data->xi2_state != xi_enabled) return FALSE;

    /* If there is no slave currently detected, no previous motion nor device
     * change events were received. Look it up now on the device list in this
     * case.
     */
    if (!thread_data->xi2_current_slave)
    {
        XIDeviceInfo *devices = thread_data->xi2_devices;

        for (i = 0; i < thread_data->xi2_device_count; i++)
        {
            if (devices[i].use != XISlavePointer) continue;
            if (devices[i].deviceid != event->deviceid) continue;
            if (devices[i].attachment != thread_data->xi2_core_pointer) continue;
            thread_data->xi2_current_slave = event->deviceid;
            break;
        }
    }
    if (event->deviceid != thread_data->xi2_current_slave) return FALSE;

    virtual_rect = get_virtual_screen_rect();

    if (x->max <= x->min) x_scale = 1;
    else x_scale = (virtual_rect.right - virtual_rect.left) / (x->max - x->min);
    if (y->max <= y->min) y_scale = 1;
    else y_scale = (virtual_rect.bottom - virtual_rect.top) / (y->max - y->min);

    for (i = 0; i <= max( x->number, y->number ); i++)
    {
        if (!XIMaskIsSet( event->valuators.mask, i )) continue;
        if (i == x->number)
        {
            x_value = *values;
            x->value += x_value * x_scale;
        }
        if (i == y->number)
        {
            y_value = *values;
            y->value += y_value * y_scale;
        }
        values++;
    }

    input->u.mi.dx = round( x->value );
    input->u.mi.dy = round( y->value );

    TRACE( "event %f,%f value %f,%f input %d,%d\n", x_value, y_value, x->value, y->value, input->u.mi.dx, input->u.mi.dy );

    x->value -= input->u.mi.dx;
    y->value -= input->u.mi.dy;

    if (!input->u.mi.dx && !input->u.mi.dy)
    {
        TRACE( "accumulating motion\n" );
        return FALSE;
    }

    return TRUE;
}

1893 1894 1895
/***********************************************************************
 *           X11DRV_RawMotion
 */
1896
static BOOL X11DRV_RawMotion( XGenericEventCookie *xev )
1897
{
1898
    XIRawEvent *event = xev->data;
1899 1900
    INPUT input;

1901
    if (broken_rawevents && is_old_motion_event( xev->serial ))
1902
    {
1903 1904
        TRACE( "old serial %lu, ignoring\n", xev->serial );
        return FALSE;
1905 1906
    }

1907
    input.type = INPUT_MOUSE;
1908 1909 1910 1911
    input.u.mi.mouseData   = 0;
    input.u.mi.dwFlags     = MOUSEEVENTF_MOVE;
    input.u.mi.time        = EVENT_x11_time_to_win32_time( event->time );
    input.u.mi.dwExtraInfo = 0;
1912 1913
    input.u.mi.dx          = 0;
    input.u.mi.dy          = 0;
1914
    if (!map_raw_event_coords( event, &input )) return FALSE;
1915

1916
    __wine_send_input( 0, &input, NULL );
1917
    return TRUE;
1918 1919 1920 1921 1922
}

#endif /* HAVE_X11_EXTENSIONS_XINPUT2_H */


1923 1924 1925 1926 1927 1928 1929
/***********************************************************************
 *              X11DRV_XInput2_Init
 */
void X11DRV_XInput2_Init(void)
{
#if defined(SONAME_LIBXI) && defined(HAVE_X11_EXTENSIONS_XINPUT2_H)
    int event, error;
1930
    void *libxi_handle = dlopen( SONAME_LIBXI, RTLD_NOW );
1931 1932 1933 1934 1935 1936 1937

    if (!libxi_handle)
    {
        WARN( "couldn't load %s\n", SONAME_LIBXI );
        return;
    }
#define LOAD_FUNCPTR(f) \
1938
    if (!(p##f = dlsym( libxi_handle, #f))) \
1939 1940 1941 1942 1943
    { \
        WARN("Failed to load %s.\n", #f); \
        return; \
    }

1944
    LOAD_FUNCPTR(XIGetClientPointer);
1945 1946 1947 1948 1949 1950 1951
    LOAD_FUNCPTR(XIFreeDeviceInfo);
    LOAD_FUNCPTR(XIQueryDevice);
    LOAD_FUNCPTR(XIQueryVersion);
    LOAD_FUNCPTR(XISelectEvents);
#undef LOAD_FUNCPTR

    xinput2_available = XQueryExtension( gdi_display, "XInputExtension", &xinput2_opcode, &event, &error );
1952 1953 1954 1955 1956 1957

    /* Until version 1.10.4 rawinput was broken in XOrg, see
     * https://bugs.freedesktop.org/show_bug.cgi?id=30068 */
    broken_rawevents  = strstr(XServerVendor( gdi_display ), "X.Org") &&
                        XVendorRelease( gdi_display ) < 11004000;

1958 1959 1960 1961 1962 1963
#else
    TRACE( "X Input 2 support not compiled in.\n" );
#endif
}


1964 1965 1966
/***********************************************************************
 *           X11DRV_GenericEvent
 */
1967
BOOL X11DRV_GenericEvent( HWND hwnd, XEvent *xev )
1968
{
1969
    BOOL ret = FALSE;
1970 1971 1972
#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
    XGenericEventCookie *event = &xev->xcookie;

1973 1974
    if (!event->data) return FALSE;
    if (event->extension != xinput2_opcode) return FALSE;
1975 1976 1977

    switch (event->evtype)
    {
1978 1979 1980
    case XI_DeviceChanged:
        ret = X11DRV_DeviceChanged( event );
        break;
1981
    case XI_RawMotion:
1982
        ret = X11DRV_RawMotion( event );
1983 1984 1985 1986 1987 1988 1989
        break;

    default:
        TRACE( "Unhandled event %#x\n", event->evtype );
        break;
    }
#endif
1990
    return ret;
1991
}