window.c 95 KB
Newer Older
1 2 3 4 5 6
/*
 * Window related functions
 *
 * Copyright 1993, 1994, 1995, 1996, 2001 Alexandre Julliard
 * Copyright 1993 David Metcalfe
 * Copyright 1995, 1996 Alex Korobka
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * 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
20
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 22 23 24
 */

#include "config.h"

25
#include <stdarg.h>
26
#include <stdlib.h>
27
#include <stdio.h>
28 29 30
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
31

32
#include <X11/Xlib.h>
33 34
#include <X11/Xresource.h>
#include <X11/Xutil.h>
35 36 37
#ifdef HAVE_LIBXSHAPE
#include <X11/extensions/shape.h>
#endif /* HAVE_LIBXSHAPE */
38

39
#include "windef.h"
40 41 42
#include "winbase.h"
#include "wingdi.h"
#include "winuser.h"
43
#include "wine/unicode.h"
44 45

#include "x11drv.h"
46
#include "xcomposite.h"
47 48
#include "wine/debug.h"
#include "wine/server.h"
49
#include "mwm.h"
50

51
WINE_DEFAULT_DEBUG_CHANNEL(x11drv);
52

53 54 55 56 57 58 59 60 61 62 63 64
#define _NET_WM_MOVERESIZE_SIZE_TOPLEFT      0
#define _NET_WM_MOVERESIZE_SIZE_TOP          1
#define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT     2
#define _NET_WM_MOVERESIZE_SIZE_RIGHT        3
#define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT  4
#define _NET_WM_MOVERESIZE_SIZE_BOTTOM       5
#define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT   6
#define _NET_WM_MOVERESIZE_SIZE_LEFT         7
#define _NET_WM_MOVERESIZE_MOVE              8
#define _NET_WM_MOVERESIZE_SIZE_KEYBOARD     9
#define _NET_WM_MOVERESIZE_MOVE_KEYBOARD    10

65 66 67 68 69 70
#define _NET_WM_STATE_REMOVE  0
#define _NET_WM_STATE_ADD     1
#define _NET_WM_STATE_TOGGLE  2

#define SWP_AGG_NOPOSCHANGE (SWP_NOSIZE | SWP_NOMOVE | SWP_NOCLIENTSIZE | SWP_NOCLIENTMOVE | SWP_NOZORDER)

71
/* is cursor clipping active? */
72
int clipping_cursor = 0;
73

74 75 76
/* X context to associate a hwnd to an X window */
XContext winContext = 0;

77
/* X context to associate a struct x11drv_win_data to an hwnd */
78
XContext win_data_context = 0;
79

80 81 82 83
/* time of last user event and window where it's stored */
static Time last_user_time;
static Window user_time_window;

84
static const char foreign_window_prop[] = "__wine_x11_foreign_window";
85
static const char whole_window_prop[] = "__wine_x11_whole_window";
86
static const char client_window_prop[]= "__wine_x11_client_window";
87
static const char icon_window_prop[]  = "__wine_x11_icon_window";
88
static const char clip_window_prop[]  = "__wine_x11_clip_window";
89
static const char fbconfig_id_prop[]  = "__wine_x11_fbconfig_id";
90
static const char gl_drawable_prop[]  = "__wine_x11_gl_drawable";
91
static const char pixmap_prop[]       = "__wine_x11_pixmap";
92
static const char managed_prop[]      = "__wine_x11_managed";
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

/***********************************************************************
 * http://standards.freedesktop.org/startup-notification-spec
 */
static void remove_startup_notification(Display *display, Window window)
{
    static LONG startup_notification_removed = 0;
    char id[1024];
    char message[1024];
    int i;
    int pos;
    XEvent xevent;
    const char *src;
    int srclen;

    if (InterlockedCompareExchange(&startup_notification_removed, 1, 0) != 0)
        return;

    if (GetEnvironmentVariableA("DESKTOP_STARTUP_ID", id, sizeof(id)) == 0)
        return;
    SetEnvironmentVariableA("DESKTOP_STARTUP_ID", NULL);

116 117
    if ((src = strstr( id, "_TIME" ))) update_user_time( atol( src + 5 ));

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    pos = snprintf(message, sizeof(message), "remove: ID=");
    message[pos++] = '"';
    for (i = 0; id[i] && pos < sizeof(message) - 2; i++)
    {
        if (id[i] == '"' || id[i] == '\\')
            message[pos++] = '\\';
        message[pos++] = id[i];
    }
    message[pos++] = '"';
    message[pos++] = '\0';

    xevent.xclient.type = ClientMessage;
    xevent.xclient.message_type = x11drv_atom(_NET_STARTUP_INFO_BEGIN);
    xevent.xclient.display = display;
    xevent.xclient.window = window;
    xevent.xclient.format = 8;

    src = message;
    srclen = strlen(src) + 1;

    while (srclen > 0)
    {
        int msglen = srclen;
        if (msglen > 20)
            msglen = 20;
        memset(&xevent.xclient.data.b[0], 0, 20);
        memcpy(&xevent.xclient.data.b[0], src, msglen);
        src += msglen;
        srclen -= msglen;

        XSendEvent( display, DefaultRootWindow( display ), False, PropertyChangeMask, &xevent );
        xevent.xclient.message_type = x11drv_atom(_NET_STARTUP_INFO);
    }
}


154 155 156 157 158 159
struct has_popup_result
{
    HWND hwnd;
    BOOL found;
};

160
static BOOL CALLBACK has_managed_popup( HWND hwnd, LPARAM lparam )
161 162
{
    struct has_popup_result *result = (struct has_popup_result *)lparam;
163
    struct x11drv_win_data *data;
164 165

    if (hwnd == result->hwnd) return FALSE;  /* popups are always above owner */
166 167 168
    if (!(data = X11DRV_get_win_data( hwnd ))) return TRUE;
    if (GetWindow( hwnd, GW_OWNER ) != result->hwnd) return TRUE;
    result->found = data->managed;
169 170 171 172 173 174 175 176 177
    return !result->found;
}

static BOOL has_owned_popups( HWND hwnd )
{
    struct has_popup_result result;

    result.hwnd = hwnd;
    result.found = FALSE;
178
    EnumWindows( has_managed_popup, (LPARAM)&result );
179 180 181
    return result.found;
}

182
/***********************************************************************
183
 *		is_window_managed
184
 *
185
 * Check if a given window should be managed
186
 */
187
static BOOL is_window_managed( HWND hwnd, UINT swp_flags, const RECT *window_rect )
188
{
189 190
    DWORD style, ex_style;

191 192
    if (!managed_mode) return FALSE;

193
    /* child windows are not managed */
194
    style = GetWindowLongW( hwnd, GWL_STYLE );
195
    if ((style & (WS_CHILD|WS_POPUP)) == WS_CHILD) return FALSE;
196 197 198
    /* activated windows are managed */
    if (!(swp_flags & (SWP_NOACTIVATE|SWP_HIDEWINDOW))) return TRUE;
    if (hwnd == GetActiveWindow()) return TRUE;
199
    /* windows with caption are managed */
200
    if ((style & WS_CAPTION) == WS_CAPTION) return TRUE;
201
    /* windows with thick frame are managed */
202 203
    if (style & WS_THICKFRAME) return TRUE;
    if (style & WS_POPUP)
204
    {
205 206 207
        HMONITOR hmon;
        MONITORINFO mi;

208 209 210
        /* popup with sysmenu == caption are managed */
        if (style & WS_SYSMENU) return TRUE;
        /* full-screen popup windows are managed */
211 212 213 214 215
        hmon = MonitorFromWindow( hwnd, MONITOR_DEFAULTTOPRIMARY );
        mi.cbSize = sizeof( mi );
        GetMonitorInfoW( hmon, &mi );
        if (window_rect->left <= mi.rcWork.left && window_rect->right >= mi.rcWork.right &&
            window_rect->top <= mi.rcWork.top && window_rect->bottom >= mi.rcWork.bottom)
216
            return TRUE;
217
    }
218 219 220
    /* application windows are managed */
    ex_style = GetWindowLongW( hwnd, GWL_EXSTYLE );
    if (ex_style & WS_EX_APPWINDOW) return TRUE;
221 222
    /* windows that own popups are managed */
    if (has_owned_popups( hwnd )) return TRUE;
223 224
    /* default: not managed */
    return FALSE;
225 226 227
}


228 229 230 231 232 233 234 235 236
/***********************************************************************
 *		is_window_resizable
 *
 * Check if window should be made resizable by the window manager
 */
static inline BOOL is_window_resizable( struct x11drv_win_data *data, DWORD style )
{
    if (style & WS_THICKFRAME) return TRUE;
    /* Metacity needs the window to be resizable to make it fullscreen */
237
    return is_window_rect_fullscreen( &data->whole_rect );
238 239 240
}


241 242 243
/***********************************************************************
 *              get_mwm_decorations
 */
244 245
static unsigned long get_mwm_decorations( struct x11drv_win_data *data,
                                          DWORD style, DWORD ex_style )
246 247 248
{
    unsigned long ret = 0;

249 250 251
    if (!decorated_mode) return 0;

    if (IsRectEmpty( &data->window_rect )) return 0;
252
    if (data->shaped) return 0;
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    if (ex_style & WS_EX_TOOLWINDOW) return 0;

    if ((style & WS_CAPTION) == WS_CAPTION)
    {
        ret |= MWM_DECOR_TITLE | MWM_DECOR_BORDER;
        if (style & WS_SYSMENU) ret |= MWM_DECOR_MENU;
        if (style & WS_MINIMIZEBOX) ret |= MWM_DECOR_MINIMIZE;
        if (style & WS_MAXIMIZEBOX) ret |= MWM_DECOR_MAXIMIZE;
    }
    if (ex_style & WS_EX_DLGMODALFRAME) ret |= MWM_DECOR_BORDER;
    else if (style & WS_THICKFRAME) ret |= MWM_DECOR_BORDER | MWM_DECOR_RESIZEH;
    else if ((style & (WS_DLGFRAME|WS_BORDER)) == WS_DLGFRAME) ret |= MWM_DECOR_BORDER;
    return ret;
}


/***********************************************************************
 *		get_x11_rect_offset
 *
 * Helper for X11DRV_window_to_X_rect and X11DRV_X_to_window_rect.
 */
static void get_x11_rect_offset( struct x11drv_win_data *data, RECT *rect )
{
    DWORD style, ex_style, style_mask = 0, ex_style_mask = 0;
    unsigned long decor;

    rect->top = rect->bottom = rect->left = rect->right = 0;

    style = GetWindowLongW( data->hwnd, GWL_STYLE );
    ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
284
    decor = get_mwm_decorations( data, style, ex_style );
285 286 287 288 289 290 291 292 293 294 295 296

    if (decor & MWM_DECOR_TITLE) style_mask |= WS_CAPTION;
    if (decor & MWM_DECOR_BORDER)
    {
        style_mask |= WS_DLGFRAME | WS_THICKFRAME;
        ex_style_mask |= WS_EX_DLGMODALFRAME;
    }

    AdjustWindowRectEx( rect, style & style_mask, FALSE, ex_style & ex_style_mask );
}


297 298 299
/***********************************************************************
 *              get_window_attributes
 *
300
 * Fill the window attributes structure for an X window.
301
 */
302 303
static int get_window_attributes( Display *display, struct x11drv_win_data *data,
                                  XSetWindowAttributes *attr )
304
{
305
    attr->override_redirect = !data->managed;
306
    attr->colormap          = X11DRV_PALETTE_PaletteXColormap;
307
    attr->save_under        = ((GetClassLongW( data->hwnd, GCL_STYLE ) & CS_SAVEBITS) != 0);
308
    attr->bit_gravity       = NorthWestGravity;
309
    attr->win_gravity       = StaticGravity;
310 311 312
    attr->backing_store     = NotUseful;
    attr->event_mask        = (ExposureMask | PointerMotionMask |
                               ButtonPressMask | ButtonReleaseMask | EnterWindowMask |
313 314 315
                               KeyPressMask | KeyReleaseMask | FocusChangeMask |
                               KeymapStateMask | StructureNotifyMask);
    if (data->managed) attr->event_mask |= PropertyChangeMask;
316

317
    return (CWOverrideRedirect | CWSaveUnder | CWColormap |
318
            CWEventMask | CWBitGravity | CWBackingStore);
319 320 321
}


322 323 324 325 326 327 328 329
/***********************************************************************
 *              create_client_window
 */
static Window create_client_window( Display *display, struct x11drv_win_data *data, XVisualInfo *vis )
{
    int cx, cy, mask;
    XSetWindowAttributes attr;
    Window client;
330
    Visual *client_visual = vis ? vis->visual : visual;
331 332 333 334 335 336 337 338 339

    attr.bit_gravity = NorthWestGravity;
    attr.win_gravity = NorthWestGravity;
    attr.backing_store = NotUseful;
    attr.event_mask = (ExposureMask | PointerMotionMask |
                       ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
    mask = CWEventMask | CWBitGravity | CWWinGravity | CWBackingStore;

    if ((cx = data->client_rect.right - data->client_rect.left) <= 0) cx = 1;
340
    else if (cx > 65535) cx = 65535;
341
    if ((cy = data->client_rect.bottom - data->client_rect.top) <= 0) cy = 1;
342
    else if (cy > 65535) cy = 65535;
343 344 345 346 347 348 349 350 351 352 353 354 355

    if (vis)
    {
        attr.colormap = XCreateColormap( display, root_window, vis->visual,
                                         (vis->class == PseudoColor || vis->class == GrayScale ||
                                          vis->class == DirectColor) ? AllocAll : AllocNone );
        mask |= CWColormap;
    }

    client = XCreateWindow( display, data->whole_window,
                            data->client_rect.left - data->whole_rect.left,
                            data->client_rect.top - data->whole_rect.top,
                            cx, cy, 0, screen_depth, InputOutput,
356
                            client_visual, mask, &attr );
357 358
    if (!client)
    {
359
        if (vis) XFreeColormap( display, attr.colormap );
360 361 362 363 364 365 366 367 368
        return 0;
    }

    if (data->client_window)
    {
        XDeleteContext( display, data->client_window, winContext );
        XDestroyWindow( display, data->client_window );
    }
    data->client_window = client;
369
    data->visualid = XVisualIDFromVisual( client_visual );
370 371 372 373 374 375 376 377 378 379 380

    if (data->colormap) XFreeColormap( display, data->colormap );
    data->colormap = vis ? attr.colormap : 0;

    XMapWindow( display, data->client_window );
    XSaveContext( display, data->client_window, winContext, (char *)data->hwnd );
    SetPropA( data->hwnd, client_window_prop, (HANDLE)data->client_window );
    return data->client_window;
}


381
/***********************************************************************
382
 *              sync_window_style
383 384 385
 *
 * Change the X window attributes when the window style has changed.
 */
386
static void sync_window_style( Display *display, struct x11drv_win_data *data )
387
{
388 389 390 391
    if (data->whole_window != root_window)
    {
        XSetWindowAttributes attr;
        int mask = get_window_attributes( display, data, &attr );
392

393
        XChangeWindowAttributes( display, data->whole_window, mask, &attr );
394
    }
395
}
396

397

398 399 400 401 402
/***********************************************************************
 *              sync_window_region
 *
 * Update the X11 window region.
 */
403
static void sync_window_region( Display *display, struct x11drv_win_data *data, HRGN win_region )
404 405
{
#ifdef HAVE_LIBXSHAPE
406 407
    HRGN hrgn = win_region;

408
    if (!data->whole_window) return;
409
    data->shaped = FALSE;
410

411 412 413 414 415 416 417 418
    if (IsRectEmpty( &data->window_rect ))  /* set an empty shape */
    {
        static XRectangle empty_rect;
        XShapeCombineRectangles( display, data->whole_window, ShapeBounding, 0, 0,
                                 &empty_rect, 1, ShapeSet, YXBanded );
        return;
    }

419 420 421 422 423 424 425 426 427 428
    if (hrgn == (HRGN)1)  /* hack: win_region == 1 means retrieve region from server */
    {
        if (!(hrgn = CreateRectRgn( 0, 0, 0, 0 ))) return;
        if (GetWindowRgn( data->hwnd, hrgn ) == ERROR)
        {
            DeleteObject( hrgn );
            hrgn = 0;
        }
    }

429 430 431 432 433 434
    if (!hrgn)
    {
        XShapeCombineMask( display, data->whole_window, ShapeBounding, 0, 0, None, ShapeSet );
    }
    else
    {
435 436 437 438
        RGNDATA *pRegionData;

        if (GetWindowLongW( data->hwnd, GWL_EXSTYLE ) & WS_EX_LAYOUTRTL) MirrorRgn( data->hwnd, hrgn );
        if ((pRegionData = X11DRV_GetRegionData( hrgn, 0 )))
439 440 441 442 443 444 445
        {
            XShapeCombineRectangles( display, data->whole_window, ShapeBounding,
                                     data->window_rect.left - data->whole_rect.left,
                                     data->window_rect.top - data->whole_rect.top,
                                     (XRectangle *)pRegionData->Buffer,
                                     pRegionData->rdh.nCount, ShapeSet, YXBanded );
            HeapFree(GetProcessHeap(), 0, pRegionData);
446
            data->shaped = TRUE;
447 448
        }
    }
449
    if (hrgn && hrgn != win_region) DeleteObject( hrgn );
450 451 452 453
#endif  /* HAVE_LIBXSHAPE */
}


454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
/***********************************************************************
 *              sync_window_opacity
 */
static void sync_window_opacity( Display *display, Window win,
                                 COLORREF key, BYTE alpha, DWORD flags )
{
    unsigned long opacity = 0xffffffff;

    if (flags & LWA_ALPHA) opacity = (0xffffffff / 0xff) * alpha;

    if (flags & LWA_COLORKEY) FIXME("LWA_COLORKEY not supported\n");

    if (opacity == 0xffffffff)
        XDeleteProperty( display, win, x11drv_atom(_NET_WM_WINDOW_OPACITY) );
    else
        XChangeProperty( display, win, x11drv_atom(_NET_WM_WINDOW_OPACITY),
                         XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&opacity, 1 );
}


474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
/***********************************************************************
 *              sync_window_text
 */
static void sync_window_text( Display *display, Window win, const WCHAR *text )
{
    UINT count;
    char *buffer, *utf8_buffer;
    XTextProperty prop;

    /* allocate new buffer for window text */
    count = WideCharToMultiByte(CP_UNIXCP, 0, text, -1, NULL, 0, NULL, NULL);
    if (!(buffer = HeapAlloc( GetProcessHeap(), 0, count ))) return;
    WideCharToMultiByte(CP_UNIXCP, 0, text, -1, buffer, count, NULL, NULL);

    count = WideCharToMultiByte(CP_UTF8, 0, text, strlenW(text), NULL, 0, NULL, NULL);
    if (!(utf8_buffer = HeapAlloc( GetProcessHeap(), 0, count )))
    {
        HeapFree( GetProcessHeap(), 0, buffer );
        return;
    }
    WideCharToMultiByte(CP_UTF8, 0, text, strlenW(text), utf8_buffer, count, NULL, NULL);

    if (XmbTextListToTextProperty( display, &buffer, 1, XStdICCTextStyle, &prop ) == Success)
    {
        XSetWMName( display, win, &prop );
        XSetWMIconName( display, win, &prop );
        XFree( prop.value );
    }
    /*
      Implements a NET_WM UTF-8 title. It should be without a trailing \0,
      according to the standard
      ( http://www.pps.jussieu.fr/~jch/software/UTF8_STRING/UTF8_STRING.text ).
    */
    XChangeProperty( display, win, x11drv_atom(_NET_WM_NAME), x11drv_atom(UTF8_STRING),
                     8, PropModeReplace, (unsigned char *) utf8_buffer, count);

    HeapFree( GetProcessHeap(), 0, utf8_buffer );
    HeapFree( GetProcessHeap(), 0, buffer );
}


515
/***********************************************************************
516
 *              set_win_format
517
 */
518
static BOOL set_win_format( HWND hwnd, XID fbconfig_id )
519 520
{
    struct x11drv_win_data *data;
521 522
    XVisualInfo *vis;
    int w, h;
523

524 525
    if (!(data = X11DRV_get_win_data(hwnd)) &&
        !(data = X11DRV_create_win_data(hwnd))) return FALSE;
526

527
    if (!(vis = visual_from_fbconfig_id(fbconfig_id))) return FALSE;
528

529
    if (data->whole_window)
530
    {
531
        Display *display = thread_display();
532 533
        Window client = data->client_window;

534
        if (vis->visualid != data->visualid)
535
        {
536 537
            client = create_client_window( display, data, vis );
            TRACE( "re-created client window %lx for %p fbconfig %lx\n", client, data->hwnd, fbconfig_id );
538
        }
539
        XFree(vis);
540
        XFlush( display );
541 542
        if (client) goto done;
        return FALSE;
543 544 545 546 547 548 549 550 551 552 553 554
    }

    w = data->client_rect.right - data->client_rect.left;
    h = data->client_rect.bottom - data->client_rect.top;

    if(w <= 0) w = 1;
    if(h <= 0) h = 1;

#ifdef SONAME_LIBXCOMPOSITE
    if(usexcomposite)
    {
        XSetWindowAttributes attrib;
555
        static Window dummy_parent;
556

557 558 559 560 561 562 563 564
        attrib.override_redirect = True;
        if (!dummy_parent)
        {
            dummy_parent = XCreateWindow( gdi_display, root_window, -1, -1, 1, 1, 0, screen_depth,
                                         InputOutput, visual, CWOverrideRedirect, &attrib );
            XMapWindow( gdi_display, dummy_parent );
        }
        data->colormap = XCreateColormap(gdi_display, dummy_parent, vis->visual,
565 566 567 568 569
                                         (vis->class == PseudoColor ||
                                          vis->class == GrayScale ||
                                          vis->class == DirectColor) ?
                                         AllocAll : AllocNone);
        attrib.colormap = data->colormap;
570 571
        XInstallColormap(gdi_display, attrib.colormap);

572
        if(data->gl_drawable) XDestroyWindow(gdi_display, data->gl_drawable);
573
        data->gl_drawable = XCreateWindow(gdi_display, dummy_parent, 0, 0, w, h, 0,
574 575 576 577 578
                                          vis->depth, InputOutput, vis->visual,
                                          CWColormap | CWOverrideRedirect,
                                          &attrib);
        if(data->gl_drawable)
        {
579
            pXCompositeRedirectWindow(gdi_display, data->gl_drawable,
580
                                      CompositeRedirectManual);
581
            XMapWindow(gdi_display, data->gl_drawable);
582
        }
583
        XFree(vis);
584
        XFlush( gdi_display );
585
    }
586
    else
587
#endif
588 589 590
    {
        WARN("XComposite is not available, using GLXPixmap hack\n");

591 592
        if(data->pixmap) XFreePixmap(gdi_display, data->pixmap);
        data->pixmap = XCreatePixmap(gdi_display, root_window, w, h, vis->depth);
593 594 595 596 597 598
        if(!data->pixmap)
        {
            XFree(vis);
            return FALSE;
        }

599 600
        if(data->gl_drawable) destroy_glxpixmap(gdi_display, data->gl_drawable);
        data->gl_drawable = create_glxpixmap(gdi_display, vis, data->pixmap);
601 602
        if(!data->gl_drawable)
        {
603
            XFreePixmap(gdi_display, data->pixmap);
604 605
            data->pixmap = 0;
        }
606
        XFree(vis);
607
        XFlush( gdi_display );
608
        if (data->pixmap) SetPropA(hwnd, pixmap_prop, (HANDLE)data->pixmap);
609 610
    }

611
    if (!data->gl_drawable) return FALSE;
612 613 614

    TRACE("Created GL drawable 0x%lx, using FBConfigID 0x%lx\n",
          data->gl_drawable, fbconfig_id);
615
    SetPropA(hwnd, gl_drawable_prop, (HANDLE)data->gl_drawable);
616

617
done:
618 619
    data->fbconfig_id = fbconfig_id;
    SetPropA(hwnd, fbconfig_id_prop, (HANDLE)data->fbconfig_id);
620 621 622
    /* force DCE invalidation */
    SetWindowPos( hwnd, 0, 0, 0, 0, 0,
                  SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE |
623
                  SWP_NOREDRAW | SWP_DEFERERASE | SWP_NOSENDCHANGING | SWP_STATECHANGED);
624 625 626
    return TRUE;
}

627
/***********************************************************************
628
 *              sync_gl_drawable
629
 */
630
static void sync_gl_drawable(struct x11drv_win_data *data)
631 632 633
{
    int w = data->client_rect.right - data->client_rect.left;
    int h = data->client_rect.bottom - data->client_rect.top;
634 635 636
    XVisualInfo *vis;
    Drawable glxp;
    Pixmap pix;
637

638 639 640
    if (w <= 0) w = 1;
    if (h <= 0) h = 1;

641 642 643 644
    TRACE("Resizing GL drawable 0x%lx to %dx%d\n", data->gl_drawable, w, h);
#ifdef SONAME_LIBXCOMPOSITE
    if(usexcomposite)
    {
645
        XMoveResizeWindow(gdi_display, data->gl_drawable, 0, 0, w, h);
646 647 648
        return;
    }
#endif
649

650
    if (!(vis = visual_from_fbconfig_id(data->fbconfig_id))) return;
651

652
    pix = XCreatePixmap(gdi_display, root_window, w, h, vis->depth);
653 654 655 656 657 658 659
    if(!pix)
    {
        ERR("Failed to create pixmap for offscreen rendering\n");
        XFree(vis);
        return;
    }

660
    glxp = create_glxpixmap(gdi_display, vis, pix);
661 662 663
    if(!glxp)
    {
        ERR("Failed to create drawable for offscreen rendering\n");
664
        XFreePixmap(gdi_display, pix);
665 666 667 668 669 670 671 672
        XFree(vis);
        return;
    }

    XFree(vis);

    mark_drawable_dirty(data->gl_drawable, glxp);

673 674
    XFreePixmap(gdi_display, data->pixmap);
    destroy_glxpixmap(gdi_display, data->gl_drawable);
675
    TRACE( "Recreated GL drawable %lx to replace %lx\n", glxp, data->gl_drawable );
676 677 678 679

    data->pixmap = pix;
    data->gl_drawable = glxp;

680
    XFlush( gdi_display );
681 682 683

    SetPropA(data->hwnd, gl_drawable_prop, (HANDLE)data->gl_drawable);
    SetPropA(data->hwnd, pixmap_prop, (HANDLE)data->pixmap);
684 685
}

686

687 688 689 690 691 692 693 694 695 696 697
/***********************************************************************
 *              get_window_changes
 *
 * fill the window changes structure
 */
static int get_window_changes( XWindowChanges *changes, const RECT *old, const RECT *new )
{
    int mask = 0;

    if (old->right - old->left != new->right - new->left )
    {
698
        if ((changes->width = new->right - new->left) <= 0) changes->width = 1;
699
        else if (changes->width > 65535) changes->width = 65535;
700 701 702 703
        mask |= CWWidth;
    }
    if (old->bottom - old->top != new->bottom - new->top)
    {
704
        if ((changes->height = new->bottom - new->top) <= 0) changes->height = 1;
705
        else if (changes->height > 65535) changes->height = 65535;
706 707 708 709 710 711 712 713 714 715 716
        mask |= CWHeight;
    }
    if (old->left != new->left)
    {
        changes->x = new->left;
        mask |= CWX;
    }
    if (old->top != new->top)
    {
        changes->y = new->top;
        mask |= CWY;
717
    }
718 719 720 721 722 723 724
    return mask;
}


/***********************************************************************
 *              create_icon_window
 */
725
static Window create_icon_window( Display *display, struct x11drv_win_data *data )
726 727 728 729
{
    XSetWindowAttributes attr;

    attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
730
                       ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
731 732
    attr.bit_gravity = NorthWestGravity;
    attr.backing_store = NotUseful/*WhenMapped*/;
733
    attr.colormap      = X11DRV_PALETTE_PaletteXColormap; /* Needed due to our visual */
734

735 736 737 738 739
    data->icon_window = XCreateWindow( display, root_window, 0, 0,
                                       GetSystemMetrics( SM_CXICON ),
                                       GetSystemMetrics( SM_CYICON ),
                                       0, screen_depth,
                                       InputOutput, visual,
740
                                       CWEventMask | CWBitGravity | CWBackingStore | CWColormap, &attr );
741
    XSaveContext( display, data->icon_window, winContext, (char *)data->hwnd );
742
    XFlush( display );  /* make sure the window exists before we start painting to it */
743

744
    TRACE( "created %lx\n", data->icon_window );
745
    SetPropA( data->hwnd, icon_window_prop, (HANDLE)data->icon_window );
746 747 748 749 750 751 752 753
    return data->icon_window;
}



/***********************************************************************
 *              destroy_icon_window
 */
754
static void destroy_icon_window( Display *display, struct x11drv_win_data *data )
755 756 757 758 759
{
    if (!data->icon_window) return;
    XDeleteContext( display, data->icon_window, winContext );
    XDestroyWindow( display, data->icon_window );
    data->icon_window = 0;
760
    RemovePropA( data->hwnd, icon_window_prop );
761 762 763
}


764 765 766 767 768 769 770
/***********************************************************************
 *              get_bitmap_argb
 *
 * Return the bitmap bits in ARGB format. Helper for setting icon hints.
 */
static unsigned long *get_bitmap_argb( HDC hdc, HBITMAP color, HBITMAP mask, unsigned int *size )
{
771 772
    char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *info = (BITMAPINFO *)buffer;
773
    BITMAP bm;
774 775 776
    unsigned int *ptr, *bits = NULL;
    unsigned char *mask_bits = NULL;
    int i, j, has_alpha = 0;
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796

    if (!GetObjectW( color, sizeof(bm), &bm )) return NULL;
    info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info->bmiHeader.biWidth = bm.bmWidth;
    info->bmiHeader.biHeight = -bm.bmHeight;
    info->bmiHeader.biPlanes = 1;
    info->bmiHeader.biBitCount = 32;
    info->bmiHeader.biCompression = BI_RGB;
    info->bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
    info->bmiHeader.biXPelsPerMeter = 0;
    info->bmiHeader.biYPelsPerMeter = 0;
    info->bmiHeader.biClrUsed = 0;
    info->bmiHeader.biClrImportant = 0;
    *size = bm.bmWidth * bm.bmHeight + 2;
    if (!(bits = HeapAlloc( GetProcessHeap(), 0, *size * sizeof(long) ))) goto failed;
    if (!GetDIBits( hdc, color, 0, bm.bmHeight, bits + 2, info, DIB_RGB_COLORS )) goto failed;

    bits[0] = bm.bmWidth;
    bits[1] = bm.bmHeight;

797 798 799 800 801 802 803 804 805 806 807 808 809 810
    for (i = 0; i < bm.bmWidth * bm.bmHeight; i++)
        if ((has_alpha = (bits[i + 2] & 0xff000000) != 0)) break;

    if (!has_alpha)
    {
        unsigned int width_bytes = (bm.bmWidth + 31) / 32 * 4;
        /* generate alpha channel from the mask */
        info->bmiHeader.biBitCount = 1;
        info->bmiHeader.biSizeImage = width_bytes * bm.bmHeight;
        if (!(mask_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto failed;
        if (!GetDIBits( hdc, mask, 0, bm.bmHeight, mask_bits, info, DIB_RGB_COLORS )) goto failed;
        ptr = bits + 2;
        for (i = 0; i < bm.bmHeight; i++)
            for (j = 0; j < bm.bmWidth; j++, ptr++)
811
                if (!((mask_bits[i * width_bytes + j / 8] << (j % 8)) & 0x80)) *ptr |= 0xff000000;
812
        HeapFree( GetProcessHeap(), 0, mask_bits );
813 814
    }

815 816 817 818 819 820 821 822
    /* convert to array of longs */
    if (bits && sizeof(long) > sizeof(int))
        for (i = *size - 1; i >= 0; i--) ((unsigned long *)bits)[i] = bits[i];

    return (unsigned long *)bits;

failed:
    HeapFree( GetProcessHeap(), 0, bits );
823
    HeapFree( GetProcessHeap(), 0, mask_bits );
824 825 826 827
    return NULL;
}


828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
/***********************************************************************
 *              create_icon_pixmaps
 */
static BOOL create_icon_pixmaps( HDC hdc, const ICONINFO *icon, struct x11drv_win_data *data )
{
    char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *info = (BITMAPINFO *)buffer;
    XVisualInfo vis;
    struct gdi_image_bits bits;
    Pixmap color_pixmap = 0, mask_pixmap = 0;
    int i, lines;

    bits.ptr = NULL;
    bits.free = NULL;
    bits.is_copy = TRUE;

    info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info->bmiHeader.biBitCount = 0;
    if (!(lines = GetDIBits( hdc, icon->hbmColor, 0, 0, NULL, info, DIB_RGB_COLORS ))) goto failed;
    if (!(bits.ptr = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto failed;
    if (!GetDIBits( hdc, icon->hbmColor, 0, lines, bits.ptr, info, DIB_RGB_COLORS )) goto failed;

    vis.visual     = visual;
    vis.depth      = screen_depth;
    vis.visualid   = visual->visualid;
    vis.class      = visual->class;
    vis.red_mask   = visual->red_mask;
    vis.green_mask = visual->green_mask;
    vis.blue_mask  = visual->blue_mask;
    color_pixmap = create_pixmap_from_image( hdc, &vis, info, &bits, DIB_RGB_COLORS );
    HeapFree( GetProcessHeap(), 0, bits.ptr );
    bits.ptr = NULL;
    if (!color_pixmap) goto failed;

    info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info->bmiHeader.biBitCount = 0;
    if (!(lines = GetDIBits( hdc, icon->hbmMask, 0, 0, NULL, info, DIB_RGB_COLORS ))) goto failed;
    if (!(bits.ptr = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto failed;
    if (!GetDIBits( hdc, icon->hbmMask, 0, lines, bits.ptr, info, DIB_RGB_COLORS )) goto failed;

    /* invert the mask */
    for (i = 0; i < info->bmiHeader.biSizeImage / sizeof(DWORD); i++) ((DWORD *)bits.ptr)[i] ^= ~0u;

    vis.depth = 1;
    mask_pixmap = create_pixmap_from_image( hdc, &vis, info, &bits, DIB_RGB_COLORS );
    HeapFree( GetProcessHeap(), 0, bits.ptr );
    bits.ptr = NULL;
    if (!mask_pixmap) goto failed;

    data->icon_pixmap = color_pixmap;
    data->icon_mask = mask_pixmap;
    return TRUE;

failed:
    if (color_pixmap) XFreePixmap( gdi_display, color_pixmap );
    if (mask_pixmap) XFreePixmap( gdi_display, mask_pixmap );
    HeapFree( GetProcessHeap(), 0, bits.ptr );
    return FALSE;
}


889 890 891 892 893
/***********************************************************************
 *              set_icon_hints
 *
 * Set the icon wm hints
 */
894 895
static void set_icon_hints( Display *display, struct x11drv_win_data *data,
                            HICON icon_big, HICON icon_small )
896
{
897 898
    XWMHints *hints = data->wm_hints;

899 900 901 902 903 904 905 906 907 908 909
    if (!icon_big)
    {
        icon_big = (HICON)SendMessageW( data->hwnd, WM_GETICON, ICON_BIG, 0 );
        if (!icon_big) icon_big = (HICON)GetClassLongPtrW( data->hwnd, GCLP_HICON );
    }
    if (!icon_small)
    {
        icon_small = (HICON)SendMessageW( data->hwnd, WM_GETICON, ICON_SMALL, 0 );
        if (!icon_small) icon_small = (HICON)GetClassLongPtrW( data->hwnd, GCLP_HICONSM );
    }

910 911 912
    if (data->icon_pixmap) XFreePixmap( gdi_display, data->icon_pixmap );
    if (data->icon_mask) XFreePixmap( gdi_display, data->icon_mask );
    data->icon_pixmap = data->icon_mask = 0;
913

914
    if (!icon_big)
915
    {
916
        if (!data->icon_window) create_icon_window( display, data );
917 918
        hints->icon_window = data->icon_window;
        hints->flags = (hints->flags & ~(IconPixmapHint | IconMaskHint)) | IconWindowHint;
919 920 921
    }
    else
    {
922
        ICONINFO ii, ii_small;
923
        HDC hDC;
924 925
        unsigned int size;
        unsigned long *bits;
926

927
        if (!GetIconInfo(icon_big, &ii)) return;
928 929

        hDC = CreateCompatibleDC(0);
930
        bits = get_bitmap_argb( hDC, ii.hbmColor, ii.hbmMask, &size );
931
        if (bits && GetIconInfo( icon_small, &ii_small ))
932 933 934 935
        {
            unsigned int size_small;
            unsigned long *bits_small, *new;

936
            if ((bits_small = get_bitmap_argb( hDC, ii_small.hbmColor, ii_small.hbmMask, &size_small )) &&
937
                (bits_small[0] != bits[0] || bits_small[1] != bits[1]))  /* size must be different */
938 939 940 941 942 943 944 945 946
            {
                if ((new = HeapReAlloc( GetProcessHeap(), 0, bits,
                                        (size + size_small) * sizeof(unsigned long) )))
                {
                    bits = new;
                    memcpy( bits + size, bits_small, size_small * sizeof(unsigned long) );
                    size += size_small;
                }
            }
947
            HeapFree( GetProcessHeap(), 0, bits_small );
948 949
            DeleteObject( ii_small.hbmColor );
            DeleteObject( ii_small.hbmMask );
950
        }
951 952 953 954 955 956
        if (bits)
            XChangeProperty( display, data->whole_window, x11drv_atom(_NET_WM_ICON),
                             XA_CARDINAL, 32, PropModeReplace, (unsigned char *)bits, size );
        else
            XDeleteProperty( display, data->whole_window, x11drv_atom(_NET_WM_ICON) );
        HeapFree( GetProcessHeap(), 0, bits );
957

958 959 960 961 962 963
        if (create_icon_pixmaps( hDC, &ii, data ))
        {
            hints->icon_pixmap = data->icon_pixmap;
            hints->icon_mask = data->icon_mask;
            hints->flags |= IconPixmapHint | IconMaskHint;
        }
964
        destroy_icon_window( display, data );
965
        hints->flags &= ~IconWindowHint;
966

967 968
        DeleteObject( ii.hbmColor );
        DeleteObject( ii.hbmMask );
969
        DeleteDC(hDC);
970 971 972 973 974
    }
}


/***********************************************************************
975
 *              set_size_hints
976
 *
977
 * set the window size hints
978
 */
979
static void set_size_hints( Display *display, struct x11drv_win_data *data, DWORD style )
980
{
981 982
    XSizeHints* size_hints;

983
    if (!(size_hints = XAllocSizeHints())) return;
984

985 986 987
    size_hints->win_gravity = StaticGravity;
    size_hints->flags |= PWinGravity;

988 989 990
    /* don't update size hints if window is not in normal state */
    if (!(style & (WS_MINIMIZE | WS_MAXIMIZE)))
    {
991 992 993 994
        if (data->hwnd != GetDesktopWindow())  /* don't force position of desktop */
        {
            size_hints->x = data->whole_rect.left;
            size_hints->y = data->whole_rect.top;
995
            size_hints->flags |= PPosition;
996
        }
997
        else size_hints->win_gravity = NorthWestGravity;
998

999
        if (!is_window_resizable( data, style ))
1000
        {
1001 1002
            size_hints->max_width = data->whole_rect.right - data->whole_rect.left;
            size_hints->max_height = data->whole_rect.bottom - data->whole_rect.top;
1003 1004
            if (size_hints->max_width <= 0 ||size_hints->max_height <= 0)
                size_hints->max_width = size_hints->max_height = 1;
1005 1006 1007
            size_hints->min_width = size_hints->max_width;
            size_hints->min_height = size_hints->max_height;
            size_hints->flags |= PMinSize | PMaxSize;
1008 1009
        }
    }
1010 1011
    XSetWMNormalHints( display, data->whole_window, size_hints );
    XFree( size_hints );
1012 1013 1014
}


1015 1016 1017 1018 1019 1020 1021
/***********************************************************************
 *              set_mwm_hints
 */
static void set_mwm_hints( Display *display, struct x11drv_win_data *data, DWORD style, DWORD ex_style )
{
    MwmHints mwm_hints;

1022 1023
    if (data->hwnd == GetDesktopWindow())
    {
1024 1025 1026
        if (is_desktop_fullscreen()) mwm_hints.decorations = 0;
        else mwm_hints.decorations = MWM_DECOR_TITLE | MWM_DECOR_BORDER | MWM_DECOR_MENU | MWM_DECOR_MINIMIZE;
        mwm_hints.functions        = MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE | MWM_FUNC_CLOSE;
1027 1028
    }
    else
1029
    {
1030 1031 1032 1033 1034 1035 1036 1037 1038
        mwm_hints.decorations = get_mwm_decorations( data, style, ex_style );
        mwm_hints.functions = MWM_FUNC_MOVE;
        if (is_window_resizable( data, style )) mwm_hints.functions |= MWM_FUNC_RESIZE;
        if (!(style & WS_DISABLED))
        {
            if (style & WS_MINIMIZEBOX) mwm_hints.functions |= MWM_FUNC_MINIMIZE;
            if (style & WS_MAXIMIZEBOX) mwm_hints.functions |= MWM_FUNC_MAXIMIZE;
            if (style & WS_SYSMENU)     mwm_hints.functions |= MWM_FUNC_CLOSE;
        }
1039
    }
1040

1041 1042 1043
    TRACE( "%p setting mwm hints to %lx,%lx (style %x exstyle %x)\n",
           data->hwnd, mwm_hints.decorations, mwm_hints.functions, style, ex_style );

1044
    mwm_hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
1045 1046 1047 1048 1049 1050
    XChangeProperty( display, data->whole_window, x11drv_atom(_MOTIF_WM_HINTS),
                     x11drv_atom(_MOTIF_WM_HINTS), 32, PropModeReplace,
                     (unsigned char*)&mwm_hints, sizeof(mwm_hints)/sizeof(long) );
}


1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
/***********************************************************************
 *              get_process_name
 *
 * get the name of the current process for setting class hints
 */
static char *get_process_name(void)
{
    static char *name;

    if (!name)
    {
        WCHAR module[MAX_PATH];
        DWORD len = GetModuleFileNameW( 0, module, MAX_PATH );
        if (len && len < MAX_PATH)
        {
            char *ptr;
            WCHAR *p, *appname = module;

            if ((p = strrchrW( appname, '/' ))) appname = p + 1;
            if ((p = strrchrW( appname, '\\' ))) appname = p + 1;
            len = WideCharToMultiByte( CP_UNIXCP, 0, appname, -1, NULL, 0, NULL, NULL );
            if ((ptr = HeapAlloc( GetProcessHeap(), 0, len )))
            {
                WideCharToMultiByte( CP_UNIXCP, 0, appname, -1, ptr, len, NULL, NULL );
                name = ptr;
            }
        }
    }
    return name;
}


1083 1084 1085 1086 1087 1088 1089
/***********************************************************************
 *              set_initial_wm_hints
 *
 * Set the window manager hints that don't change over the lifetime of a window.
 */
static void set_initial_wm_hints( Display *display, struct x11drv_win_data *data )
{
1090
    long i;
1091
    Atom protocols[3];
1092
    Atom dndVersion = WINE_XDND_VERSION;
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    XClassHint *class_hints;
    char *process_name = get_process_name();

    /* wm protocols */
    i = 0;
    protocols[i++] = x11drv_atom(WM_DELETE_WINDOW);
    protocols[i++] = x11drv_atom(_NET_WM_PING);
    if (use_take_focus) protocols[i++] = x11drv_atom(WM_TAKE_FOCUS);
    XChangeProperty( display, data->whole_window, x11drv_atom(WM_PROTOCOLS),
                     XA_ATOM, 32, PropModeReplace, (unsigned char *)protocols, i );

    /* class hints */
    if ((class_hints = XAllocClassHint()))
    {
        static char wine[] = "Wine";

        class_hints->res_name = process_name;
        class_hints->res_class = wine;
        XSetClassHint( display, data->whole_window, class_hints );
        XFree( class_hints );
    }

    /* set the WM_CLIENT_MACHINE and WM_LOCALE_NAME properties */
    XSetWMProperties(display, data->whole_window, NULL, NULL, NULL, 0, NULL, NULL, NULL);
    /* set the pid. together, these properties are needed so the window manager can kill us if we freeze */
    i = getpid();
    XChangeProperty(display, data->whole_window, x11drv_atom(_NET_WM_PID),
                    XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&i, 1);

    XChangeProperty( display, data->whole_window, x11drv_atom(XdndAware),
                     XA_ATOM, 32, PropModeReplace, (unsigned char*)&dndVersion, 1 );

1125 1126 1127 1128 1129
    update_user_time( 0 );  /* make sure that the user time window exists */
    if (user_time_window)
        XChangeProperty( display, data->whole_window, x11drv_atom(_NET_WM_USER_TIME_WINDOW),
                         XA_WINDOW, 32, PropModeReplace, (unsigned char *)&user_time_window, 1 );

1130
    data->wm_hints = XAllocWMHints();
1131 1132 1133
    if (data->wm_hints)
    {
        data->wm_hints->flags = 0;
1134
        set_icon_hints( display, data, 0, 0 );
1135
    }
1136 1137 1138
}


1139 1140 1141 1142 1143
/***********************************************************************
 *              get_owner_whole_window
 *
 * Retrieve an owner's window, creating it if necessary.
 */
1144
static Window get_owner_whole_window( HWND owner, BOOL force_managed )
1145 1146 1147 1148 1149 1150 1151
{
    struct x11drv_win_data *data;

    if (!owner) return 0;

    if (!(data = X11DRV_get_win_data( owner )))
    {
1152 1153
        if (GetWindowThreadProcessId( owner, NULL ) != GetCurrentThreadId() ||
            !(data = X11DRV_create_win_data( owner )))
1154 1155
            return (Window)GetPropA( owner, whole_window_prop );
    }
1156
    else if (!data->managed && force_managed)  /* make it managed */
1157 1158 1159 1160 1161
    {
        SetWindowPos( owner, 0, 0, 0, 0, 0,
                      SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE |
                      SWP_NOREDRAW | SWP_DEFERERASE | SWP_NOSENDCHANGING | SWP_STATECHANGED );
    }
1162 1163 1164 1165
    return data->whole_window;
}


1166
/***********************************************************************
1167
 *              set_wm_hints
1168 1169
 *
 * Set the window manager hints for a newly-created window
1170
 */
1171
static void set_wm_hints( Display *display, struct x11drv_win_data *data )
1172
{
1173 1174
    Window group_leader = data->whole_window;
    Window owner_win = 0;
1175
    Atom window_type;
1176 1177
    DWORD style, ex_style;
    HWND owner;
1178

1179 1180 1181
    if (data->hwnd == GetDesktopWindow())
    {
        /* force some styles for the desktop to get the correct decorations */
1182 1183
        style = WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
        ex_style = WS_EX_APPWINDOW;
1184 1185
        owner = 0;
    }
1186 1187 1188 1189
    else
    {
        style = GetWindowLongW( data->hwnd, GWL_STYLE );
        ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
1190
        owner = GetWindow( data->hwnd, GW_OWNER );
1191
        if ((owner_win = get_owner_whole_window( owner, data->managed ))) group_leader = owner_win;
1192
    }
1193

1194 1195
    if (owner_win) XSetTransientForHint( display, data->whole_window, owner_win );

1196
    /* size hints */
1197
    set_size_hints( display, data, style );
1198
    set_mwm_hints( display, data, style, ex_style );
1199

1200 1201 1202 1203
    /* Only use dialog type for owned popups. Metacity allows making fullscreen
     * only normal windows, and doesn't handle correctly TRANSIENT_FOR hint for
     * dialogs owned by fullscreen windows.
     */
1204
    if (((style & WS_POPUP) || (ex_style & WS_EX_DLGMODALFRAME)) && owner) window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_DIALOG);
1205 1206
    else window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_NORMAL);

1207 1208
    XChangeProperty(display, data->whole_window, x11drv_atom(_NET_WM_WINDOW_TYPE),
		    XA_ATOM, 32, PropModeReplace, (unsigned char*)&window_type, 1);
1209

1210
    /* wm hints */
1211
    if (data->wm_hints)
1212
    {
1213
        data->wm_hints->flags |= InputHint | StateHint | WindowGroupHint;
1214
        data->wm_hints->input = !use_take_focus && !(style & WS_DISABLED);
1215 1216 1217
        data->wm_hints->initial_state = (style & WS_MINIMIZE) ? IconicState : NormalState;
        data->wm_hints->window_group = group_leader;
        XSetWMHints( display, data->whole_window, data->wm_hints );
1218
    }
1219 1220 1221
}


1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
/***********************************************************************
 *     init_clip_window
 */
Window init_clip_window(void)
{
    struct x11drv_thread_data *data = x11drv_init_thread_data();

    if (!data->clip_window &&
        (data->clip_window = (Window)GetPropA( GetDesktopWindow(), clip_window_prop )))
    {
        XSelectInput( data->display, data->clip_window, StructureNotifyMask );
    }
    return data->clip_window;
}


1238 1239 1240 1241 1242 1243 1244
/***********************************************************************
 *     update_user_time
 */
void update_user_time( Time time )
{
    if (!user_time_window)
    {
1245 1246 1247 1248
        Window win = XCreateWindow( gdi_display, root_window, -1, -1, 1, 1, 0, 0, InputOnly,
                                    DefaultVisual(gdi_display,DefaultScreen(gdi_display)), 0, NULL );
        if (InterlockedCompareExchangePointer( (void **)&user_time_window, (void *)win, 0 ))
            XDestroyWindow( gdi_display, win );
1249 1250
        TRACE( "user time window %lx\n", user_time_window );
    }
1251 1252 1253 1254

    if (!time) return;
    XLockDisplay( gdi_display );
    if (!last_user_time || (long)(time - last_user_time) > 0)
1255 1256 1257 1258 1259
    {
        last_user_time = time;
        XChangeProperty( gdi_display, user_time_window, x11drv_atom(_NET_WM_USER_TIME),
                         XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&time, 1 );
    }
1260
    XUnlockDisplay( gdi_display );
1261 1262
}

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
/***********************************************************************
 *     update_net_wm_states
 */
void update_net_wm_states( Display *display, struct x11drv_win_data *data )
{
    static const unsigned int state_atoms[NB_NET_WM_STATES] =
    {
        XATOM__NET_WM_STATE_FULLSCREEN,
        XATOM__NET_WM_STATE_ABOVE,
        XATOM__NET_WM_STATE_MAXIMIZED_VERT,
        XATOM__NET_WM_STATE_SKIP_PAGER,
        XATOM__NET_WM_STATE_SKIP_TASKBAR
    };

    DWORD i, style, ex_style, new_state = 0;

    if (!data->managed) return;
    if (data->whole_window == root_window) return;

    style = GetWindowLongW( data->hwnd, GWL_STYLE );
1283
    if (is_window_rect_fullscreen( &data->whole_rect ))
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    {
        if ((style & WS_MAXIMIZE) && (style & WS_CAPTION) == WS_CAPTION)
            new_state |= (1 << NET_WM_STATE_MAXIMIZED);
        else if (!(style & WS_MINIMIZE))
            new_state |= (1 << NET_WM_STATE_FULLSCREEN);
    }
    else if (style & WS_MAXIMIZE)
        new_state |= (1 << NET_WM_STATE_MAXIMIZED);

    ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
    if (ex_style & WS_EX_TOPMOST)
        new_state |= (1 << NET_WM_STATE_ABOVE);
1296
    if (ex_style & (WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE))
1297
        new_state |= (1 << NET_WM_STATE_SKIP_TASKBAR) | (1 << NET_WM_STATE_SKIP_PAGER);
1298
    if (!(ex_style & WS_EX_APPWINDOW) && GetWindow( data->hwnd, GW_OWNER ))
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
        new_state |= (1 << NET_WM_STATE_SKIP_TASKBAR);

    if (!data->mapped)  /* set the _NET_WM_STATE atom directly */
    {
        Atom atoms[NB_NET_WM_STATES+1];
        DWORD count;

        for (i = count = 0; i < NB_NET_WM_STATES; i++)
        {
            if (!(new_state & (1 << i))) continue;
            TRACE( "setting wm state %u for unmapped window %p/%lx\n",
                   i, data->hwnd, data->whole_window );
            atoms[count++] = X11DRV_Atoms[state_atoms[i] - FIRST_XATOM];
            if (state_atoms[i] == XATOM__NET_WM_STATE_MAXIMIZED_VERT)
                atoms[count++] = x11drv_atom(_NET_WM_STATE_MAXIMIZED_HORZ);
        }
        XChangeProperty( display, data->whole_window, x11drv_atom(_NET_WM_STATE), XA_ATOM,
                         32, PropModeReplace, (unsigned char *)atoms, count );
    }
    else  /* ask the window manager to do it for us */
    {
        XEvent xev;

        xev.xclient.type = ClientMessage;
        xev.xclient.window = data->whole_window;
        xev.xclient.message_type = x11drv_atom(_NET_WM_STATE);
        xev.xclient.serial = 0;
        xev.xclient.display = display;
        xev.xclient.send_event = True;
        xev.xclient.format = 32;
        xev.xclient.data.l[3] = 1;

        for (i = 0; i < NB_NET_WM_STATES; i++)
        {
            if (!((data->net_wm_state ^ new_state) & (1 << i))) continue;  /* unchanged */

            TRACE( "setting wm state %u for window %p/%lx to %u prev %u\n",
                   i, data->hwnd, data->whole_window,
                   (new_state & (1 << i)) != 0, (data->net_wm_state & (1 << i)) != 0 );

            xev.xclient.data.l[0] = (new_state & (1 << i)) ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
            xev.xclient.data.l[1] = X11DRV_Atoms[state_atoms[i] - FIRST_XATOM];
            xev.xclient.data.l[2] = ((state_atoms[i] == XATOM__NET_WM_STATE_MAXIMIZED_VERT) ?
                                     x11drv_atom(_NET_WM_STATE_MAXIMIZED_HORZ) : 0);
            XSendEvent( display, root_window, False,
                        SubstructureRedirectMask | SubstructureNotifyMask, &xev );
        }
    }
    data->net_wm_state = new_state;
}


/***********************************************************************
 *     set_xembed_flags
 */
static void set_xembed_flags( Display *display, struct x11drv_win_data *data, unsigned long flags )
{
    unsigned long info[2];

1358 1359
    if (!data->whole_window) return;

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
    info[0] = 0; /* protocol version */
    info[1] = flags;
    XChangeProperty( display, data->whole_window, x11drv_atom(_XEMBED_INFO),
                     x11drv_atom(_XEMBED_INFO), 32, PropModeReplace, (unsigned char*)info, 2 );
}


/***********************************************************************
 *     map_window
 */
static void map_window( Display *display, struct x11drv_win_data *data, DWORD new_style )
{
    TRACE( "win %p/%lx\n", data->hwnd, data->whole_window );

1374 1375
    remove_startup_notification( display, data->whole_window );

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
    wait_for_withdrawn_state( display, data, TRUE );

    if (!data->embedded)
    {
        update_net_wm_states( display, data );
        sync_window_style( display, data );
        XMapWindow( display, data->whole_window );
    }
    else set_xembed_flags( display, data, XEMBED_MAPPED );

    data->mapped = TRUE;
    data->iconic = (new_style & WS_MINIMIZE) != 0;
}


/***********************************************************************
 *     unmap_window
 */
static void unmap_window( Display *display, struct x11drv_win_data *data )
{
    TRACE( "win %p/%lx\n", data->hwnd, data->whole_window );

    if (!data->embedded)
    {
        wait_for_withdrawn_state( display, data, FALSE );
        if (data->managed) XWithdrawWindow( display, data->whole_window, DefaultScreen(display) );
        else XUnmapWindow( display, data->whole_window );
    }
    else set_xembed_flags( display, data, 0 );

    data->mapped = FALSE;
    data->net_wm_state = 0;
}


/***********************************************************************
 *     make_window_embedded
 */
void make_window_embedded( Display *display, struct x11drv_win_data *data )
{
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    BOOL was_mapped = data->mapped;
    /* the window cannot be mapped before being embedded */
    if (data->mapped) unmap_window( display, data );

    data->embedded = TRUE;
    data->managed = TRUE;
    SetPropA( data->hwnd, managed_prop, (HANDLE)1 );
    sync_window_style( display, data );

    if (was_mapped)
1426 1427 1428 1429 1430 1431
        map_window( display, data, 0 );
    else
        set_xembed_flags( display, data, 0 );
}


1432 1433 1434 1435 1436
/***********************************************************************
 *		X11DRV_window_to_X_rect
 *
 * Convert a rect from client to X window coordinates
 */
1437
static void X11DRV_window_to_X_rect( struct x11drv_win_data *data, RECT *rect )
1438
{
1439 1440
    RECT rc;

1441
    if (!data->managed) return;
1442 1443
    if (IsRectEmpty( rect )) return;

1444
    get_x11_rect_offset( data, &rc );
1445

1446 1447 1448 1449
    rect->left   -= rc.left;
    rect->right  -= rc.right;
    rect->top    -= rc.top;
    rect->bottom -= rc.bottom;
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
    if (rect->top >= rect->bottom) rect->bottom = rect->top + 1;
    if (rect->left >= rect->right) rect->right = rect->left + 1;
}


/***********************************************************************
 *		X11DRV_X_to_window_rect
 *
 * Opposite of X11DRV_window_to_X_rect
 */
1460
void X11DRV_X_to_window_rect( struct x11drv_win_data *data, RECT *rect )
1461
{
1462
    RECT rc;
1463

1464
    if (!data->managed) return;
1465 1466
    if (IsRectEmpty( rect )) return;

1467
    get_x11_rect_offset( data, &rc );
1468

1469 1470 1471 1472
    rect->left   += rc.left;
    rect->right  += rc.right;
    rect->top    += rc.top;
    rect->bottom += rc.bottom;
1473 1474 1475 1476 1477 1478
    if (rect->top >= rect->bottom) rect->bottom = rect->top + 1;
    if (rect->left >= rect->right) rect->right = rect->left + 1;
}


/***********************************************************************
1479
 *		sync_window_position
1480
 *
1481
 * Synchronize the X window position with the Windows one
1482
 */
1483
static void sync_window_position( Display *display, struct x11drv_win_data *data,
1484 1485
                                  UINT swp_flags, const RECT *old_window_rect,
                                  const RECT *old_whole_rect, const RECT *old_client_rect )
1486
{
1487
    DWORD style = GetWindowLongW( data->hwnd, GWL_STYLE );
1488
    DWORD ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
1489
    XWindowChanges changes;
1490
    unsigned int mask = 0;
1491 1492 1493

    if (data->managed && data->iconic) return;

1494 1495 1496
    /* resizing a managed maximized window is not allowed */
    if (!(style & WS_MAXIMIZE) || !data->managed)
    {
1497 1498 1499 1500
        changes.width = data->whole_rect.right - data->whole_rect.left;
        changes.height = data->whole_rect.bottom - data->whole_rect.top;
        /* if window rect is empty force size to 1x1 */
        if (changes.width <= 0 || changes.height <= 0) changes.width = changes.height = 1;
1501 1502
        if (changes.width > 65535) changes.width = 65535;
        if (changes.height > 65535) changes.height = 65535;
1503 1504
        mask |= CWWidth | CWHeight;
    }
1505 1506 1507 1508 1509 1510 1511 1512

    /* only the size is allowed to change for the desktop window */
    if (data->whole_window != root_window)
    {
        changes.x = data->whole_rect.left - virtual_screen_rect.left;
        changes.y = data->whole_rect.top - virtual_screen_rect.top;
        mask |= CWX | CWY;
    }
1513

1514
    if (!(swp_flags & SWP_NOZORDER) || (swp_flags & SWP_SHOWWINDOW))
1515
    {
1516 1517 1518 1519 1520
        /* find window that this one must be after */
        HWND prev = GetWindow( data->hwnd, GW_HWNDPREV );
        while (prev && !(GetWindowLongW( prev, GWL_STYLE ) & WS_VISIBLE))
            prev = GetWindow( prev, GW_HWNDPREV );
        if (!prev)  /* top child */
1521
        {
1522 1523
            changes.stack_mode = Above;
            mask |= CWStackMode;
1524
        }
1525 1526
        /* should use stack_mode Below but most window managers don't get it right */
        /* and Above with a sibling doesn't work so well either, so we ignore it */
1527 1528
    }

1529
    set_size_hints( display, data, style );
1530
    set_mwm_hints( display, data, style, ex_style );
1531
    data->configure_serial = NextRequest( display );
1532 1533
    XReconfigureWMWindow( display, data->whole_window,
                          DefaultScreen(display), mask, &changes );
1534
#ifdef HAVE_LIBXSHAPE
1535 1536
    if (IsRectEmpty( old_window_rect ) != IsRectEmpty( &data->window_rect ))
        sync_window_region( display, data, (HRGN)1 );
1537 1538
    if (data->shaped)
    {
1539 1540 1541 1542 1543 1544 1545
        int old_x_offset = old_window_rect->left - old_whole_rect->left;
        int old_y_offset = old_window_rect->top - old_whole_rect->top;
        int new_x_offset = data->window_rect.left - data->whole_rect.left;
        int new_y_offset = data->window_rect.top - data->whole_rect.top;
        if (old_x_offset != new_x_offset || old_y_offset != new_y_offset)
            XShapeOffsetShape( display, data->whole_window, ShapeBounding,
                               new_x_offset - old_x_offset, new_y_offset - old_y_offset );
1546 1547
    }
#endif
1548 1549 1550 1551 1552 1553

    TRACE( "win %p/%lx pos %d,%d,%dx%d after %lx changes=%x serial=%lu\n",
           data->hwnd, data->whole_window, data->whole_rect.left, data->whole_rect.top,
           data->whole_rect.right - data->whole_rect.left,
           data->whole_rect.bottom - data->whole_rect.top,
           changes.sibling, mask, data->configure_serial );
1554
}
1555

1556

1557
/***********************************************************************
1558
 *		sync_client_position
1559 1560 1561
 *
 * Synchronize the X client window position with the Windows one
 */
1562
static void sync_client_position( Display *display, struct x11drv_win_data *data,
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
                                  UINT swp_flags, const RECT *old_client_rect,
                                  const RECT *old_whole_rect )
{
    int mask;
    XWindowChanges changes;
    RECT old = *old_client_rect;
    RECT new = data->client_rect;

    OffsetRect( &old, -old_whole_rect->left, -old_whole_rect->top );
    OffsetRect( &new, -data->whole_rect.left, -data->whole_rect.top );
    if (!(mask = get_window_changes( &changes, &old, &new ))) return;

    if (data->client_window)
    {
        TRACE( "setting client win %lx pos %d,%d,%dx%d changes=%x\n",
               data->client_window, new.left, new.top,
               new.right - new.left, new.bottom - new.top, mask );
        XConfigureWindow( display, data->client_window, mask, &changes );
    }

1583
    if (data->gl_drawable && (mask & (CWWidth|CWHeight))) sync_gl_drawable( data );
1584 1585 1586
}


1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
/***********************************************************************
 *		move_window_bits
 *
 * Move the window bits when a window is moved.
 */
static void move_window_bits( struct x11drv_win_data *data, const RECT *old_rect, const RECT *new_rect,
                              const RECT *old_client_rect )
{
    RECT src_rect = *old_rect;
    RECT dst_rect = *new_rect;
    HDC hdc_src, hdc_dst;
    INT code;
1599
    HRGN rgn;
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
    HWND parent = 0;

    if (!data->whole_window)
    {
        OffsetRect( &dst_rect, -data->window_rect.left, -data->window_rect.top );
        parent = GetAncestor( data->hwnd, GA_PARENT );
        hdc_src = GetDCEx( parent, 0, DCX_CACHE );
        hdc_dst = GetDCEx( data->hwnd, 0, DCX_CACHE | DCX_WINDOW );
    }
    else
    {
        OffsetRect( &dst_rect, -data->client_rect.left, -data->client_rect.top );
        /* make src rect relative to the old position of the window */
        OffsetRect( &src_rect, -old_client_rect->left, -old_client_rect->top );
        if (dst_rect.left == src_rect.left && dst_rect.top == src_rect.top) return;
        hdc_src = hdc_dst = GetDCEx( data->hwnd, 0, DCX_CACHE );
    }

1618 1619 1620
    rgn = CreateRectRgnIndirect( &dst_rect );
    SelectClipRgn( hdc_dst, rgn );
    DeleteObject( rgn );
1621 1622
    ExcludeUpdateRgn( hdc_dst, data->hwnd );

1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
    code = X11DRV_START_EXPOSURES;
    ExtEscape( hdc_dst, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );

    TRACE( "copying bits for win %p/%lx/%lx %s -> %s\n",
           data->hwnd, data->whole_window, data->client_window,
           wine_dbgstr_rect(&src_rect), wine_dbgstr_rect(&dst_rect) );
    BitBlt( hdc_dst, dst_rect.left, dst_rect.top,
            dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top,
            hdc_src, src_rect.left, src_rect.top, SRCCOPY );

1633
    rgn = 0;
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
    code = X11DRV_END_EXPOSURES;
    ExtEscape( hdc_dst, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, sizeof(rgn), (LPSTR)&rgn );

    ReleaseDC( data->hwnd, hdc_dst );
    if (hdc_src != hdc_dst) ReleaseDC( parent, hdc_src );

    if (rgn)
    {
        if (!data->whole_window)
        {
            /* map region to client rect since we are using DCX_WINDOW */
            OffsetRgn( rgn, data->window_rect.left - data->client_rect.left,
                       data->window_rect.top - data->client_rect.top );
            RedrawWindow( data->hwnd, NULL, rgn,
                          RDW_INVALIDATE | RDW_FRAME | RDW_ERASE | RDW_ALLCHILDREN );
        }
        else RedrawWindow( data->hwnd, NULL, rgn, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN );
        DeleteObject( rgn );
    }
}


1656 1657 1658 1659 1660
/**********************************************************************
 *		create_whole_window
 *
 * Create the whole X window for a given window
 */
1661
static Window create_whole_window( Display *display, struct x11drv_win_data *data )
1662 1663 1664
{
    int cx, cy, mask;
    XSetWindowAttributes attr;
1665
    WCHAR text[1024];
1666 1667 1668
    COLORREF key;
    BYTE alpha;
    DWORD layered_flags;
1669
    HRGN win_rgn;
1670

1671 1672 1673 1674 1675 1676 1677
    if (!data->managed && is_window_managed( data->hwnd, SWP_NOACTIVATE, &data->window_rect ))
    {
        TRACE( "making win %p/%lx managed\n", data->hwnd, data->whole_window );
        data->managed = TRUE;
        SetPropA( data->hwnd, managed_prop, (HANDLE)1 );
    }

1678 1679 1680 1681 1682 1683 1684 1685
    if ((win_rgn = CreateRectRgn( 0, 0, 0, 0 )) &&
        GetWindowRgn( data->hwnd, win_rgn ) == ERROR)
    {
        DeleteObject( win_rgn );
        win_rgn = 0;
    }
    data->shaped = (win_rgn != 0);

1686
    mask = get_window_attributes( display, data, &attr );
1687

1688
    data->whole_rect = data->window_rect;
1689 1690 1691 1692 1693 1694
    X11DRV_window_to_X_rect( data, &data->whole_rect );
    if (!(cx = data->whole_rect.right - data->whole_rect.left)) cx = 1;
    else if (cx > 65535) cx = 65535;
    if (!(cy = data->whole_rect.bottom - data->whole_rect.top)) cy = 1;
    else if (cy > 65535) cy = 65535;

1695
    data->whole_window = XCreateWindow( display, root_window,
1696 1697
                                        data->whole_rect.left - virtual_screen_rect.left,
                                        data->whole_rect.top - virtual_screen_rect.top,
1698 1699
                                        cx, cy, 0, screen_depth, InputOutput,
                                        visual, mask, &attr );
1700
    if (!data->whole_window) goto done;
1701

1702
    if (!create_client_window( display, data, NULL ))
1703 1704 1705
    {
        XDestroyWindow( display, data->whole_window );
        data->whole_window = 0;
1706
        goto done;
1707 1708
    }

1709
    set_initial_wm_hints( display, data );
1710
    set_wm_hints( display, data );
1711

1712
    XSaveContext( display, data->whole_window, winContext, (char *)data->hwnd );
1713
    SetPropA( data->hwnd, whole_window_prop, (HANDLE)data->whole_window );
1714

1715 1716 1717 1718
    /* set the window text */
    if (!InternalGetWindowText( data->hwnd, text, sizeof(text)/sizeof(WCHAR) )) text[0] = 0;
    sync_window_text( display, data->whole_window, text );

1719
    /* set the window region */
1720
    if (win_rgn || IsRectEmpty( &data->window_rect )) sync_window_region( display, data, win_rgn );
1721

1722 1723 1724 1725
    /* set the window opacity */
    if (!GetLayeredWindowAttributes( data->hwnd, &key, &alpha, &layered_flags )) layered_flags = 0;
    sync_window_opacity( display, data->whole_window, key, alpha, layered_flags );

1726 1727
    init_clip_window();  /* make sure the clip window is initialized in this thread */

1728
    XFlush( display );  /* make sure the window exists before we start painting to it */
1729

1730
    sync_window_cursor( data->whole_window );
1731

1732 1733
done:
    if (win_rgn) DeleteObject( win_rgn );
1734 1735 1736 1737 1738
    return data->whole_window;
}


/**********************************************************************
1739
 *		destroy_whole_window
1740
 *
1741
 * Destroy the whole X window for a given window.
1742
 */
1743
static void destroy_whole_window( Display *display, struct x11drv_win_data *data, BOOL already_destroyed )
1744
{
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    if (!data->whole_window)
    {
        if (data->embedded)
        {
            Window xwin = (Window)GetPropA( data->hwnd, foreign_window_prop );
            if (xwin)
            {
                if (!already_destroyed) XSelectInput( display, xwin, 0 );
                XDeleteContext( display, xwin, winContext );
                RemovePropA( data->hwnd, foreign_window_prop );
            }
        }
        return;
    }

1760

1761
    TRACE( "win %p xwin %lx/%lx\n", data->hwnd, data->whole_window, data->client_window );
1762
    XDeleteContext( display, data->whole_window, winContext );
1763
    XDeleteContext( display, data->client_window, winContext );
1764
    if (!already_destroyed) XDestroyWindow( display, data->whole_window );
1765
    data->whole_window = data->client_window = 0;
1766 1767 1768
    data->wm_state = WithdrawnState;
    data->net_wm_state = 0;
    data->mapped = FALSE;
1769 1770 1771 1772
    if (data->xic)
    {
        XUnsetICFocus( data->xic );
        XDestroyIC( data->xic );
1773
        data->xic = 0;
1774
    }
1775 1776
    /* Outlook stops processing messages after destroying a dialog, so we need an explicit flush */
    XFlush( display );
1777 1778
    XFree( data->wm_hints );
    data->wm_hints = NULL;
1779
    RemovePropA( data->hwnd, whole_window_prop );
1780
    RemovePropA( data->hwnd, client_window_prop );
1781 1782 1783 1784 1785 1786
}


/*****************************************************************
 *		SetWindowText   (X11DRV.@)
 */
1787
void CDECL X11DRV_SetWindowText( HWND hwnd, LPCWSTR text )
1788 1789
{
    Window win;
1790

1791 1792 1793
    if ((win = X11DRV_get_whole_window( hwnd )) && win != DefaultRootWindow(gdi_display))
    {
        Display *display = thread_init_display();
1794
        sync_window_text( display, win, text );
1795
    }
1796 1797 1798
}


1799 1800 1801 1802 1803
/***********************************************************************
 *		SetWindowStyle   (X11DRV.@)
 *
 * Update the X state of a window to reflect a style change
 */
1804
void CDECL X11DRV_SetWindowStyle( HWND hwnd, INT offset, STYLESTRUCT *style )
1805
{
1806
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
1807
    DWORD changed;
1808 1809

    if (hwnd == GetDesktopWindow()) return;
1810
    changed = style->styleNew ^ style->styleOld;
1811

1812 1813
    /* if WS_VISIBLE was set through WM_SETREDRAW, map the window if it's the first time */
    if (offset == GWL_STYLE && (changed & WS_VISIBLE) && (style->styleNew & WS_VISIBLE) && !data)
1814
    {
1815
        if (!(data = X11DRV_create_win_data( hwnd ))) return;
1816 1817 1818

        if (data->whole_window && is_window_rect_mapped( &data->window_rect ))
        {
1819
            Display *display = thread_display();
1820
            set_wm_hints( display, data );
1821
            if (!data->mapped) map_window( display, data, style->styleNew );
1822 1823
        }
    }
1824
    if (!data || !data->whole_window) return;
1825

1826
    if (offset == GWL_STYLE && (changed & WS_DISABLED))
1827
        set_wm_hints( thread_display(), data );
1828

1829 1830
    if (offset == GWL_EXSTYLE && (changed & WS_EX_LAYERED)) /* changing WS_EX_LAYERED resets attributes */
        sync_window_opacity( thread_display(), data->whole_window, 0, 0, 0 );
1831 1832 1833
}


1834 1835 1836
/***********************************************************************
 *		DestroyWindow   (X11DRV.@)
 */
1837
void CDECL X11DRV_DestroyWindow( HWND hwnd )
1838
{
1839
    struct x11drv_thread_data *thread_data = x11drv_thread_data();
1840
    struct x11drv_win_data *data;
1841

1842
    if (!(data = X11DRV_get_win_data( hwnd ))) return;
1843

1844 1845
    if (data->pixmap)
    {
1846 1847
        destroy_glxpixmap(gdi_display, data->gl_drawable);
        XFreePixmap(gdi_display, data->pixmap);
1848 1849
    }
    else if (data->gl_drawable)
1850
    {
1851
        XDestroyWindow(gdi_display, data->gl_drawable);
1852 1853
    }

1854 1855
    destroy_whole_window( thread_data->display, data, FALSE );
    destroy_icon_window( thread_data->display, data );
1856

1857
    if (data->colormap) XFreeColormap( thread_data->display, data->colormap );
1858

1859
    if (thread_data->last_focus == hwnd) thread_data->last_focus = 0;
1860
    if (thread_data->last_xic_hwnd == hwnd) thread_data->last_xic_hwnd = 0;
1861 1862
    if (data->icon_pixmap) XFreePixmap( gdi_display, data->icon_pixmap );
    if (data->icon_mask) XFreePixmap( gdi_display, data->icon_mask );
1863
    XDeleteContext( thread_data->display, (XID)hwnd, win_data_context );
1864 1865 1866 1867
    HeapFree( GetProcessHeap(), 0, data );
}


1868 1869 1870 1871 1872 1873 1874 1875 1876
/***********************************************************************
 *		X11DRV_DestroyNotify
 */
void X11DRV_DestroyNotify( HWND hwnd, XEvent *event )
{
    Display *display = event->xdestroywindow.display;
    struct x11drv_win_data *data;

    if (!(data = X11DRV_get_win_data( hwnd ))) return;
1877
    if (!data->embedded) FIXME( "window %p/%lx destroyed from the outside\n", hwnd, data->whole_window );
1878

1879
    destroy_whole_window( display, data, TRUE );
1880
    if (data->embedded) SendMessageW( hwnd, WM_CLOSE, 0, 0 );
1881 1882 1883
}


1884 1885 1886 1887
static struct x11drv_win_data *alloc_win_data( Display *display, HWND hwnd )
{
    struct x11drv_win_data *data;

1888
    if ((data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data))))
1889
    {
1890
        data->hwnd = hwnd;
1891 1892 1893 1894 1895 1896
        XSaveContext( display, (XID)hwnd, win_data_context, (char *)data );
    }
    return data;
}


1897
/* initialize the desktop window id in the desktop manager process */
1898
static struct x11drv_win_data *create_desktop_win_data( Display *display, HWND hwnd )
1899
{
1900
    struct x11drv_win_data *data;
1901

1902
    if (!(data = alloc_win_data( display, hwnd ))) return NULL;
1903
    data->whole_window = data->client_window = root_window;
1904 1905 1906
    data->managed = TRUE;
    SetPropA( data->hwnd, managed_prop, (HANDLE)1 );
    SetPropA( data->hwnd, whole_window_prop, (HANDLE)root_window );
1907
    SetPropA( data->hwnd, client_window_prop, (HANDLE)root_window );
1908 1909
    set_initial_wm_hints( display, data );
    return data;
1910 1911
}

1912 1913 1914
/**********************************************************************
 *		CreateDesktopWindow   (X11DRV.@)
 */
1915
BOOL CDECL X11DRV_CreateDesktopWindow( HWND hwnd )
1916
{
1917
    unsigned int width, height;
1918

1919 1920 1921
    /* retrieve the real size of the desktop */
    SERVER_START_REQ( get_window_rectangles )
    {
1922
        req->handle = wine_server_user_handle( hwnd );
1923
        req->relative = COORDS_CLIENT;
1924
        wine_server_call( req );
1925 1926
        width  = reply->window.right;
        height = reply->window.bottom;
1927 1928
    }
    SERVER_END_REQ;
1929

1930 1931 1932 1933
    if (!width && !height)  /* not initialized yet */
    {
        SERVER_START_REQ( set_window_pos )
        {
1934
            req->handle        = wine_server_user_handle( hwnd );
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
            req->previous      = 0;
            req->flags         = SWP_NOZORDER;
            req->window.left   = virtual_screen_rect.left;
            req->window.top    = virtual_screen_rect.top;
            req->window.right  = virtual_screen_rect.right;
            req->window.bottom = virtual_screen_rect.bottom;
            req->client        = req->window;
            wine_server_call( req );
        }
        SERVER_END_REQ;
    }
    else
    {
        Window win = (Window)GetPropA( hwnd, whole_window_prop );
        if (win && win != root_window) X11DRV_init_desktop( win, width, height );
    }
1951 1952 1953 1954
    return TRUE;
}


1955 1956 1957
/**********************************************************************
 *		CreateWindow   (X11DRV.@)
 */
1958
BOOL CDECL X11DRV_CreateWindow( HWND hwnd )
1959
{
1960
    if (hwnd == GetDesktopWindow())
1961
    {
1962
        struct x11drv_thread_data *data = x11drv_init_thread_data();
1963 1964 1965 1966 1967
        XSetWindowAttributes attr;

        if (root_window != DefaultRootWindow( gdi_display ))
        {
            /* the desktop win data can't be created lazily */
1968
            if (!create_desktop_win_data( data->display, hwnd )) return FALSE;
1969
        }
1970

1971 1972
        /* create the cursor clipping window */
        attr.override_redirect = TRUE;
1973
        attr.event_mask = StructureNotifyMask | FocusChangeMask;
1974 1975
        data->clip_window = XCreateWindow( data->display, root_window, 0, 0, 1, 1, 0, 0,
                                           InputOnly, visual, CWOverrideRedirect | CWEventMask, &attr );
1976
        XFlush( data->display );
1977
        SetPropA( hwnd, clip_window_prop, (HANDLE)data->clip_window );
1978
    }
1979 1980 1981 1982 1983
    return TRUE;
}


/***********************************************************************
1984
 *		X11DRV_get_win_data
1985
 *
1986
 * Return the X11 data structure associated with a window.
1987
 */
1988
struct x11drv_win_data *X11DRV_get_win_data( HWND hwnd )
1989
{
1990
    struct x11drv_thread_data *thread_data = x11drv_thread_data();
1991
    char *data;
1992

1993 1994 1995
    if (!thread_data) return NULL;
    if (!hwnd) return NULL;
    if (XFindContext( thread_data->display, (XID)hwnd, win_data_context, &data )) data = NULL;
1996
    return (struct x11drv_win_data *)data;
1997 1998 1999
}


2000 2001 2002 2003 2004 2005 2006
/***********************************************************************
 *		X11DRV_create_win_data
 *
 * Create an X11 data window structure for an existing window.
 */
struct x11drv_win_data *X11DRV_create_win_data( HWND hwnd )
{
2007
    Display *display;
2008 2009 2010 2011
    struct x11drv_win_data *data;
    HWND parent;

    if (!(parent = GetAncestor( hwnd, GA_PARENT ))) return NULL;  /* desktop */
2012

2013 2014 2015
    /* don't create win data for HWND_MESSAGE windows */
    if (parent != GetDesktopWindow() && !GetAncestor( parent, GA_PARENT )) return NULL;

2016
    display = thread_init_display();
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
    if (!(data = alloc_win_data( display, hwnd ))) return NULL;

    GetWindowRect( hwnd, &data->window_rect );
    MapWindowPoints( 0, parent, (POINT *)&data->window_rect, 2 );
    data->whole_rect = data->window_rect;
    GetClientRect( hwnd, &data->client_rect );
    MapWindowPoints( hwnd, parent, (POINT *)&data->client_rect, 2 );

    if (parent == GetDesktopWindow())
    {
        if (!create_whole_window( display, data ))
        {
            HeapFree( GetProcessHeap(), 0, data );
            return NULL;
        }
2032 2033
        TRACE( "win %p/%lx/%lx window %s whole %s client %s\n",
               hwnd, data->whole_window, data->client_window, wine_dbgstr_rect( &data->window_rect ),
2034 2035 2036 2037 2038 2039
               wine_dbgstr_rect( &data->whole_rect ), wine_dbgstr_rect( &data->client_rect ));
    }
    return data;
}


2040 2041 2042 2043 2044
/* window procedure for foreign windows */
static LRESULT WINAPI foreign_window_proc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
    switch(msg)
    {
2045 2046 2047
    case WM_WINDOWPOSCHANGED:
        update_systray_balloon_position();
        break;
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
    case WM_PARENTNOTIFY:
        if (LOWORD(wparam) == WM_DESTROY)
        {
            TRACE( "%p: got parent notify destroy for win %lx\n", hwnd, lparam );
            PostMessageW( hwnd, WM_CLOSE, 0, 0 );  /* so that we come back here once the child is gone */
        }
        return 0;
    case WM_CLOSE:
        if (GetWindow( hwnd, GW_CHILD )) return 0;  /* refuse to die if we still have children */
        break;
    }
    return DefWindowProcW( hwnd, msg, wparam, lparam );
}


/***********************************************************************
 *		create_foreign_window
 *
 * Create a foreign window for the specified X window and its ancestors
 */
HWND create_foreign_window( Display *display, Window xwin )
{
    static const WCHAR classW[] = {'_','_','w','i','n','e','_','x','1','1','_','f','o','r','e','i','g','n','_','w','i','n','d','o','w',0};
    static BOOL class_registered;
    struct x11drv_win_data *data;
    HWND hwnd, parent;
    Window xparent, xroot;
    Window *xchildren;
    unsigned int nchildren;
    XWindowAttributes attr;
    DWORD style = WS_CLIPCHILDREN;

    if (!class_registered)
    {
        WNDCLASSEXW class;

        memset( &class, 0, sizeof(class) );
        class.cbSize        = sizeof(class);
        class.lpfnWndProc   = foreign_window_proc;
        class.lpszClassName = classW;
        if (!RegisterClassExW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS)
        {
            ERR( "Could not register foreign window class\n" );
            return FALSE;
        }
        class_registered = TRUE;
    }

    if (XFindContext( display, xwin, winContext, (char **)&hwnd )) hwnd = 0;
2097
    if (hwnd) return hwnd;  /* already created */
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134

    XSelectInput( display, xwin, StructureNotifyMask );
    if (!XGetWindowAttributes( display, xwin, &attr ) ||
        !XQueryTree( display, xwin, &xroot, &xparent, &xchildren, &nchildren ))
    {
        XSelectInput( display, xwin, 0 );
        return 0;
    }
    XFree( xchildren );

    if (xparent == xroot)
    {
        parent = GetDesktopWindow();
        style |= WS_POPUP;
        attr.x += virtual_screen_rect.left;
        attr.y += virtual_screen_rect.top;
    }
    else
    {
        parent = create_foreign_window( display, xparent );
        style |= WS_CHILD;
    }

    hwnd = CreateWindowW( classW, NULL, style, attr.x, attr.y, attr.width, attr.height,
                          parent, 0, 0, NULL );

    if (!(data = alloc_win_data( display, hwnd )))
    {
        DestroyWindow( hwnd );
        return 0;
    }
    SetRect( &data->window_rect, attr.x, attr.y, attr.x + attr.width, attr.y + attr.height );
    data->whole_rect = data->client_rect = data->window_rect;
    data->whole_window = data->client_window = 0;
    data->embedded = TRUE;
    data->mapped = TRUE;

2135
    SetPropA( hwnd, foreign_window_prop, (HANDLE)xwin );
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
    XSaveContext( display, xwin, winContext, (char *)data->hwnd );

    ShowWindow( hwnd, SW_SHOW );

    TRACE( "win %lx parent %p style %08x %s -> hwnd %p\n",
           xwin, parent, style, wine_dbgstr_rect(&data->window_rect), hwnd );

    return hwnd;
}


2147 2148 2149 2150 2151 2152 2153
/***********************************************************************
 *		X11DRV_get_whole_window
 *
 * Return the X window associated with the full area of a window
 */
Window X11DRV_get_whole_window( HWND hwnd )
{
2154
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2155

2156 2157 2158 2159 2160
    if (!data)
    {
        if (hwnd == GetDesktopWindow()) return root_window;
        return (Window)GetPropA( hwnd, whole_window_prop );
    }
2161
    return data->whole_window;
2162 2163 2164
}


2165 2166 2167 2168 2169
/***********************************************************************
 *		X11DRV_get_client_window
 *
 * Return the X window associated with the client area of a window
 */
2170
static Window X11DRV_get_client_window( HWND hwnd )
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
{
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );

    if (!data)
    {
        if (hwnd == GetDesktopWindow()) return root_window;
        return (Window)GetPropA( hwnd, client_window_prop );
    }
    return data->client_window;
}


2183
/***********************************************************************
2184
 *		X11DRV_get_ic
2185
 *
2186
 * Return the X input context associated with a window
2187
 */
2188
XIC X11DRV_get_ic( HWND hwnd )
2189 2190
{
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2191
    XIM xim;
2192

2193
    if (!data) return 0;
2194 2195

    x11drv_thread_data()->last_xic_hwnd = hwnd;
2196 2197 2198
    if (data->xic) return data->xic;
    if (!(xim = x11drv_thread_data()->xim)) return 0;
    return X11DRV_CreateIC( xim, data );
2199 2200
}

2201

2202
/***********************************************************************
2203
 *		X11DRV_GetDC   (X11DRV.@)
2204
 */
2205 2206
void CDECL X11DRV_GetDC( HDC hdc, HWND hwnd, HWND top, const RECT *win_rect,
                         const RECT *top_rect, DWORD flags )
2207
{
2208
    struct x11drv_escape_set_drawable escape;
2209
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2210
    HWND parent;
2211

2212 2213 2214 2215 2216
    escape.code        = X11DRV_SET_DRAWABLE;
    escape.mode        = IncludeInferiors;
    escape.fbconfig_id = 0;
    escape.gl_drawable = 0;
    escape.pixmap      = 0;
2217
    escape.gl_type     = DC_GL_NONE;
2218

2219 2220 2221 2222 2223
    escape.dc_rect.left         = win_rect->left - top_rect->left;
    escape.dc_rect.top          = win_rect->top - top_rect->top;
    escape.dc_rect.right        = win_rect->right - top_rect->left;
    escape.dc_rect.bottom       = win_rect->bottom - top_rect->top;

2224
    if (top == hwnd)
2225
    {
2226 2227 2228
        escape.fbconfig_id = data ? data->fbconfig_id : (XID)GetPropA( hwnd, fbconfig_id_prop );
        /* GL draws to the client area even for window DCs */
        escape.gl_drawable = data ? data->client_window : X11DRV_get_client_window( hwnd );
2229 2230 2231 2232 2233
        if (data && IsIconic( hwnd ) && data->icon_window)
        {
            escape.drawable = data->icon_window;
        }
        else if (flags & DCX_WINDOW)
2234 2235 2236
            escape.drawable = data ? data->whole_window : X11DRV_get_whole_window( hwnd );
        else
            escape.drawable = escape.gl_drawable;
2237

2238
        if (escape.gl_drawable) escape.gl_type = DC_GL_WINDOW;
2239 2240
        /* special case: when repainting the root window, clip out top-level windows */
        if (data && data->whole_window == root_window) escape.mode = ClipByChildren;
2241 2242 2243
    }
    else
    {
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
        /* find the first ancestor that has a drawable */
        for (parent = hwnd; parent && parent != top; parent = GetAncestor( parent, GA_PARENT ))
            if ((escape.drawable = X11DRV_get_client_window( parent ))) break;

        if (escape.drawable)
        {
            POINT pt = { 0, 0 };
            MapWindowPoints( top, parent, &pt, 1 );
            OffsetRect( &escape.dc_rect, pt.x, pt.y );
        }
        else escape.drawable = X11DRV_get_client_window( top );

2256 2257 2258
        escape.fbconfig_id = data ? data->fbconfig_id : (XID)GetPropA( hwnd, fbconfig_id_prop );
        escape.gl_drawable = data ? data->gl_drawable : (Drawable)GetPropA( hwnd, gl_drawable_prop );
        escape.pixmap      = data ? data->pixmap : (Pixmap)GetPropA( hwnd, pixmap_prop );
2259
        if (escape.gl_drawable) escape.gl_type = escape.pixmap ? DC_GL_PIXMAP_WIN : DC_GL_CHILD_WIN;
2260
        if (flags & DCX_CLIPCHILDREN) escape.mode = ClipByChildren;
2261
    }
2262

2263
    ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
2264 2265
}

2266

2267
/***********************************************************************
2268
 *		X11DRV_ReleaseDC  (X11DRV.@)
2269
 */
2270
void CDECL X11DRV_ReleaseDC( HWND hwnd, HDC hdc )
2271
{
2272 2273 2274 2275 2276 2277 2278
    struct x11drv_escape_set_drawable escape;

    escape.code = X11DRV_SET_DRAWABLE;
    escape.drawable = root_window;
    escape.mode = IncludeInferiors;
    SetRect( &escape.dc_rect, 0, 0, virtual_screen_rect.right - virtual_screen_rect.left,
             virtual_screen_rect.bottom - virtual_screen_rect.top );
2279
    OffsetRect( &escape.dc_rect, -virtual_screen_rect.left, -virtual_screen_rect.top );
2280 2281 2282
    escape.fbconfig_id = 0;
    escape.gl_drawable = 0;
    escape.pixmap = 0;
2283
    escape.gl_type = DC_GL_NONE;
2284
    ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
2285 2286 2287
}


2288 2289 2290
/***********************************************************************
 *		SetCapture  (X11DRV.@)
 */
2291
void CDECL X11DRV_SetCapture( HWND hwnd, UINT flags )
2292 2293 2294
{
    struct x11drv_thread_data *thread_data = x11drv_thread_data();

2295
    if (!thread_data) return;
2296
    if (!(flags & (GUI_INMOVESIZE | GUI_INMENUMODE))) return;
2297 2298 2299 2300 2301 2302 2303 2304 2305

    if (hwnd)
    {
        Window grab_win = X11DRV_get_client_window( GetAncestor( hwnd, GA_ROOT ) );

        if (!grab_win) return;
        XFlush( gdi_display );
        XGrabPointer( thread_data->display, grab_win, False,
                      PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
2306
                      GrabModeAsync, GrabModeAsync, None, None, CurrentTime );
2307 2308 2309 2310 2311 2312
        thread_data->grab_window = grab_win;
    }
    else  /* release capture */
    {
        XFlush( gdi_display );
        XUngrabPointer( thread_data->display, CurrentTime );
2313
        XFlush( thread_data->display );
2314 2315 2316 2317 2318
        thread_data->grab_window = None;
    }
}


2319 2320 2321
/*****************************************************************
 *		SetParent   (X11DRV.@)
 */
2322
void CDECL X11DRV_SetParent( HWND hwnd, HWND parent, HWND old_parent )
2323
{
2324
    Display *display = thread_display();
2325
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2326

2327 2328
    if (!data) return;
    if (parent == old_parent) return;
2329
    if (data->embedded) return;
2330

2331
    if (parent != GetDesktopWindow()) /* a child window */
2332
    {
2333
        if (old_parent == GetDesktopWindow())
2334
        {
2335
            /* destroy the old X windows */
2336
            destroy_whole_window( display, data, FALSE );
2337 2338
            destroy_icon_window( display, data );
            if (data->managed)
2339
            {
2340 2341
                data->managed = FALSE;
                RemovePropA( data->hwnd, managed_prop );
2342 2343
            }
        }
2344
    }
2345 2346 2347
    else  /* new top level window */
    {
        /* FIXME: we ignore errors since we can't really recover anyway */
2348
        create_whole_window( display, data );
2349
    }
2350 2351 2352 2353 2354 2355 2356 2357
}


/*****************************************************************
 *		SetFocus   (X11DRV.@)
 *
 * Set the X focus.
 */
2358
void CDECL X11DRV_SetFocus( HWND hwnd )
2359
{
2360
    Display *display = thread_display();
2361
    struct x11drv_win_data *data;
2362
    XWindowChanges changes;
2363
    DWORD timestamp;
2364

2365
    if (!(hwnd = GetAncestor( hwnd, GA_ROOT ))) return;
2366
    if (!(data = X11DRV_get_win_data( hwnd ))) return;
2367
    if (data->managed || !data->whole_window) return;
2368

2369 2370 2371 2372 2373 2374 2375
    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;

2376
    /* Set X focus and install colormap */
2377 2378
    changes.stack_mode = Above;
    XConfigureWindow( display, data->whole_window, CWStackMode, &changes );
2379
    XSetInputFocus( display, data->whole_window, RevertToParent, timestamp );
2380 2381 2382
}


2383
/***********************************************************************
2384
 *		WindowPosChanging   (X11DRV.@)
2385
 */
2386 2387
void CDECL X11DRV_WindowPosChanging( HWND hwnd, HWND insert_after, UINT swp_flags,
                                     const RECT *window_rect, const RECT *client_rect, RECT *visible_rect )
2388 2389
{
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2390
    DWORD style = GetWindowLongW( hwnd, GWL_STYLE );
2391 2392 2393 2394

    if (!data)
    {
        /* create the win data if the window is being made visible */
2395
        if (!(style & WS_VISIBLE) && !(swp_flags & SWP_SHOWWINDOW)) return;
2396 2397 2398 2399
        if (!(data = X11DRV_create_win_data( hwnd ))) return;
    }

    /* check if we need to switch the window to managed */
2400
    if (!data->managed && data->whole_window && is_window_managed( hwnd, swp_flags, window_rect ))
2401 2402
    {
        TRACE( "making win %p/%lx managed\n", hwnd, data->whole_window );
2403
        if (data->mapped) unmap_window( thread_display(), data );
2404 2405 2406 2407
        data->managed = TRUE;
        SetPropA( hwnd, managed_prop, (HANDLE)1 );
    }

2408 2409 2410 2411 2412 2413 2414 2415
    *visible_rect = *window_rect;
    X11DRV_window_to_X_rect( data, visible_rect );
}


/***********************************************************************
 *		WindowPosChanged   (X11DRV.@)
 */
2416 2417 2418
void CDECL X11DRV_WindowPosChanged( HWND hwnd, HWND insert_after, UINT swp_flags,
                                    const RECT *rectWindow, const RECT *rectClient,
                                    const RECT *visible_rect, const RECT *valid_rects )
2419 2420 2421 2422 2423
{
    struct x11drv_thread_data *thread_data;
    Display *display;
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
    DWORD new_style = GetWindowLongW( hwnd, GWL_STYLE );
2424
    RECT old_window_rect, old_whole_rect, old_client_rect;
2425 2426 2427 2428 2429 2430 2431
    int event_type;

    if (!data) return;

    thread_data = x11drv_thread_data();
    display = thread_data->display;

2432
    old_window_rect = data->window_rect;
2433 2434 2435
    old_whole_rect  = data->whole_rect;
    old_client_rect = data->client_rect;
    data->window_rect = *rectWindow;
2436
    data->whole_rect  = *visible_rect;
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
    data->client_rect = *rectClient;

    TRACE( "win %p window %s client %s style %08x flags %08x\n",
           hwnd, wine_dbgstr_rect(rectWindow), wine_dbgstr_rect(rectClient), new_style, swp_flags );

    if (!IsRectEmpty( &valid_rects[0] ))
    {
        int x_offset = old_whole_rect.left - data->whole_rect.left;
        int y_offset = old_whole_rect.top - data->whole_rect.top;

        /* if all that happened is that the whole window moved, copy everything */
        if (!(swp_flags & SWP_FRAMECHANGED) &&
            old_whole_rect.right   - data->whole_rect.right   == x_offset &&
            old_whole_rect.bottom  - data->whole_rect.bottom  == y_offset &&
            old_client_rect.left   - data->client_rect.left   == x_offset &&
            old_client_rect.right  - data->client_rect.right  == x_offset &&
            old_client_rect.top    - data->client_rect.top    == y_offset &&
            old_client_rect.bottom - data->client_rect.bottom == y_offset &&
            !memcmp( &valid_rects[0], &data->client_rect, sizeof(RECT) ))
        {
            /* if we have an X window the bits will be moved by the X server */
2458
            if (!data->whole_window && (x_offset != 0 || y_offset != 0))
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
                move_window_bits( data, &old_whole_rect, &data->whole_rect, &old_client_rect );
        }
        else
            move_window_bits( data, &valid_rects[1], &valid_rects[0], &old_client_rect );
    }

    XFlush( gdi_display );  /* make sure painting is done before we move the window */

    sync_client_position( display, data, swp_flags, &old_client_rect, &old_whole_rect );

    if (!data->whole_window) return;

    /* check if we are currently processing an event relevant to this window */
    event_type = 0;
    if (thread_data->current_event && thread_data->current_event->xany.window == data->whole_window)
        event_type = thread_data->current_event->type;

2476 2477
    if (event_type != ConfigureNotify && event_type != PropertyNotify &&
        event_type != GravityNotify && event_type != ReparentNotify)
2478 2479
        event_type = 0;  /* ignore other events */

2480
    if (data->mapped && event_type != ReparentNotify)
2481 2482
    {
        if (((swp_flags & SWP_HIDEWINDOW) && !(new_style & WS_VISIBLE)) ||
2483
            (!event_type &&
2484
             !is_window_rect_mapped( rectWindow ) && is_window_rect_mapped( &old_window_rect )))
2485
        {
2486
            unmap_window( display, data );
2487 2488
            if (is_window_rect_fullscreen( &old_window_rect )) reset_clipping_window();
        }
2489
    }
2490 2491 2492 2493

    /* don't change position if we are about to minimize or maximize a managed window */
    if (!event_type &&
        !(data->managed && (swp_flags & SWP_STATECHANGED) && (new_style & (WS_MINIMIZE|WS_MAXIMIZE))))
2494 2495
        sync_window_position( display, data, swp_flags,
                              &old_window_rect, &old_whole_rect, &old_client_rect );
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526

    if ((new_style & WS_VISIBLE) &&
        ((new_style & WS_MINIMIZE) || is_window_rect_mapped( rectWindow )))
    {
        if (!data->mapped || (swp_flags & (SWP_FRAMECHANGED|SWP_STATECHANGED)))
            set_wm_hints( display, data );

        if (!data->mapped)
        {
            map_window( display, data, new_style );
        }
        else if ((swp_flags & SWP_STATECHANGED) && (!data->iconic != !(new_style & WS_MINIMIZE)))
        {
            data->iconic = (new_style & WS_MINIMIZE) != 0;
            TRACE( "changing win %p iconic state to %u\n", data->hwnd, data->iconic );
            if (data->iconic)
                XIconifyWindow( display, data->whole_window, DefaultScreen(display) );
            else if (is_window_rect_mapped( rectWindow ))
                XMapWindow( display, data->whole_window );
            update_net_wm_states( display, data );
        }
        else if (!event_type)
        {
            update_net_wm_states( display, data );
        }
    }

    XFlush( display );  /* make sure changes are done before we start painting again */
}


2527 2528 2529
/***********************************************************************
 *           ShowWindow   (X11DRV.@)
 */
2530
UINT CDECL X11DRV_ShowWindow( HWND hwnd, INT cmd, RECT *rect, UINT swp )
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
{
    int x, y;
    unsigned int width, height, border, depth;
    Window root, top;
    DWORD style = GetWindowLongW( hwnd, GWL_STYLE );
    struct x11drv_thread_data *thread_data = x11drv_thread_data();
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );

    if (!data || !data->whole_window || !data->managed || !data->mapped || data->iconic) return swp;
    if (style & WS_MINIMIZE) return swp;
2541
    if (IsRectEmpty( rect )) return swp;
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567

    /* only fetch the new rectangle if the ShowWindow was a result of a window manager event */

    if (!thread_data->current_event || thread_data->current_event->xany.window != data->whole_window)
        return swp;

    if (thread_data->current_event->type != ConfigureNotify &&
        thread_data->current_event->type != PropertyNotify)
        return swp;

    TRACE( "win %p/%lx cmd %d at %s flags %08x\n",
           hwnd, data->whole_window, cmd, wine_dbgstr_rect(rect), swp );

    XGetGeometry( thread_data->display, data->whole_window,
                  &root, &x, &y, &width, &height, &border, &depth );
    XTranslateCoordinates( thread_data->display, data->whole_window, root, 0, 0, &x, &y, &top );
    rect->left   = x;
    rect->top    = y;
    rect->right  = x + width;
    rect->bottom = y + height;
    OffsetRect( rect, virtual_screen_rect.left, virtual_screen_rect.top );
    X11DRV_X_to_window_rect( data, rect );
    return swp & ~(SWP_NOMOVE | SWP_NOCLIENTMOVE | SWP_NOSIZE | SWP_NOCLIENTSIZE);
}


2568
/**********************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
2569
 *		SetWindowIcon (X11DRV.@)
2570 2571 2572 2573 2574 2575 2576 2577
 *
 * hIcon or hIconSm has changed (or is being initialised for the
 * first time). Complete the X11 driver-specific initialisation
 * and set the window hints.
 *
 * This is not entirely correct, may need to create
 * an icon window and set the pixmap as a background
 */
2578
void CDECL X11DRV_SetWindowIcon( HWND hwnd, UINT type, HICON icon )
2579
{
2580
    Display *display = thread_display();
2581
    struct x11drv_win_data *data;
2582 2583


2584
    if (!(data = X11DRV_get_win_data( hwnd ))) return;
2585
    if (!data->whole_window) return;
2586
    if (!data->managed) return;
2587

2588
    if (data->wm_hints)
2589
    {
2590 2591
        if (type == ICON_BIG) set_icon_hints( display, data, icon, 0 );
        else set_icon_hints( display, data, 0, icon );
2592
        XSetWMHints( display, data->whole_window, data->wm_hints );
2593 2594
    }
}
2595 2596 2597 2598 2599 2600 2601


/***********************************************************************
 *		SetWindowRgn  (X11DRV.@)
 *
 * Assign specified region to window (for non-rectangular windows)
 */
2602
int CDECL X11DRV_SetWindowRgn( HWND hwnd, HRGN hrgn, BOOL redraw )
2603 2604 2605 2606 2607 2608 2609
{
    struct x11drv_win_data *data;

    if ((data = X11DRV_get_win_data( hwnd )))
    {
        sync_window_region( thread_display(), data, hrgn );
    }
2610
    else if (X11DRV_get_whole_window( hwnd ))
2611
    {
2612
        SendMessageW( hwnd, WM_X11DRV_SET_WIN_REGION, 0, 0 );
2613 2614 2615
    }
    return TRUE;
}
2616 2617


2618 2619 2620 2621 2622
/***********************************************************************
 *		SetLayeredWindowAttributes  (X11DRV.@)
 *
 * Set transparency attributes for a layered window.
 */
2623
void CDECL X11DRV_SetLayeredWindowAttributes( HWND hwnd, COLORREF key, BYTE alpha, DWORD flags )
2624
{
2625
    struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2626

2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
    if (data)
    {
        if (data->whole_window)
            sync_window_opacity( thread_display(), data->whole_window, key, alpha, flags );
    }
    else
    {
        Window win = X11DRV_get_whole_window( hwnd );
        if (win) sync_window_opacity( gdi_display, win, key, alpha, flags );
    }
2637 2638 2639
}


2640 2641 2642
/**********************************************************************
 *           X11DRV_WindowMessage   (X11DRV.@)
 */
2643
LRESULT CDECL X11DRV_WindowMessage( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
2644
{
2645 2646
    struct x11drv_win_data *data;

2647 2648 2649 2650 2651 2652
    switch(msg)
    {
    case WM_X11DRV_ACQUIRE_SELECTION:
        return X11DRV_AcquireClipboard( hwnd );
    case WM_X11DRV_SET_WIN_FORMAT:
        return set_win_format( hwnd, (XID)wp );
2653 2654 2655
    case WM_X11DRV_SET_WIN_REGION:
        if ((data = X11DRV_get_win_data( hwnd ))) sync_window_region( thread_display(), data, (HRGN)1 );
        return 0;
2656 2657 2658
    case WM_X11DRV_RESIZE_DESKTOP:
        X11DRV_resize_desktop( LOWORD(lp), HIWORD(lp) );
        return 0;
2659
    case WM_X11DRV_SET_CURSOR:
2660
        if ((data = X11DRV_get_win_data( hwnd )) && data->whole_window)
2661
            set_window_cursor( data->whole_window, (HCURSOR)lp );
2662 2663
        else if (hwnd == x11drv_thread_data()->clip_hwnd)
            set_window_cursor( x11drv_thread_data()->clip_window, (HCURSOR)lp );
2664
        return 0;
2665 2666
    case WM_X11DRV_CLIP_CURSOR:
        return clip_cursor_notify( hwnd, (HWND)lp );
2667 2668 2669 2670 2671 2672 2673
    default:
        FIXME( "got window msg %x hwnd %p wp %lx lp %lx\n", msg, hwnd, wp, lp );
        return 0;
    }
}


2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
/***********************************************************************
 *              is_netwm_supported
 */
static BOOL is_netwm_supported( Display *display, Atom atom )
{
    static Atom *net_supported;
    static int net_supported_count = -1;
    int i;

    if (net_supported_count == -1)
    {
        Atom type;
        int format;
        unsigned long count, remaining;

        if (!XGetWindowProperty( display, DefaultRootWindow(display), x11drv_atom(_NET_SUPPORTED), 0,
                                 ~0UL, False, XA_ATOM, &type, &format, &count,
                                 &remaining, (unsigned char **)&net_supported ))
            net_supported_count = get_property_size( format, count ) / sizeof(Atom);
        else
            net_supported_count = 0;
    }

    for (i = 0; i < net_supported_count; i++)
        if (net_supported[i] == atom) return TRUE;
    return FALSE;
}


/***********************************************************************
 *           SysCommand   (X11DRV.@)
 *
 * Perform WM_SYSCOMMAND handling.
 */
2708
LRESULT CDECL X11DRV_SysCommand( HWND hwnd, WPARAM wparam, LPARAM lparam )
2709 2710
{
    WPARAM hittest = wparam & 0x0f;
2711
    int dir;
2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
    Display *display = thread_display();
    struct x11drv_win_data *data;

    if (!(data = X11DRV_get_win_data( hwnd ))) return -1;
    if (!data->whole_window || !data->managed || !data->mapped) return -1;

    switch (wparam & 0xfff0)
    {
    case SC_MOVE:
        if (!hittest) dir = _NET_WM_MOVERESIZE_MOVE_KEYBOARD;
        else dir = _NET_WM_MOVERESIZE_MOVE;
        break;
    case SC_SIZE:
        /* windows without WS_THICKFRAME are not resizable through the window manager */
        if (!(GetWindowLongW( hwnd, GWL_STYLE ) & WS_THICKFRAME)) return -1;

        switch (hittest)
        {
        case WMSZ_LEFT:        dir = _NET_WM_MOVERESIZE_SIZE_LEFT; break;
        case WMSZ_RIGHT:       dir = _NET_WM_MOVERESIZE_SIZE_RIGHT; break;
        case WMSZ_TOP:         dir = _NET_WM_MOVERESIZE_SIZE_TOP; break;
        case WMSZ_TOPLEFT:     dir = _NET_WM_MOVERESIZE_SIZE_TOPLEFT; break;
        case WMSZ_TOPRIGHT:    dir = _NET_WM_MOVERESIZE_SIZE_TOPRIGHT; break;
        case WMSZ_BOTTOM:      dir = _NET_WM_MOVERESIZE_SIZE_BOTTOM; break;
        case WMSZ_BOTTOMLEFT:  dir = _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT; break;
        case WMSZ_BOTTOMRIGHT: dir = _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT; break;
        default:               dir = _NET_WM_MOVERESIZE_SIZE_KEYBOARD; break;
        }
        break;

    case SC_KEYMENU:
        /* prevent a simple ALT press+release from activating the system menu,
         * as that can get confusing on managed windows */
        if ((WCHAR)lparam) return -1;  /* got an explicit char */
        if (GetMenu( hwnd )) return -1;  /* window has a real menu */
        if (!(GetWindowLongW( hwnd, GWL_STYLE ) & WS_SYSMENU)) return -1;  /* no system menu */
        TRACE( "ignoring SC_KEYMENU wp %lx lp %lx\n", wparam, lparam );
        return 0;

    default:
        return -1;
    }

    if (IsZoomed(hwnd)) return -1;

    if (!is_netwm_supported( display, x11drv_atom(_NET_WM_MOVERESIZE) ))
    {
        TRACE( "_NET_WM_MOVERESIZE not supported\n" );
        return -1;
    }

2763
    move_resize_window( display, data, dir );
2764 2765
    return 0;
}