event.c 56.7 KB
Newer Older
1
/*
2
 * X11 event driver
3 4
 *
 * Copyright 1993 Alexandre Julliard
5
 *	     1999 Noel Borthwick
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 <poll.h>
25 26
#include <X11/Xatom.h>
#include <X11/keysym.h>
27
#include <X11/Xlib.h>
28 29
#include <X11/Xresource.h>
#include <X11/Xutil.h>
30 31 32
#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
#include <X11/extensions/XInput2.h>
#endif
33

34
#include <assert.h>
35
#include <stdarg.h>
36
#include <string.h>
37

38 39
#include "windef.h"
#include "winbase.h"
40

41
#include "x11drv.h"
42 43 44 45

/* avoid conflict with field names in included win32 headers */
#undef Status
#include "shlobj.h"  /* DROPFILES */
46
#include "shellapi.h"
47

48
#include "wine/server.h"
49
#include "wine/debug.h"
50

51
WINE_DEFAULT_DEBUG_CHANNEL(event);
52

53 54
extern BOOL ximInComposeMode;

55 56 57 58 59 60 61 62 63 64 65 66 67 68
#define DndNotDnd       -1    /* OffiX drag&drop */
#define DndUnknown      0
#define DndRawData      1
#define DndFile         2
#define DndFiles        3
#define DndText         4
#define DndDir          5
#define DndLink         6
#define DndExe          7

#define DndEND          8

#define DndURL          128   /* KDE drag&drop */

69 70 71 72 73 74 75 76 77 78 79 80 81 82
#define XEMBED_EMBEDDED_NOTIFY        0
#define XEMBED_WINDOW_ACTIVATE        1
#define XEMBED_WINDOW_DEACTIVATE      2
#define XEMBED_REQUEST_FOCUS          3
#define XEMBED_FOCUS_IN               4
#define XEMBED_FOCUS_OUT              5
#define XEMBED_FOCUS_NEXT             6
#define XEMBED_FOCUS_PREV             7
#define XEMBED_MODALITY_ON            10
#define XEMBED_MODALITY_OFF           11
#define XEMBED_REGISTER_ACCELERATOR   12
#define XEMBED_UNREGISTER_ACCELERATOR 13
#define XEMBED_ACTIVATE_ACCELERATOR   14

83 84 85
Bool (*pXGetEventData)( Display *display, XEvent /*XGenericEventCookie*/ *event ) = NULL;
void (*pXFreeEventData)( Display *display, XEvent /*XGenericEventCookie*/ *event ) = NULL;

86
  /* Event handlers */
87 88 89 90 91 92 93 94 95 96
static BOOL X11DRV_FocusIn( HWND hwnd, XEvent *event );
static BOOL X11DRV_FocusOut( HWND hwnd, XEvent *event );
static BOOL X11DRV_Expose( HWND hwnd, XEvent *event );
static BOOL X11DRV_MapNotify( HWND hwnd, XEvent *event );
static BOOL X11DRV_UnmapNotify( HWND hwnd, XEvent *event );
static BOOL X11DRV_ReparentNotify( HWND hwnd, XEvent *event );
static BOOL X11DRV_ConfigureNotify( HWND hwnd, XEvent *event );
static BOOL X11DRV_PropertyNotify( HWND hwnd, XEvent *event );
static BOOL X11DRV_ClientMessage( HWND hwnd, XEvent *event );
static BOOL X11DRV_GravityNotify( HWND hwnd, XEvent *event );
97

98
#define MAX_EVENT_HANDLERS 128
99

100
static x11drv_event_handler handlers[MAX_EVENT_HANDLERS] =
101
{
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    NULL,                     /*  0 reserved */
    NULL,                     /*  1 reserved */
    X11DRV_KeyEvent,          /*  2 KeyPress */
    X11DRV_KeyEvent,          /*  3 KeyRelease */
    X11DRV_ButtonPress,       /*  4 ButtonPress */
    X11DRV_ButtonRelease,     /*  5 ButtonRelease */
    X11DRV_MotionNotify,      /*  6 MotionNotify */
    X11DRV_EnterNotify,       /*  7 EnterNotify */
    NULL,                     /*  8 LeaveNotify */
    X11DRV_FocusIn,           /*  9 FocusIn */
    X11DRV_FocusOut,          /* 10 FocusOut */
    X11DRV_KeymapNotify,      /* 11 KeymapNotify */
    X11DRV_Expose,            /* 12 Expose */
    NULL,                     /* 13 GraphicsExpose */
    NULL,                     /* 14 NoExpose */
    NULL,                     /* 15 VisibilityNotify */
    NULL,                     /* 16 CreateNotify */
    X11DRV_DestroyNotify,     /* 17 DestroyNotify */
    X11DRV_UnmapNotify,       /* 18 UnmapNotify */
    X11DRV_MapNotify,         /* 19 MapNotify */
    NULL,                     /* 20 MapRequest */
    X11DRV_ReparentNotify,    /* 21 ReparentNotify */
    X11DRV_ConfigureNotify,   /* 22 ConfigureNotify */
    NULL,                     /* 23 ConfigureRequest */
    X11DRV_GravityNotify,     /* 24 GravityNotify */
    NULL,                     /* 25 ResizeRequest */
    NULL,                     /* 26 CirculateNotify */
    NULL,                     /* 27 CirculateRequest */
    X11DRV_PropertyNotify,    /* 28 PropertyNotify */
    X11DRV_SelectionClear,    /* 29 SelectionClear */
    X11DRV_SelectionRequest,  /* 30 SelectionRequest */
    NULL,                     /* 31 SelectionNotify */
    NULL,                     /* 32 ColormapNotify */
    X11DRV_ClientMessage,     /* 33 ClientMessage */
    X11DRV_MappingNotify,     /* 34 MappingNotify */
137
    X11DRV_GenericEvent       /* 35 GenericEvent */
138
};
139

140 141 142 143 144 145 146 147 148 149
static const char * event_names[MAX_EVENT_HANDLERS] =
{
    NULL, NULL, "KeyPress", "KeyRelease", "ButtonPress", "ButtonRelease",
    "MotionNotify", "EnterNotify", "LeaveNotify", "FocusIn", "FocusOut",
    "KeymapNotify", "Expose", "GraphicsExpose", "NoExpose", "VisibilityNotify",
    "CreateNotify", "DestroyNotify", "UnmapNotify", "MapNotify", "MapRequest",
    "ReparentNotify", "ConfigureNotify", "ConfigureRequest", "GravityNotify", "ResizeRequest",
    "CirculateNotify", "CirculateRequest", "PropertyNotify", "SelectionClear", "SelectionRequest",
    "SelectionNotify", "ColormapNotify", "ClientMessage", "MappingNotify", "GenericEvent"
};
150

151 152 153
/* is someone else grabbing the keyboard, for example the WM, when manipulating the window */
BOOL keyboard_grabbed = FALSE;

154 155
int xinput2_opcode = 0;

156 157 158
/* return the name of an X event */
static const char *dbgstr_event( int type )
{
159
    if (type < MAX_EVENT_HANDLERS && event_names[type]) return event_names[type];
160
    return wine_dbg_sprintf( "Unknown event %d", type );
161 162
}

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
static inline void get_event_data( XEvent *event )
{
#if defined(GenericEvent) && defined(HAVE_XEVENT_XCOOKIE)
    if (event->xany.type != GenericEvent) return;
    if (!pXGetEventData || !pXGetEventData( event->xany.display, event )) event->xcookie.data = NULL;
#endif
}

static inline void free_event_data( XEvent *event )
{
#if defined(GenericEvent) && defined(HAVE_XEVENT_XCOOKIE)
    if (event->xany.type != GenericEvent) return;
    if (event->xcookie.data) pXFreeEventData( event->xany.display, event );
#endif
}
178

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
/***********************************************************************
 *           xembed_request_focus
 */
static void xembed_request_focus( Display *display, Window window, DWORD timestamp )
{
    XEvent xev;

    xev.xclient.type = ClientMessage;
    xev.xclient.window = window;
    xev.xclient.message_type = x11drv_atom(_XEMBED);
    xev.xclient.serial = 0;
    xev.xclient.display = display;
    xev.xclient.send_event = True;
    xev.xclient.format = 32;

    xev.xclient.data.l[0] = timestamp;
    xev.xclient.data.l[1] = XEMBED_REQUEST_FOCUS;
    xev.xclient.data.l[2] = 0;
    xev.xclient.data.l[3] = 0;
    xev.xclient.data.l[4] = 0;

    XSendEvent(display, window, False, NoEventMask, &xev);
    XFlush( display );
}

204 205 206 207 208 209
/***********************************************************************
 *           X11DRV_register_event_handler
 *
 * Register a handler for a given event type.
 * If already registered, overwrite the previous handler.
 */
210
void X11DRV_register_event_handler( int type, x11drv_event_handler handler, const char *name )
211
{
212
    assert( type < MAX_EVENT_HANDLERS );
213
    assert( !handlers[type] || handlers[type] == handler );
214 215 216
    handlers[type] = handler;
    event_names[type] = name;
    TRACE("registered handler %p for event %d %s\n", handler, type, debugstr_a(name) );
217
}
218 219


220 221 222 223 224
/***********************************************************************
 *           filter_event
 */
static Bool filter_event( Display *display, XEvent *event, char *arg )
{
225
    ULONG_PTR mask = (ULONG_PTR)arg;
226 227 228 229 230 231 232 233

    if ((mask & QS_ALLINPUT) == QS_ALLINPUT) return 1;

    switch(event->type)
    {
    case KeyPress:
    case KeyRelease:
    case KeymapNotify:
234
    case MappingNotify:
235
        return (mask & (QS_KEY|QS_HOTKEY)) != 0;
236 237 238
    case ButtonPress:
    case ButtonRelease:
        return (mask & QS_MOUSEBUTTON) != 0;
239 240 241
#ifdef GenericEvent
    case GenericEvent:
#endif
242 243 244 245 246 247
    case MotionNotify:
    case EnterNotify:
    case LeaveNotify:
        return (mask & QS_MOUSEMOVE) != 0;
    case Expose:
        return (mask & QS_PAINT) != 0;
248 249 250 251 252 253
    case FocusIn:
    case FocusOut:
    case MapNotify:
    case UnmapNotify:
    case ConfigureNotify:
    case PropertyNotify:
254 255 256 257 258 259 260 261
    case ClientMessage:
        return (mask & QS_POSTMESSAGE) != 0;
    default:
        return (mask & QS_SENDMESSAGE) != 0;
    }
}


262 263 264 265
enum event_merge_action
{
    MERGE_DISCARD,  /* discard the old event */
    MERGE_HANDLE,   /* handle the old event */
266 267
    MERGE_KEEP,     /* keep the old event for future merging */
    MERGE_IGNORE    /* ignore the new event, keep the old one */
268 269
};

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
/***********************************************************************
 *           merge_raw_motion_events
 */
#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
static enum event_merge_action merge_raw_motion_events( XIRawEvent *prev, XIRawEvent *next )
{
    int i, j, k;
    unsigned char mask;

    if (!prev->valuators.mask_len) return MERGE_HANDLE;
    if (!next->valuators.mask_len) return MERGE_HANDLE;

    mask = prev->valuators.mask[0] | next->valuators.mask[0];
    if (mask == next->valuators.mask[0])  /* keep next */
    {
        for (i = j = k = 0; i < 8; i++)
        {
            if (XIMaskIsSet( prev->valuators.mask, i ))
                next->valuators.values[j] += prev->valuators.values[k++];
            if (XIMaskIsSet( next->valuators.mask, i )) j++;
        }
        TRACE( "merging duplicate GenericEvent\n" );
        return MERGE_DISCARD;
    }
    if (mask == prev->valuators.mask[0])  /* keep prev */
    {
        for (i = j = k = 0; i < 8; i++)
        {
            if (XIMaskIsSet( next->valuators.mask, i ))
                prev->valuators.values[j] += next->valuators.values[k++];
            if (XIMaskIsSet( prev->valuators.mask, i )) j++;
        }
        TRACE( "merging duplicate GenericEvent\n" );
        return MERGE_IGNORE;
    }
    /* can't merge events with disjoint masks */
    return MERGE_HANDLE;
}
#endif

310 311 312 313 314 315 316 317 318 319 320 321 322
/***********************************************************************
 *           merge_events
 *
 * Try to merge 2 consecutive events.
 */
static enum event_merge_action merge_events( XEvent *prev, XEvent *next )
{
    switch (prev->type)
    {
    case ConfigureNotify:
        switch (next->type)
        {
        case ConfigureNotify:
323 324 325 326 327 328
            if (prev->xany.window == next->xany.window)
            {
                TRACE( "discarding duplicate ConfigureNotify for window %lx\n", prev->xany.window );
                return MERGE_DISCARD;
            }
            break;
329 330 331 332 333 334
        case Expose:
        case PropertyNotify:
            return MERGE_KEEP;
        }
        break;
    case MotionNotify:
335
        switch (next->type)
336
        {
337 338 339 340 341 342 343 344 345 346 347 348 349
        case MotionNotify:
            if (prev->xany.window == next->xany.window)
            {
                TRACE( "discarding duplicate MotionNotify for window %lx\n", prev->xany.window );
                return MERGE_DISCARD;
            }
            break;
#ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
        case GenericEvent:
            if (next->xcookie.extension != xinput2_opcode) break;
            if (next->xcookie.evtype != XI_RawMotion) break;
            if (x11drv_thread_data()->warp_serial) break;
            return MERGE_KEEP;
350 351
        }
        break;
352
    case GenericEvent:
353 354 355
        if (prev->xcookie.extension != xinput2_opcode) break;
        if (prev->xcookie.evtype != XI_RawMotion) break;
        switch (next->type)
356
        {
357 358 359 360 361 362
        case GenericEvent:
            if (next->xcookie.extension != xinput2_opcode) break;
            if (next->xcookie.evtype != XI_RawMotion) break;
            if (x11drv_thread_data()->warp_serial) break;
            return merge_raw_motion_events( prev->xcookie.data, next->xcookie.data );
#endif
363 364
        }
        break;
365 366 367 368 369 370 371 372
    }
    return MERGE_HANDLE;
}


/***********************************************************************
 *           call_event_handler
 */
373
static inline BOOL call_event_handler( Display *display, XEvent *event )
374 375
{
    HWND hwnd;
376 377
    XEvent *prev;
    struct x11drv_thread_data *thread_data;
378
    BOOL ret;
379

380
    if (!handlers[event->type])
381 382
    {
        TRACE( "%s for win %lx, ignoring\n", dbgstr_event( event->type ), event->xany.window );
383
        return FALSE;  /* no handler, ignore it */
384 385
    }

386 387 388
#ifdef GenericEvent
    if (event->type == GenericEvent) hwnd = 0; else
#endif
389 390 391 392
    if (XFindContext( display, event->xany.window, winContext, (char **)&hwnd ) != 0)
        hwnd = 0;  /* not for a registered window */
    if (!hwnd && event->xany.window == root_window) hwnd = GetDesktopWindow();

393 394
    TRACE( "%lu %s for hwnd/window %p/%lx\n",
           event->xany.serial, dbgstr_event( event->type ), hwnd, event->xany.window );
395 396 397
    thread_data = x11drv_thread_data();
    prev = thread_data->current_event;
    thread_data->current_event = event;
398
    ret = handlers[event->type]( hwnd, event );
399
    thread_data->current_event = prev;
400
    return ret;
401 402 403
}


404
/***********************************************************************
405
 *           process_events
406
 */
407
static BOOL process_events( Display *display, Bool (*filter)(Display*, XEvent*,XPointer), ULONG_PTR arg )
408
{
409
    XEvent event, prev_event;
410
    int count = 0;
411
    BOOL queued = FALSE;
412
    enum event_merge_action action = MERGE_DISCARD;
413

414
    prev_event.type = 0;
415
    while (XCheckIfEvent( display, &event, filter, (char *)arg ))
416
    {
417
        count++;
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
        if (XFilterEvent( &event, None ))
        {
            /*
             * SCIM on linux filters key events strangely. It does not filter the
             * KeyPress events for these keys however it does filter the
             * KeyRelease events. This causes wine to become very confused as
             * to the keyboard state.
             *
             * We need to let those KeyRelease events be processed so that the
             * keyboard state is correct.
             */
            if (event.type == KeyRelease)
            {
                KeySym keysym = 0;
                XKeyEvent *keyevent = &event.xkey;

                XLookupString(keyevent, NULL, 0, &keysym, NULL);
                if (!(keysym == XK_Shift_L ||
                    keysym == XK_Shift_R ||
                    keysym == XK_Control_L ||
                    keysym == XK_Control_R ||
                    keysym == XK_Alt_R ||
                    keysym == XK_Alt_L ||
                    keysym == XK_Meta_R ||
                    keysym == XK_Meta_L))
                        continue; /* not a key we care about, ignore it */
            }
            else
                continue;  /* filtered, ignore it */
        }
448
        get_event_data( &event );
449 450
        if (prev_event.type) action = merge_events( &prev_event, &event );
        switch( action )
451
        {
452
        case MERGE_HANDLE:  /* handle prev, keep new */
453
            queued |= call_event_handler( display, &prev_event );
454 455 456
            /* fall through */
        case MERGE_DISCARD:  /* discard prev, keep new */
            free_event_data( &prev_event );
457 458 459
            prev_event = event;
            break;
        case MERGE_KEEP:  /* handle new, keep prev for future merging */
460
            queued |= call_event_handler( display, &event );
461 462
            /* fall through */
        case MERGE_IGNORE: /* ignore new, keep prev for future merging */
463
            free_event_data( &event );
464
            break;
465
        }
466
    }
467
    if (prev_event.type) queued |= call_event_handler( display, &prev_event );
468
    free_event_data( &prev_event );
469
    XFlush( gdi_display );
470
    if (count) TRACE( "processed %d events, returning %d\n", count, queued );
471
    return queued;
472 473
}

474

475
/***********************************************************************
476
 *           MsgWaitForMultipleObjectsEx   (X11DRV.@)
477
 */
478 479
DWORD CDECL X11DRV_MsgWaitForMultipleObjectsEx( DWORD count, const HANDLE *handles,
                                                DWORD timeout, DWORD mask, DWORD flags )
480
{
481
    DWORD ret;
482
    struct x11drv_thread_data *data = TlsGetValue( thread_data_tls_index );
483

484
    if (!data)
485 486
    {
        if (!count && !timeout) return WAIT_TIMEOUT;
487 488
        return WaitForMultipleObjectsEx( count, handles, flags & MWMO_WAITALL,
                                         timeout, flags & MWMO_ALERTABLE );
489
    }
490

491
    if (data->current_event) mask = 0;  /* don't process nested events */
492

493
    if (process_events( data->display, filter_event, mask )) ret = count - 1;
494
    else if (count || timeout)
495
    {
496
        ret = WaitForMultipleObjectsEx( count, handles, flags & MWMO_WAITALL,
497
                                        timeout, flags & MWMO_ALERTABLE );
498
        if (ret == count - 1) process_events( data->display, filter_event, mask );
499
    }
500 501
    else ret = WAIT_TIMEOUT;

502
    return ret;
503 504
}

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
/***********************************************************************
 *           EVENT_x11_time_to_win32_time
 *
 * Make our timer and the X timer line up as best we can
 *  Pass 0 to retrieve the current adjustment value (times -1)
 */
DWORD EVENT_x11_time_to_win32_time(Time time)
{
  static DWORD adjust = 0;
  DWORD now = GetTickCount();
  DWORD ret;

  if (! adjust && time != 0)
  {
    ret = now;
    adjust = time - now;
  }
  else
  {
      /* If we got an event in the 'future', then our clock is clearly wrong. 
         If we got it more than 10000 ms in the future, then it's most likely
         that the clock has wrapped.  */

      ret = time - adjust;
      if (ret > now && ((ret - now) < 10000) && time != 0)
      {
        adjust += ret - now;
        ret    -= ret - now;
      }
  }

  return ret;

}
539

540 541 542 543 544
/*******************************************************************
 *         can_activate_window
 *
 * Check if we can activate the specified window.
 */
545
static inline BOOL can_activate_window( HWND hwnd )
546 547
{
    LONG style = GetWindowLongW( hwnd, GWL_STYLE );
548
    RECT rect;
549

550 551
    if (!(style & WS_VISIBLE)) return FALSE;
    if ((style & (WS_POPUP|WS_CHILD)) == WS_CHILD) return FALSE;
552
    if (style & WS_MINIMIZE) return FALSE;
553
    if (GetWindowLongW( hwnd, GWL_EXSTYLE ) & WS_EX_NOACTIVATE) return FALSE;
554
    if (hwnd == GetDesktopWindow()) return FALSE;
555
    if (GetWindowRect( hwnd, &rect ) && IsRectEmpty( &rect )) return FALSE;
556 557 558 559
    return !(style & WS_DISABLED);
}


560 561 562
/**********************************************************************
 *              set_input_focus
 *
563
 * Try to force focus for embedded or non-managed windows.
564
 */
565
static void set_input_focus( struct x11drv_win_data *data )
566 567 568 569
{
    XWindowChanges changes;
    DWORD timestamp;

570
    if (!data->whole_window) return;
571 572 573 574 575 576 577 578 579 580

    if (EVENT_x11_time_to_win32_time(0))
        /* ICCCM says don't use CurrentTime, so try to use last message time if possible */
        /* FIXME: this is not entirely correct */
        timestamp = GetMessageTime() - EVENT_x11_time_to_win32_time(0);
    else
        timestamp = CurrentTime;

    /* Set X focus and install colormap */
    changes.stack_mode = Above;
581 582 583 584 585 586 587
    XConfigureWindow( data->display, data->whole_window, CWStackMode, &changes );

    if (data->embedder)
        xembed_request_focus( data->display, data->embedder, timestamp );
    else
        XSetInputFocus( data->display, data->whole_window, RevertToParent, timestamp );

588 589
}

590 591 592
/**********************************************************************
 *              set_focus
 */
593
static void set_focus( Display *display, HWND hwnd, Time time )
594
{
595
    HWND focus;
596
    Window win;
597
    GUITHREADINFO threadinfo;
598

599
    TRACE( "setting foreground window to %p\n", hwnd );
600
    SetForegroundWindow( hwnd );
601

602
    threadinfo.cbSize = sizeof(threadinfo);
603 604
    GetGUIThreadInfo(0, &threadinfo);
    focus = threadinfo.hwndFocus;
605
    if (!focus) focus = threadinfo.hwndActive;
606
    if (focus) focus = GetAncestor( focus, GA_ROOT );
607 608 609 610
    win = X11DRV_get_whole_window(focus);

    if (win)
    {
611
        TRACE( "setting focus to %p (%lx) time=%ld\n", focus, win, time );
612
        XSetInputFocus( display, win, RevertToParent, time );
613
    }
614 615 616
}


617 618 619 620 621 622 623 624 625 626 627
/**********************************************************************
 *              handle_manager_message
 */
static void handle_manager_message( HWND hwnd, XClientMessageEvent *event )
{
    if (hwnd != GetDesktopWindow()) return;
    if (systray_atom && event->data.l[1] == systray_atom)
        change_systray_owner( event->display, event->data.l[2] );
}


628
/**********************************************************************
629
 *              handle_wm_protocols
630
 */
631
static void handle_wm_protocols( HWND hwnd, XClientMessageEvent *event )
632
{
633
    Atom protocol = (Atom)event->data.l[0];
634
    Time event_time = (Time)event->data.l[1];
635 636

    if (!protocol) return;
637

638
    if (protocol == x11drv_atom(WM_DELETE_WINDOW))
639
    {
640 641
        update_user_time( event_time );

642 643 644 645 646 647 648 649
        if (hwnd == GetDesktopWindow())
        {
            /* The desktop window does not have a close button that we can
             * pretend to click. Therefore, we simply send it a close command. */
            SendMessageW(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0);
            return;
        }

650 651 652 653
        /* Ignore the delete window request if the window has been disabled
         * and we are in managed mode. This is to disallow applications from
         * being closed by the window manager while in a modal state.
         */
654 655 656 657 658 659 660 661 662 663 664 665
        if (IsWindowEnabled(hwnd))
        {
            HMENU hSysMenu;

            if (GetClassLongW(hwnd, GCL_STYLE) & CS_NOCLOSE) return;
            hSysMenu = GetSystemMenu(hwnd, FALSE);
            if (hSysMenu)
            {
                UINT state = GetMenuState(hSysMenu, SC_CLOSE, MF_BYCOMMAND);
                if (state == 0xFFFFFFFF || (state & (MF_DISABLED | MF_GRAYED)))
                    return;
            }
666 667 668 669
            if (GetActiveWindow() != hwnd)
            {
                LRESULT ma = SendMessageW( hwnd, WM_MOUSEACTIVATE,
                                           (WPARAM)GetAncestor( hwnd, GA_ROOT ),
670
                                           MAKELPARAM( HTCLOSE, WM_NCLBUTTONDOWN ) );
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
                switch(ma)
                {
                    case MA_NOACTIVATEANDEAT:
                    case MA_ACTIVATEANDEAT:
                        return;
                    case MA_NOACTIVATE:
                        break;
                    case MA_ACTIVATE:
                    case 0:
                        SetActiveWindow(hwnd);
                        break;
                    default:
                        WARN( "unknown WM_MOUSEACTIVATE code %d\n", (int) ma );
                        break;
                }
            }
687

688
            PostMessageW( hwnd, WM_SYSCOMMAND, SC_CLOSE, 0 );
689
        }
690
    }
691
    else if (protocol == x11drv_atom(WM_TAKE_FOCUS))
692
    {
693 694
        HWND last_focus = x11drv_thread_data()->last_focus;

695
        TRACE( "got take focus msg for %p, enabled=%d, visible=%d (style %08x), focus=%p, active=%p, fg=%p, last=%p\n",
696 697
               hwnd, IsWindowEnabled(hwnd), IsWindowVisible(hwnd), GetWindowLongW(hwnd, GWL_STYLE),
               GetFocus(), GetActiveWindow(), GetForegroundWindow(), last_focus );
698

699
        if (can_activate_window(hwnd))
700
        {
701
            /* simulate a mouse click on the menu to find out
702 703
             * whether the window wants to be activated */
            LRESULT ma = SendMessageW( hwnd, WM_MOUSEACTIVATE,
704
                                       (WPARAM)GetAncestor( hwnd, GA_ROOT ),
705
                                       MAKELONG( HTMENU, WM_LBUTTONDOWN ) );
706 707
            if (ma != MA_NOACTIVATEANDEAT && ma != MA_NOACTIVATE)
            {
708
                set_focus( event->display, hwnd, event_time );
709 710
                return;
            }
711
        }
712 713 714 715 716 717 718 719
        else if (hwnd == GetDesktopWindow())
        {
            hwnd = GetForegroundWindow();
            if (!hwnd) hwnd = last_focus;
            if (!hwnd) hwnd = GetDesktopWindow();
            set_focus( event->display, hwnd, event_time );
            return;
        }
720 721 722 723 724
        /* try to find some other window to give the focus to */
        hwnd = GetFocus();
        if (hwnd) hwnd = GetAncestor( hwnd, GA_ROOT );
        if (!hwnd) hwnd = GetActiveWindow();
        if (!hwnd) hwnd = last_focus;
725
        if (hwnd && can_activate_window(hwnd)) set_focus( event->display, hwnd, event_time );
726 727 728
    }
    else if (protocol == x11drv_atom(_NET_WM_PING))
    {
729 730 731 732 733 734
      XClientMessageEvent xev;
      xev = *event;
      
      TRACE("NET_WM Ping\n");
      xev.window = DefaultRootWindow(xev.display);
      XSendEvent(xev.display, xev.window, False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*)&xev);
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    }
}


static const char * const focus_details[] =
{
    "NotifyAncestor",
    "NotifyVirtual",
    "NotifyInferior",
    "NotifyNonlinear",
    "NotifyNonlinearVirtual",
    "NotifyPointer",
    "NotifyPointerRoot",
    "NotifyDetailNone"
};

751 752 753 754 755 756 757 758
static const char * const focus_modes[] =
{
    "NotifyNormal",
    "NotifyGrab",
    "NotifyUngrab",
    "NotifyWhileGrabbed"
};

759
/**********************************************************************
760
 *              X11DRV_FocusIn
761
 */
762
static BOOL X11DRV_FocusIn( HWND hwnd, XEvent *xev )
763
{
764
    XFocusChangeEvent *event = &xev->xfocus;
765 766
    XIC xic;

767
    if (!hwnd) return FALSE;
768

769
    TRACE( "win %p xwin %lx detail=%s mode=%s\n", hwnd, event->window, focus_details[event->detail], focus_modes[event->mode] );
770

771 772
    if (event->detail == NotifyPointer) return FALSE;
    if (hwnd == GetDesktopWindow()) return FALSE;
773

774 775 776
    switch (event->mode)
    {
    case NotifyGrab:
777 778 779
        /* these are received when moving undecorated managed windows on mutter */
        keyboard_grabbed = TRUE;
        return FALSE;
780
    case NotifyWhileGrabbed:
781
        keyboard_grabbed = TRUE;
782 783
        break;
    case NotifyNormal:
784
        keyboard_grabbed = FALSE;
785 786
        break;
    case NotifyUngrab:
787
        keyboard_grabbed = FALSE;
788
        retry_grab_clipping_window();
789 790 791
        return TRUE; /* ignore wm specific NotifyUngrab / NotifyGrab events w.r.t focus */
    }

792
    if ((xic = X11DRV_get_ic( hwnd ))) XSetICFocus( xic );
793 794
    if (use_take_focus)
    {
795
        if (hwnd == GetForegroundWindow()) clip_fullscreen_window( hwnd, FALSE );
796
        return TRUE;
797
    }
798

799
    if (!can_activate_window(hwnd))
800 801
    {
        HWND hwnd = GetFocus();
802
        if (hwnd) hwnd = GetAncestor( hwnd, GA_ROOT );
803 804
        if (!hwnd) hwnd = GetActiveWindow();
        if (!hwnd) hwnd = x11drv_thread_data()->last_focus;
805
        if (hwnd && can_activate_window(hwnd)) set_focus( event->display, hwnd, CurrentTime );
806
    }
807
    else SetForegroundWindow( hwnd );
808
    return TRUE;
809 810 811
}

/**********************************************************************
812
 *              focus_out
813
 */
814
static void focus_out( Display *display , HWND hwnd )
815
 {
816 817 818
    HWND hwnd_tmp;
    Window focus_win;
    int revert;
819
    XIC xic;
820

821 822
    if (ximInComposeMode) return;

823
    x11drv_thread_data()->last_focus = hwnd;
824 825
    if ((xic = X11DRV_get_ic( hwnd ))) XUnsetICFocus( xic );

826
    if (is_virtual_desktop())
827 828 829 830
    {
        if (hwnd == GetDesktopWindow()) reset_clipping_window();
        return;
    }
831
    if (hwnd != GetForegroundWindow()) return;
832
    SendMessageW( hwnd, WM_CANCELMODE, 0, 0 );
833 834 835 836

    /* don't reset the foreground window, if the window which is
       getting the focus is a Wine window */

837
    XGetInputFocus( display, &focus_win, &revert );
838 839
    if (focus_win)
    {
840
        if (XFindContext( display, focus_win, winContext, (char **)&hwnd_tmp ) != 0)
841 842 843 844
            focus_win = 0;
    }

    if (!focus_win)
845 846 847 848 849 850 851
    {
        /* Abey : 6-Oct-99. Check again if the focus out window is the
           Foreground window, because in most cases the messages sent
           above must have already changed the foreground window, in which
           case we don't have to change the foreground window to 0 */
        if (hwnd == GetForegroundWindow())
        {
852 853
            TRACE( "lost focus, setting fg to desktop\n" );
            SetForegroundWindow( GetDesktopWindow() );
854 855
        }
    }
856 857 858 859 860 861 862
 }

/**********************************************************************
 *              X11DRV_FocusOut
 *
 * Note: only top-level windows get FocusOut events.
 */
863
static BOOL X11DRV_FocusOut( HWND hwnd, XEvent *xev )
864 865 866
{
    XFocusChangeEvent *event = &xev->xfocus;

867
    TRACE( "win %p xwin %lx detail=%s mode=%s\n", hwnd, event->window, focus_details[event->detail], focus_modes[event->mode] );
868 869 870 871

    if (event->detail == NotifyPointer)
    {
        if (!hwnd && event->window == x11drv_thread_data()->clip_window) reset_clipping_window();
872
        return TRUE;
873
    }
874
    if (!hwnd) return FALSE;
875 876 877 878

    switch (event->mode)
    {
    case NotifyUngrab:
879 880 881
        /* these are received when moving undecorated managed windows on mutter */
        keyboard_grabbed = FALSE;
        return FALSE;
882
    case NotifyNormal:
883
        keyboard_grabbed = FALSE;
884 885
        break;
    case NotifyWhileGrabbed:
886
        keyboard_grabbed = TRUE;
887 888
        break;
    case NotifyGrab:
889
        keyboard_grabbed = TRUE;
890 891 892 893 894 895 896

        /* This will do nothing due to keyboard_grabbed == TRUE, but it
         * will save the current clipping rect so we can restore it on
         * FocusIn with NotifyUngrab mode.
         */
        retry_grab_clipping_window();

897 898 899
        return TRUE; /* ignore wm specific NotifyUngrab / NotifyGrab events w.r.t focus */
    }

900
    focus_out( event->display, hwnd );
901
    return TRUE;
902 903 904
}


905 906 907
/***********************************************************************
 *           X11DRV_Expose
 */
908
static BOOL X11DRV_Expose( HWND hwnd, XEvent *xev )
909 910
{
    XExposeEvent *event = &xev->xexpose;
911
    RECT rect, abs_rect;
912
    POINT pos;
913
    struct x11drv_win_data *data;
914 915
    HRGN surface_region = 0;
    UINT flags = RDW_INVALIDATE | RDW_ERASE | RDW_FRAME | RDW_ALLCHILDREN;
916 917 918 919

    TRACE( "win %p (%lx) %d,%d %dx%d\n",
           hwnd, event->window, event->x, event->y, event->width, event->height );

920 921 922 923 924 925 926
    if (event->window != root_window)
    {
        pos.x = event->x;
        pos.y = event->y;
    }
    else pos = root_to_virtual_screen( event->x, event->y );

927
    if (!(data = get_win_data( hwnd ))) return FALSE;
928

929 930 931 932
    rect.left   = pos.x;
    rect.top    = pos.y;
    rect.right  = pos.x + event->width;
    rect.bottom = pos.y + event->height;
933

934
    if (event->window != data->client_window)
935
    {
936 937 938 939 940 941
        if (data->surface)
        {
            surface_region = expose_surface( data->surface, &rect );
            if (!surface_region) flags = 0;
            else OffsetRgn( surface_region, data->whole_rect.left - data->client_rect.left,
                            data->whole_rect.top - data->client_rect.top );
942

943 944 945
            if (data->vis.visualid != default_visual.visualid)
                data->surface->funcs->flush( data->surface );
        }
946 947
        OffsetRect( &rect, data->whole_rect.left - data->client_rect.left,
                    data->whole_rect.top - data->client_rect.top );
948
    }
949

950 951
    if (event->window != root_window)
    {
952 953
        if (GetWindowLongW( data->hwnd, GWL_EXSTYLE ) & WS_EX_LAYOUTRTL)
            mirror_rect( &data->client_rect, &rect );
954 955
        abs_rect = rect;
        MapWindowPoints( hwnd, 0, (POINT *)&abs_rect, 2 );
956

957 958
        SERVER_START_REQ( update_window_zorder )
        {
959
            req->window      = wine_server_user_handle( hwnd );
960 961 962 963
            req->rect.left   = abs_rect.left;
            req->rect.top    = abs_rect.top;
            req->rect.right  = abs_rect.right;
            req->rect.bottom = abs_rect.bottom;
964 965 966 967
            wine_server_call( req );
        }
        SERVER_END_REQ;
    }
968 969
    else flags &= ~RDW_ALLCHILDREN;

970 971
    release_win_data( data );

972 973
    if (flags) RedrawWindow( hwnd, &rect, surface_region, flags );
    if (surface_region) DeleteObject( surface_region );
974
    return TRUE;
975 976 977
}


978 979 980
/**********************************************************************
 *		X11DRV_MapNotify
 */
981
static BOOL X11DRV_MapNotify( HWND hwnd, XEvent *event )
982 983 984
{
    struct x11drv_win_data *data;

985 986
    if (event->xany.window == x11drv_thread_data()->clip_window) return TRUE;

987
    if (!(data = get_win_data( hwnd ))) return FALSE;
988

989
    if (!data->managed && !data->embedded && data->mapped)
990 991
    {
        HWND hwndFocus = GetFocus();
992
        if (hwndFocus && IsChild( hwnd, hwndFocus ))
993
            set_input_focus( data );
994
    }
995
    release_win_data( data );
996
    return TRUE;
997 998 999
}


1000 1001 1002
/**********************************************************************
 *		X11DRV_UnmapNotify
 */
1003
static BOOL X11DRV_UnmapNotify( HWND hwnd, XEvent *event )
1004
{
1005
    return TRUE;
1006 1007 1008
}


1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
/***********************************************************************
 *           reparent_notify
 */
static void reparent_notify( Display *display, HWND hwnd, Window xparent, int x, int y )
{
    HWND parent, old_parent;
    DWORD style;

    style = GetWindowLongW( hwnd, GWL_STYLE );
    if (xparent == root_window)
    {
        parent = GetDesktopWindow();
        style = (style & ~WS_CHILD) | WS_POPUP;
    }
    else
    {
        if (!(parent = create_foreign_window( display, xparent ))) return;
        style = (style & ~WS_POPUP) | WS_CHILD;
    }

    ShowWindow( hwnd, SW_HIDE );
    old_parent = SetParent( hwnd, parent );
    SetWindowLongW( hwnd, GWL_STYLE, style );
    SetWindowPos( hwnd, HWND_TOP, x, y, 0, 0,
                  SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOCOPYBITS |
                  ((style & WS_VISIBLE) ? SWP_SHOWWINDOW : 0) );

    /* make old parent destroy itself if it no longer has children */
    if (old_parent != GetDesktopWindow()) PostMessageW( old_parent, WM_CLOSE, 0, 0 );
}

1040

1041 1042 1043
/***********************************************************************
 *           X11DRV_ReparentNotify
 */
1044
static BOOL X11DRV_ReparentNotify( HWND hwnd, XEvent *xev )
1045 1046 1047 1048
{
    XReparentEvent *event = &xev->xreparent;
    struct x11drv_win_data *data;

1049
    if (!(data = get_win_data( hwnd ))) return FALSE;
1050 1051 1052 1053

    if (!data->embedded)
    {
        release_win_data( data );
1054
        return FALSE;
1055
    }
1056 1057 1058 1059 1060 1061 1062

    if (data->whole_window)
    {
        if (event->parent == root_window)
        {
            TRACE( "%p/%lx reparented to root\n", hwnd, data->whole_window );
            data->embedder = 0;
1063
            release_win_data( data );
1064
            SendMessageW( hwnd, WM_CLOSE, 0, 0 );
1065
            return TRUE;
1066 1067 1068 1069 1070
        }
        data->embedder = event->parent;
    }

    TRACE( "%p/%lx reparented to %lx\n", hwnd, data->whole_window, event->parent );
1071
    release_win_data( data );
1072

1073
    reparent_notify( event->display, hwnd, event->parent, event->x, event->y );
1074
    return TRUE;
1075 1076 1077
}


1078 1079 1080
/***********************************************************************
 *		X11DRV_ConfigureNotify
 */
1081
static BOOL X11DRV_ConfigureNotify( HWND hwnd, XEvent *xev )
1082 1083 1084 1085
{
    XConfigureEvent *event = &xev->xconfigure;
    struct x11drv_win_data *data;
    RECT rect;
1086
    POINT pos;
1087
    UINT flags;
1088 1089
    HWND parent;
    BOOL root_coords;
1090
    int cx, cy, x = event->x, y = event->y;
1091
    DWORD style;
1092

1093 1094
    if (!hwnd) return FALSE;
    if (!(data = get_win_data( hwnd ))) return FALSE;
1095 1096
    if (!data->mapped || data->iconic) goto done;
    if (data->whole_window && !data->managed) goto done;
1097
    /* ignore synthetic events on foreign windows */
1098
    if (event->send_event && !data->whole_window) goto done;
1099 1100 1101 1102 1103
    if (data->configure_serial && (long)(data->configure_serial - event->serial) > 0)
    {
        TRACE( "win %p/%lx event %d,%d,%dx%d ignoring old serial %lu/%lu\n",
               hwnd, data->whole_window, event->x, event->y, event->width, event->height,
               event->serial, data->configure_serial );
1104
        goto done;
1105
    }
1106 1107 1108

    /* Get geometry */

1109 1110 1111 1112
    parent = GetAncestor( hwnd, GA_PARENT );
    root_coords = event->send_event;  /* synthetic events are always in root coords */

    if (!root_coords && parent == GetDesktopWindow()) /* normal event, map coordinates to the root */
1113 1114
    {
        Window child;
1115
        XTranslateCoordinates( event->display, event->window, root_window,
1116
                               0, 0, &x, &y, &child );
1117
        root_coords = TRUE;
1118
    }
1119 1120 1121 1122 1123 1124 1125 1126

    if (!root_coords)
    {
        pos.x = x;
        pos.y = y;
    }
    else pos = root_to_virtual_screen( x, y );

1127 1128 1129
    X11DRV_X_to_window_rect( data, &rect, pos.x, pos.y, event->width, event->height );
    if (root_coords) MapWindowPoints( 0, parent, (POINT *)&rect, 2 );

1130 1131
    TRACE( "win %p/%lx new X rect %d,%d,%dx%d (event %d,%d,%dx%d)\n",
           hwnd, data->whole_window, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top,
1132 1133 1134 1135
           event->x, event->y, event->width, event->height );

    /* Compare what has changed */

1136 1137 1138 1139 1140 1141
    x     = rect.left;
    y     = rect.top;
    cx    = rect.right - rect.left;
    cy    = rect.bottom - rect.top;
    flags = SWP_NOACTIVATE | SWP_NOZORDER;

1142 1143
    if (!data->whole_window) flags |= SWP_NOCOPYBITS;  /* we can't copy bits of foreign windows */

1144
    if (data->window_rect.left == x && data->window_rect.top == y) flags |= SWP_NOMOVE;
1145 1146
    else
        TRACE( "%p moving from (%d,%d) to (%d,%d)\n",
1147
               hwnd, data->window_rect.left, data->window_rect.top, x, y );
1148

1149 1150
    if ((data->window_rect.right - data->window_rect.left == cx &&
         data->window_rect.bottom - data->window_rect.top == cy) ||
1151
        IsRectEmpty( &data->window_rect ))
1152 1153 1154
        flags |= SWP_NOSIZE;
    else
        TRACE( "%p resizing from (%dx%d) to (%dx%d)\n",
1155 1156
               hwnd, data->window_rect.right - data->window_rect.left,
               data->window_rect.bottom - data->window_rect.top, cx, cy );
1157

1158
    style = GetWindowLongW( data->hwnd, GWL_STYLE );
1159
    if ((style & WS_CAPTION) == WS_CAPTION || !is_window_rect_full_screen( &data->whole_rect ))
1160
    {
1161 1162
        read_net_wm_states( event->display, data );
        if ((data->net_wm_state & (1 << NET_WM_STATE_MAXIMIZED)))
1163
        {
1164 1165 1166 1167 1168
            if (!(style & WS_MAXIMIZE))
            {
                TRACE( "win %p/%lx is maximized\n", data->hwnd, data->whole_window );
                release_win_data( data );
                SendMessageW( data->hwnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0 );
1169
                return TRUE;
1170
            }
1171
        }
1172
        else if (style & WS_MAXIMIZE)
1173 1174
        {
            TRACE( "window %p/%lx is no longer maximized\n", data->hwnd, data->whole_window );
1175
            release_win_data( data );
1176
            SendMessageW( data->hwnd, WM_SYSCOMMAND, SC_RESTORE, 0 );
1177
            return TRUE;
1178 1179 1180
        }
    }

1181
    if ((flags & (SWP_NOSIZE | SWP_NOMOVE)) != (SWP_NOSIZE | SWP_NOMOVE))
1182 1183
    {
        release_win_data( data );
1184
        SetWindowPos( hwnd, 0, x, y, cx, cy, flags );
1185
        return TRUE;
1186 1187 1188 1189
    }

done:
    release_win_data( data );
1190
    return FALSE;
1191 1192 1193
}


1194 1195 1196
/**********************************************************************
 *           X11DRV_GravityNotify
 */
1197
static BOOL X11DRV_GravityNotify( HWND hwnd, XEvent *xev )
1198 1199
{
    XGravityEvent *event = &xev->xgravity;
1200
    struct x11drv_win_data *data = get_win_data( hwnd );
1201 1202
    RECT window_rect;
    int x, y;
1203

1204
    if (!data) return FALSE;
1205 1206 1207 1208

    if (data->whole_window)  /* only handle this for foreign windows */
    {
        release_win_data( data );
1209
        return FALSE;
1210
    }
1211

1212 1213
    x = event->x + data->window_rect.left - data->whole_rect.left;
    y = event->y + data->window_rect.top - data->whole_rect.top;
1214

1215 1216
    TRACE( "win %p/%lx new X pos %d,%d (event %d,%d)\n",
           hwnd, data->whole_window, x, y, event->x, event->y );
1217

1218 1219
    window_rect = data->window_rect;
    release_win_data( data );
1220

1221 1222 1223
    if (window_rect.left != x || window_rect.top != y)
        SetWindowPos( hwnd, 0, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOCOPYBITS );

1224
    return TRUE;
1225 1226 1227
}


1228 1229 1230
/***********************************************************************
 *           get_window_wm_state
 */
1231
static int get_window_wm_state( Display *display, Window window )
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
{
    struct
    {
        CARD32 state;
        XID     icon;
    } *state;
    Atom type;
    int format, ret = -1;
    unsigned long count, remaining;

1242
    if (!XGetWindowProperty( display, window, x11drv_atom(WM_STATE), 0,
1243 1244 1245
                             sizeof(*state)/sizeof(CARD32), False, x11drv_atom(WM_STATE),
                             &type, &format, &count, &remaining, (unsigned char **)&state ))
    {
1246
        if (type == x11drv_atom(WM_STATE) && get_property_size( format, count ) >= sizeof(*state))
1247 1248 1249 1250 1251 1252 1253
            ret = state->state;
        XFree( state );
    }
    return ret;
}


1254
/***********************************************************************
1255 1256 1257
 *           handle_wm_state_notify
 *
 * Handle a PropertyNotify for WM_STATE.
1258
 */
1259
static void handle_wm_state_notify( HWND hwnd, XPropertyEvent *event, BOOL update_window )
1260
{
1261
    struct x11drv_win_data *data = get_win_data( hwnd );
1262 1263
    DWORD style;

1264 1265
    if (!data) return;

1266
    switch(event->state)
1267
    {
1268
    case PropertyDelete:
1269
        TRACE( "%p/%lx: WM_STATE deleted from %d\n", data->hwnd, data->whole_window, data->wm_state );
1270
        data->wm_state = WithdrawnState;
1271
        break;
1272
    case PropertyNewValue:
1273
        {
1274
            int old_state = data->wm_state;
1275
            int new_state = get_window_wm_state( event->display, data->whole_window );
1276 1277
            if (new_state != -1 && new_state != data->wm_state)
            {
1278 1279
                TRACE( "%p/%lx: new WM_STATE %d from %d\n",
                       data->hwnd, data->whole_window, new_state, old_state );
1280
                data->wm_state = new_state;
1281 1282
                /* ignore the initial state transition out of withdrawn state */
                /* metacity does Withdrawn->NormalState->IconicState when mapping an iconic window */
1283
                if (!old_state) goto done;
1284 1285 1286
            }
        }
        break;
1287
    }
1288

1289
    if (!update_window || !data->managed || !data->mapped) goto done;
1290

1291 1292
    style = GetWindowLongW( data->hwnd, GWL_STYLE );

1293 1294 1295
    if (data->iconic && data->wm_state == NormalState)  /* restore window */
    {
        data->iconic = FALSE;
1296 1297
        read_net_wm_states( event->display, data );
        if ((style & WS_CAPTION) == WS_CAPTION && (data->net_wm_state & (1 << NET_WM_STATE_MAXIMIZED)))
1298
        {
1299 1300 1301
            if ((style & WS_MAXIMIZEBOX) && !(style & WS_DISABLED))
            {
                TRACE( "restoring to max %p/%lx\n", data->hwnd, data->whole_window );
1302 1303 1304
                release_win_data( data );
                SendMessageW( hwnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0 );
                return;
1305
            }
1306
            TRACE( "not restoring to max win %p/%lx style %08x\n", data->hwnd, data->whole_window, style );
1307
        }
1308
        else
1309
        {
1310 1311 1312 1313
            if (style & (WS_MINIMIZE | WS_MAXIMIZE))
            {
                TRACE( "restoring win %p/%lx\n", data->hwnd, data->whole_window );
                release_win_data( data );
1314 1315
                if ((style & (WS_MINIMIZE | WS_VISIBLE)) == (WS_MINIMIZE | WS_VISIBLE))
                    SetActiveWindow( hwnd );
1316 1317 1318 1319
                SendMessageW( hwnd, WM_SYSCOMMAND, SC_RESTORE, 0 );
                return;
            }
            TRACE( "not restoring win %p/%lx style %08x\n", data->hwnd, data->whole_window, style );
1320
        }
1321 1322 1323 1324
    }
    else if (!data->iconic && data->wm_state == IconicState)
    {
        data->iconic = TRUE;
1325 1326 1327
        if ((style & WS_MINIMIZEBOX) && !(style & WS_DISABLED))
        {
            TRACE( "minimizing win %p/%lx\n", data->hwnd, data->whole_window );
1328 1329 1330
            release_win_data( data );
            SendMessageW( hwnd, WM_SYSCOMMAND, SC_MINIMIZE, 0 );
            return;
1331
        }
1332
        TRACE( "not minimizing win %p/%lx style %08x\n", data->hwnd, data->whole_window, style );
1333
    }
1334 1335
done:
    release_win_data( data );
1336
}
1337

1338

1339
/***********************************************************************
1340
 *           X11DRV_PropertyNotify
1341
 */
1342
static BOOL X11DRV_PropertyNotify( HWND hwnd, XEvent *xev )
1343 1344 1345
{
    XPropertyEvent *event = &xev->xproperty;

1346
    if (!hwnd) return FALSE;
1347
    if (event->atom == x11drv_atom(WM_STATE)) handle_wm_state_notify( hwnd, event, TRUE );
1348
    return TRUE;
1349 1350 1351
}


1352 1353 1354
/* event filter to wait for a WM_STATE change notification on a window */
static Bool is_wm_state_notify( Display *display, XEvent *event, XPointer arg )
{
1355 1356 1357
    if (event->xany.window != (Window)arg) return 0;
    return (event->type == DestroyNotify ||
            (event->type == PropertyNotify && event->xproperty.atom == x11drv_atom(WM_STATE)));
1358 1359 1360 1361 1362
}

/***********************************************************************
 *           wait_for_withdrawn_state
 */
1363
void wait_for_withdrawn_state( HWND hwnd, BOOL set )
1364
{
1365
    Display *display = thread_display();
1366
    struct x11drv_win_data *data;
1367 1368
    DWORD end = GetTickCount() + 2000;

1369
    TRACE( "waiting for window %p to become %swithdrawn\n", hwnd, set ? "" : "not " );
1370

1371
    for (;;)
1372
    {
1373
        XEvent event;
1374
        Window window;
1375 1376
        int count = 0;

1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
        if (!(data = get_win_data( hwnd ))) break;
        if (!data->managed || data->embedded || data->display != display) break;
        if (!(window = data->whole_window)) break;
        if (!data->mapped == !set)
        {
            TRACE( "window %p/%lx now %smapped\n", hwnd, window, data->mapped ? "" : "un" );
            break;
        }
        if ((data->wm_state == WithdrawnState) != !set)
        {
            TRACE( "window %p/%lx state now %d\n", hwnd, window, data->wm_state );
            break;
        }
        release_win_data( data );

        while (XCheckIfEvent( display, &event, is_wm_state_notify, (char *)window ))
1393 1394 1395 1396
        {
            count++;
            if (XFilterEvent( &event, None )) continue;  /* filtered, ignore it */
            if (event.type == DestroyNotify) call_event_handler( display, &event );
1397
            else handle_wm_state_notify( hwnd, &event.xproperty, FALSE );
1398 1399 1400
        }

        if (!count)
1401
        {
1402 1403 1404 1405 1406 1407 1408
            struct pollfd pfd;
            int timeout = end - GetTickCount();

            pfd.fd = ConnectionNumber(display);
            pfd.events = POLLIN;
            if (timeout <= 0 || poll( &pfd, 1, timeout ) != 1)
            {
1409 1410
                FIXME( "window %p/%lx wait timed out\n", hwnd, window );
                return;
1411
            }
1412 1413
        }
    }
1414
    release_win_data( data );
1415 1416 1417
}


1418 1419 1420 1421 1422 1423 1424 1425 1426
/*****************************************************************
 *		SetFocus   (X11DRV.@)
 *
 * Set the X focus.
 */
void CDECL X11DRV_SetFocus( HWND hwnd )
{
    struct x11drv_win_data *data;

1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
    HWND parent;

    for (;;)
    {
        if (!(data = get_win_data( hwnd ))) return;
        if (data->embedded) break;
        parent = GetAncestor( hwnd, GA_PARENT );
        if (!parent || parent == GetDesktopWindow()) break;
        release_win_data( data );
        hwnd = parent;
    }
    if (!data->managed || data->embedder) set_input_focus( data );
1439
    release_win_data( data );
1440 1441 1442
}


1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
static HWND find_drop_window( HWND hQueryWnd, LPPOINT lpPt )
{
    RECT tempRect;

    if (!IsWindowEnabled(hQueryWnd)) return 0;
    
    GetWindowRect(hQueryWnd, &tempRect);

    if(!PtInRect(&tempRect, *lpPt)) return 0;

    if (!IsIconic( hQueryWnd ))
    {
1455 1456
        POINT pt = *lpPt;
        ScreenToClient( hQueryWnd, &pt );
1457 1458
        GetClientRect( hQueryWnd, &tempRect );

1459
        if (PtInRect( &tempRect, pt))
1460
        {
1461 1462
            HWND ret = ChildWindowFromPointEx( hQueryWnd, pt, CWP_SKIPINVISIBLE|CWP_SKIPDISABLED );
            if (ret && ret != hQueryWnd)
1463
            {
1464 1465
                ret = find_drop_window( ret, lpPt );
                if (ret) return ret;
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
            }
        }
    }

    if(!(GetWindowLongA( hQueryWnd, GWL_EXSTYLE ) & WS_EX_ACCEPTFILES)) return 0;
    
    ScreenToClient(hQueryWnd, lpPt);

    return hQueryWnd;
}

1477 1478 1479
/**********************************************************************
 *           EVENT_DropFromOffix
 *
Austin English's avatar
Austin English committed
1480
 * don't know if it still works (last Changelog is from 96/11/04)
1481
 */
1482
static void EVENT_DropFromOffiX( HWND hWnd, XClientMessageEvent *event )
1483
{
1484
    struct x11drv_win_data *data;
1485
    POINT pt;
1486 1487 1488
    unsigned long	data_length;
    unsigned long	aux_long;
    unsigned char*	p_data = NULL;
1489
    Atom atom_aux;
1490
    int			x, y, cx, cy, dummy;
1491
    Window		win, w_aux_root, w_aux_child;
1492

1493 1494 1495 1496 1497 1498
    if (!(data = get_win_data( hWnd ))) return;
    cx = data->whole_rect.right - data->whole_rect.left;
    cy = data->whole_rect.bottom - data->whole_rect.top;
    win = data->whole_window;
    release_win_data( data );

1499
    XQueryPointer( event->display, win, &w_aux_root, &w_aux_child,
1500
                   &x, &y, &dummy, &dummy, (unsigned int*)&aux_long);
1501
    pt = root_to_virtual_screen( x, y );
1502 1503

    /* find out drop point and drop window */
1504
    if (pt.x < 0 || pt.y < 0 || pt.x > cx || pt.y > cy)
1505
    {
1506 1507
	if (!(GetWindowLongW( hWnd, GWL_EXSTYLE ) & WS_EX_ACCEPTFILES)) return;
	pt.x = pt.y = 0;
1508 1509
    }
    else
1510
    {
1511
        if (!find_drop_window( hWnd, &pt )) return;
1512
    }
1513

1514 1515
    XGetWindowProperty( event->display, DefaultRootWindow(event->display),
                        x11drv_atom(DndSelection), 0, 65535, FALSE,
1516
                        AnyPropertyType, &atom_aux, &dummy,
1517
                        &data_length, &aux_long, &p_data);
1518 1519

    if( !aux_long && p_data)  /* don't bother if > 64K */
1520
    {
1521
        char *p = (char *)p_data;
1522
        char *p_drop;
1523

1524 1525 1526
        aux_long = 0;
        while( *p )  /* calculate buffer size */
        {
1527 1528
            INT len = GetShortPathNameA( p, NULL, 0 );
            if (len) aux_long += len + 1;
1529 1530 1531 1532 1533 1534 1535 1536 1537
            p += strlen(p) + 1;
        }
        if( aux_long && aux_long < 65535 )
        {
            HDROP                 hDrop;
            DROPFILES *lpDrop;

            aux_long += sizeof(DROPFILES) + 1;
            hDrop = GlobalAlloc( GMEM_SHARE, aux_long );
1538
            lpDrop = GlobalLock( hDrop );
1539 1540 1541 1542

            if( lpDrop )
            {
                lpDrop->pFiles = sizeof(DROPFILES);
1543
                lpDrop->pt = pt;
1544
                lpDrop->fNC = FALSE;
1545 1546
                lpDrop->fWide = FALSE;
                p_drop = (char *)(lpDrop + 1);
1547
                p = (char *)p_data;
1548 1549
                while(*p)
                {
1550
                    if (GetShortPathNameA( p, p_drop, aux_long - (p_drop - (char *)lpDrop) ))
1551 1552 1553 1554 1555 1556 1557 1558
                        p_drop += strlen( p_drop ) + 1;
                    p += strlen(p) + 1;
                }
                *p_drop = '\0';
                PostMessageA( hWnd, WM_DROPFILES, (WPARAM)hDrop, 0L );
            }
        }
    }
1559
    if( p_data ) XFree(p_data);
1560 1561 1562 1563 1564
}

/**********************************************************************
 *           EVENT_DropURLs
 *
1565
 * drop items are separated by \n
1566 1567 1568 1569
 * each item is prefixed by its mime type
 *
 * event->data.l[3], event->data.l[4] contains drop x,y position
 */
1570
static void EVENT_DropURLs( HWND hWnd, XClientMessageEvent *event )
1571
{
1572
  struct x11drv_win_data *win_data;
1573 1574 1575 1576 1577
  unsigned long	data_length;
  unsigned long	aux_long, drop_len = 0;
  unsigned char	*p_data = NULL; /* property data */
  char		*p_drop = NULL;
  char          *p, *next;
1578
  int		x, y;
1579
  POINT pos;
1580 1581
  DROPFILES *lpDrop;
  HDROP hDrop;
1582 1583 1584 1585
  union {
    Atom	atom_aux;
    int         i;
    Window      w_aux;
Mike McCormack's avatar
Mike McCormack committed
1586
    unsigned int u;
1587 1588
  }		u; /* unused */

1589
  if (!(GetWindowLongW( hWnd, GWL_EXSTYLE ) & WS_EX_ACCEPTFILES)) return;
1590

1591 1592 1593 1594
  XGetWindowProperty( event->display, DefaultRootWindow(event->display),
                      x11drv_atom(DndSelection), 0, 65535, FALSE,
                      AnyPropertyType, &u.atom_aux, &u.i,
                      &data_length, &aux_long, &p_data);
1595
  if (aux_long)
1596 1597
    WARN("property too large, truncated!\n");
  TRACE("urls=%s\n", p_data);
1598 1599 1600

  if( !aux_long && p_data) {	/* don't bother if > 64K */
    /* calculate length */
Mike McCormack's avatar
Mike McCormack committed
1601
    p = (char*) p_data;
1602 1603 1604 1605
    next = strchr(p, '\n');
    while (p) {
      if (next) *next=0;
      if (strncmp(p,"file:",5) == 0 ) {
1606
	INT len = GetShortPathNameA( p+5, NULL, 0 );
1607 1608
	if (len) drop_len += len + 1;
      }
1609 1610
      if (next) {
	*next = '\n';
1611 1612 1613 1614 1615 1616
	p = next + 1;
	next = strchr(p, '\n');
      } else {
	p = NULL;
      }
    }
1617

1618
    if( drop_len && drop_len < 65535 ) {
1619
      XQueryPointer( event->display, root_window, &u.w_aux, &u.w_aux,
Mike McCormack's avatar
Mike McCormack committed
1620
                     &x, &y, &u.i, &u.i, &u.u);
1621
      pos = root_to_virtual_screen( x, y );
1622

1623
      drop_len += sizeof(DROPFILES) + 1;
1624
      hDrop = GlobalAlloc( GMEM_SHARE, drop_len );
1625
      lpDrop = GlobalLock( hDrop );
1626

1627
      if( lpDrop && (win_data = get_win_data( hWnd )))
1628
      {
1629
	  lpDrop->pFiles = sizeof(DROPFILES);
1630
	  lpDrop->pt = pos;
1631
	  lpDrop->fNC =
1632 1633 1634 1635
	    (pos.x < (win_data->client_rect.left - win_data->whole_rect.left)  ||
	     pos.y < (win_data->client_rect.top - win_data->whole_rect.top)    ||
	     pos.x > (win_data->client_rect.right - win_data->whole_rect.left) ||
	     pos.y > (win_data->client_rect.bottom - win_data->whole_rect.top) );
1636 1637
	  lpDrop->fWide = FALSE;
	  p_drop = (char*)(lpDrop + 1);
1638
          release_win_data( win_data );
1639
      }
1640

1641 1642
      /* create message content */
      if (p_drop) {
Mike McCormack's avatar
Mike McCormack committed
1643
	p = (char*) p_data;
1644 1645 1646 1647
	next = strchr(p, '\n');
	while (p) {
	  if (next) *next=0;
	  if (strncmp(p,"file:",5) == 0 ) {
1648
	    INT len = GetShortPathNameA( p+5, p_drop, 65535 );
1649
	    if (len) {
1650
	      TRACE("drop file %s as %s\n", p+5, p_drop);
1651 1652
	      p_drop += len+1;
	    } else {
1653
	      WARN("can't convert file %s to dos name\n", p+5);
1654 1655
	    }
	  } else {
1656
	    WARN("unknown mime type %s\n", p);
1657
	  }
1658 1659
	  if (next) {
	    *next = '\n';
1660 1661 1662 1663 1664 1665 1666 1667
	    p = next + 1;
	    next = strchr(p, '\n');
	  } else {
	    p = NULL;
	  }
	  *p_drop = '\0';
	}

1668
        GlobalUnlock(hDrop);
1669
        PostMessageA( hWnd, WM_DROPFILES, (WPARAM)hDrop, 0L );
1670 1671 1672
      }
    }
  }
1673
  if( p_data ) XFree(p_data);
1674 1675
}

1676 1677 1678 1679 1680 1681 1682 1683 1684

/**********************************************************************
 *              handle_xembed_protocol
 */
static void handle_xembed_protocol( HWND hwnd, XClientMessageEvent *event )
{
    switch (event->data.l[1])
    {
    case XEMBED_EMBEDDED_NOTIFY:
1685 1686 1687 1688 1689 1690 1691 1692
        {
            struct x11drv_win_data *data = get_win_data( hwnd );
            if (!data) break;

            TRACE( "win %p/%lx XEMBED_EMBEDDED_NOTIFY owner %lx\n", hwnd, event->window, event->data.l[3] );
            data->embedder = event->data.l[3];

            /* window has been marked as embedded before (e.g. systray) */
1693
            if (data->embedded || !data->embedder /* broken QX11EmbedContainer implementation */)
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
            {
                release_win_data( data );
                break;
            }

            make_window_embedded( data );
            release_win_data( data );
            reparent_notify( event->display, hwnd, event->data.l[3], 0, 0 );
        }
        break;

    case XEMBED_WINDOW_DEACTIVATE:
        TRACE( "win %p/%lx XEMBED_WINDOW_DEACTIVATE message\n", hwnd, event->window );
        focus_out( event->display, GetAncestor( hwnd, GA_ROOT ) );
        break;

    case XEMBED_FOCUS_OUT:
        TRACE( "win %p/%lx XEMBED_FOCUS_OUT message\n", hwnd, event->window );
        focus_out( event->display, GetAncestor( hwnd, GA_ROOT ) );
1713
        break;
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724

    case XEMBED_MODALITY_ON:
        TRACE( "win %p/%lx XEMBED_MODALITY_ON message\n", hwnd, event->window );
        EnableWindow( hwnd, FALSE );
        break;

    case XEMBED_MODALITY_OFF:
        TRACE( "win %p/%lx XEMBED_MODALITY_OFF message\n", hwnd, event->window );
        EnableWindow( hwnd, TRUE );
        break;

1725 1726 1727 1728 1729 1730 1731 1732
    default:
        TRACE( "win %p/%lx XEMBED message %lu(%lu)\n",
               hwnd, event->window, event->data.l[1], event->data.l[2] );
        break;
    }
}


1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
/**********************************************************************
 *              handle_dnd_protocol
 */
static void handle_dnd_protocol( HWND hwnd, XClientMessageEvent *event )
{
    Window root, child;
    int root_x, root_y, child_x, child_y;
    unsigned int u;

    /* query window (drag&drop event contains only drag window) */
    XQueryPointer( event->display, root_window, &root, &child,
                   &root_x, &root_y, &child_x, &child_y, &u);
    if (XFindContext( event->display, child, winContext, (char **)&hwnd ) != 0) hwnd = 0;
    if (!hwnd) return;
    if (event->data.l[0] == DndFile || event->data.l[0] == DndFiles)
        EVENT_DropFromOffiX(hwnd, event);
    else if (event->data.l[0] == DndURL)
        EVENT_DropURLs(hwnd, event);
}


struct client_message_handler
{
    int    atom;                                  /* protocol atom */
    void (*handler)(HWND, XClientMessageEvent *); /* corresponding handler function */
};

static const struct client_message_handler client_messages[] =
{
1762
    { XATOM_MANAGER,      handle_manager_message },
1763
    { XATOM_WM_PROTOCOLS, handle_wm_protocols },
1764
    { XATOM__XEMBED,      handle_xembed_protocol },
1765 1766 1767 1768 1769 1770 1771 1772
    { XATOM_DndProtocol,  handle_dnd_protocol },
    { XATOM_XdndEnter,    X11DRV_XDND_EnterEvent },
    { XATOM_XdndPosition, X11DRV_XDND_PositionEvent },
    { XATOM_XdndDrop,     X11DRV_XDND_DropEvent },
    { XATOM_XdndLeave,    X11DRV_XDND_LeaveEvent }
};


1773
/**********************************************************************
1774
 *           X11DRV_ClientMessage
1775
 */
1776
static BOOL X11DRV_ClientMessage( HWND hwnd, XEvent *xev )
1777
{
1778
    XClientMessageEvent *event = &xev->xclient;
1779
    unsigned int i;
1780

1781
    if (!hwnd) return FALSE;
1782

1783
    if (event->format != 32)
1784
    {
1785
        WARN( "Don't know how to handle format %d\n", event->format );
1786
        return FALSE;
1787
    }
1788

1789
    for (i = 0; i < ARRAY_SIZE( client_messages ); i++)
1790
    {
1791 1792 1793
        if (event->message_type == X11DRV_Atoms[client_messages[i].atom - FIRST_XATOM])
        {
            client_messages[i].handler( hwnd, event );
1794
            return TRUE;
1795
        }
1796
    }
1797
    TRACE( "no handler found for %ld\n", event->message_type );
1798
    return FALSE;
1799
}