winex11: Export a couple of helper functions for window rectangles.
[wine] / dlls / winex11.drv / window.c
1 /*
2  * Window related functions
3  *
4  * Copyright 1993, 1994, 1995, 1996, 2001 Alexandre Julliard
5  * Copyright 1993 David Metcalfe
6  * Copyright 1995, 1996 Alex Korobka
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * 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 #include "config.h"
24
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31
32 #include <X11/Xlib.h>
33 #include <X11/Xresource.h>
34 #include <X11/Xutil.h>
35 #ifdef HAVE_LIBXSHAPE
36 #include <X11/extensions/shape.h>
37 #endif /* HAVE_LIBXSHAPE */
38
39 #include "windef.h"
40 #include "winbase.h"
41 #include "wingdi.h"
42 #include "winuser.h"
43 #include "wine/unicode.h"
44
45 #include "x11drv.h"
46 #include "xcomposite.h"
47 #include "wine/debug.h"
48 #include "wine/server.h"
49 #include "mwm.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(x11drv);
52
53 #define _NET_WM_MOVERESIZE_SIZE_TOPLEFT      0
54 #define _NET_WM_MOVERESIZE_SIZE_TOP          1
55 #define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT     2
56 #define _NET_WM_MOVERESIZE_SIZE_RIGHT        3
57 #define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT  4
58 #define _NET_WM_MOVERESIZE_SIZE_BOTTOM       5
59 #define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT   6
60 #define _NET_WM_MOVERESIZE_SIZE_LEFT         7
61 #define _NET_WM_MOVERESIZE_MOVE              8
62 #define _NET_WM_MOVERESIZE_SIZE_KEYBOARD     9
63 #define _NET_WM_MOVERESIZE_MOVE_KEYBOARD    10
64
65 #define _NET_WM_STATE_REMOVE  0
66 #define _NET_WM_STATE_ADD     1
67 #define _NET_WM_STATE_TOGGLE  2
68
69 #define SWP_AGG_NOPOSCHANGE (SWP_NOSIZE | SWP_NOMOVE | SWP_NOCLIENTSIZE | SWP_NOCLIENTMOVE | SWP_NOZORDER)
70
71 /* is cursor clipping active? */
72 int clipping_cursor = 0;
73
74 /* X context to associate a hwnd to an X window */
75 XContext winContext = 0;
76
77 /* X context to associate a struct x11drv_win_data to an hwnd */
78 static XContext win_data_context;
79
80 /* time of last user event and window where it's stored */
81 static Time last_user_time;
82 static Window user_time_window;
83
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  * http://standards.freedesktop.org/startup-notification-spec
97  */
98 static void remove_startup_notification(Display *display, Window window)
99 {
100     static LONG startup_notification_removed = 0;
101     char id[1024];
102     char message[1024];
103     int i;
104     int pos;
105     XEvent xevent;
106     const char *src;
107     int srclen;
108
109     if (InterlockedCompareExchange(&startup_notification_removed, 1, 0) != 0)
110         return;
111
112     if (GetEnvironmentVariableA("DESKTOP_STARTUP_ID", id, sizeof(id)) == 0)
113         return;
114     SetEnvironmentVariableA("DESKTOP_STARTUP_ID", NULL);
115
116     if ((src = strstr( id, "_TIME" ))) update_user_time( atol( src + 5 ));
117
118     pos = snprintf(message, sizeof(message), "remove: ID=");
119     message[pos++] = '"';
120     for (i = 0; id[i] && pos < sizeof(message) - 2; i++)
121     {
122         if (id[i] == '"' || id[i] == '\\')
123             message[pos++] = '\\';
124         message[pos++] = id[i];
125     }
126     message[pos++] = '"';
127     message[pos++] = '\0';
128
129     xevent.xclient.type = ClientMessage;
130     xevent.xclient.message_type = x11drv_atom(_NET_STARTUP_INFO_BEGIN);
131     xevent.xclient.display = display;
132     xevent.xclient.window = window;
133     xevent.xclient.format = 8;
134
135     src = message;
136     srclen = strlen(src) + 1;
137
138     wine_tsx11_lock();
139     while (srclen > 0)
140     {
141         int msglen = srclen;
142         if (msglen > 20)
143             msglen = 20;
144         memset(&xevent.xclient.data.b[0], 0, 20);
145         memcpy(&xevent.xclient.data.b[0], src, msglen);
146         src += msglen;
147         srclen -= msglen;
148
149         XSendEvent( display, DefaultRootWindow( display ), False, PropertyChangeMask, &xevent );
150         xevent.xclient.message_type = x11drv_atom(_NET_STARTUP_INFO);
151     }
152     wine_tsx11_unlock();
153 }
154
155
156 struct has_popup_result
157 {
158     HWND hwnd;
159     BOOL found;
160 };
161
162 static BOOL CALLBACK has_popup( HWND hwnd, LPARAM lparam )
163 {
164     struct has_popup_result *result = (struct has_popup_result *)lparam;
165
166     if (hwnd == result->hwnd) return FALSE;  /* popups are always above owner */
167     result->found = (GetWindow( hwnd, GW_OWNER ) == result->hwnd);
168     return !result->found;
169 }
170
171 static BOOL has_owned_popups( HWND hwnd )
172 {
173     struct has_popup_result result;
174
175     result.hwnd = hwnd;
176     result.found = FALSE;
177     EnumWindows( has_popup, (LPARAM)&result );
178     return result.found;
179 }
180
181 /***********************************************************************
182  *              is_window_managed
183  *
184  * Check if a given window should be managed
185  */
186 static BOOL is_window_managed( HWND hwnd, UINT swp_flags, const RECT *window_rect )
187 {
188     DWORD style, ex_style;
189
190     if (!managed_mode) return FALSE;
191
192     /* child windows are not managed */
193     style = GetWindowLongW( hwnd, GWL_STYLE );
194     if ((style & (WS_CHILD|WS_POPUP)) == WS_CHILD) return FALSE;
195     /* activated windows are managed */
196     if (!(swp_flags & (SWP_NOACTIVATE|SWP_HIDEWINDOW))) return TRUE;
197     if (hwnd == GetActiveWindow()) return TRUE;
198     /* windows with caption are managed */
199     if ((style & WS_CAPTION) == WS_CAPTION) return TRUE;
200     /* windows with thick frame are managed */
201     if (style & WS_THICKFRAME) return TRUE;
202     if (style & WS_POPUP)
203     {
204         HMONITOR hmon;
205         MONITORINFO mi;
206
207         /* popup with sysmenu == caption are managed */
208         if (style & WS_SYSMENU) return TRUE;
209         /* full-screen popup windows are managed */
210         hmon = MonitorFromWindow( hwnd, MONITOR_DEFAULTTOPRIMARY );
211         mi.cbSize = sizeof( mi );
212         GetMonitorInfoW( hmon, &mi );
213         if (window_rect->left <= mi.rcWork.left && window_rect->right >= mi.rcWork.right &&
214             window_rect->top <= mi.rcWork.top && window_rect->bottom >= mi.rcWork.bottom)
215             return TRUE;
216     }
217     /* application windows are managed */
218     ex_style = GetWindowLongW( hwnd, GWL_EXSTYLE );
219     if (ex_style & WS_EX_APPWINDOW) return TRUE;
220     /* windows that own popups are managed */
221     if (has_owned_popups( hwnd )) return TRUE;
222     /* default: not managed */
223     return FALSE;
224 }
225
226
227 /***********************************************************************
228  *              is_window_resizable
229  *
230  * Check if window should be made resizable by the window manager
231  */
232 static inline BOOL is_window_resizable( struct x11drv_win_data *data, DWORD style )
233 {
234     if (style & WS_THICKFRAME) return TRUE;
235     /* Metacity needs the window to be resizable to make it fullscreen */
236     return is_window_rect_fullscreen( &data->whole_rect );
237 }
238
239
240 /***********************************************************************
241  *              get_mwm_decorations
242  */
243 static unsigned long get_mwm_decorations( struct x11drv_win_data *data,
244                                           DWORD style, DWORD ex_style )
245 {
246     unsigned long ret = 0;
247
248     if (!decorated_mode) return 0;
249
250     if (IsRectEmpty( &data->window_rect )) return 0;
251     if (data->shaped) return 0;
252
253     if (ex_style & WS_EX_TOOLWINDOW) return 0;
254
255     if ((style & WS_CAPTION) == WS_CAPTION)
256     {
257         ret |= MWM_DECOR_TITLE | MWM_DECOR_BORDER;
258         if (style & WS_SYSMENU) ret |= MWM_DECOR_MENU;
259         if (style & WS_MINIMIZEBOX) ret |= MWM_DECOR_MINIMIZE;
260         if (style & WS_MAXIMIZEBOX) ret |= MWM_DECOR_MAXIMIZE;
261     }
262     if (ex_style & WS_EX_DLGMODALFRAME) ret |= MWM_DECOR_BORDER;
263     else if (style & WS_THICKFRAME) ret |= MWM_DECOR_BORDER | MWM_DECOR_RESIZEH;
264     else if ((style & (WS_DLGFRAME|WS_BORDER)) == WS_DLGFRAME) ret |= MWM_DECOR_BORDER;
265     return ret;
266 }
267
268
269 /***********************************************************************
270  *              get_x11_rect_offset
271  *
272  * Helper for X11DRV_window_to_X_rect and X11DRV_X_to_window_rect.
273  */
274 static void get_x11_rect_offset( struct x11drv_win_data *data, RECT *rect )
275 {
276     DWORD style, ex_style, style_mask = 0, ex_style_mask = 0;
277     unsigned long decor;
278
279     rect->top = rect->bottom = rect->left = rect->right = 0;
280
281     style = GetWindowLongW( data->hwnd, GWL_STYLE );
282     ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
283     decor = get_mwm_decorations( data, style, ex_style );
284
285     if (decor & MWM_DECOR_TITLE) style_mask |= WS_CAPTION;
286     if (decor & MWM_DECOR_BORDER)
287     {
288         style_mask |= WS_DLGFRAME | WS_THICKFRAME;
289         ex_style_mask |= WS_EX_DLGMODALFRAME;
290     }
291
292     AdjustWindowRectEx( rect, style & style_mask, FALSE, ex_style & ex_style_mask );
293 }
294
295
296 /***********************************************************************
297  *              get_window_attributes
298  *
299  * Fill the window attributes structure for an X window.
300  */
301 static int get_window_attributes( Display *display, struct x11drv_win_data *data,
302                                   XSetWindowAttributes *attr )
303 {
304     attr->override_redirect = !data->managed;
305     attr->colormap          = X11DRV_PALETTE_PaletteXColormap;
306     attr->save_under        = ((GetClassLongW( data->hwnd, GCL_STYLE ) & CS_SAVEBITS) != 0);
307     attr->bit_gravity       = NorthWestGravity;
308     attr->win_gravity       = StaticGravity;
309     attr->backing_store     = NotUseful;
310     attr->event_mask        = (ExposureMask | PointerMotionMask |
311                                ButtonPressMask | ButtonReleaseMask | EnterWindowMask |
312                                KeyPressMask | KeyReleaseMask | FocusChangeMask |
313                                KeymapStateMask | StructureNotifyMask);
314     if (data->managed) attr->event_mask |= PropertyChangeMask;
315
316     return (CWOverrideRedirect | CWSaveUnder | CWColormap |
317             CWEventMask | CWBitGravity | CWBackingStore);
318 }
319
320
321 /***********************************************************************
322  *              create_client_window
323  */
324 static Window create_client_window( Display *display, struct x11drv_win_data *data, XVisualInfo *vis )
325 {
326     int cx, cy, mask;
327     XSetWindowAttributes attr;
328     Window client;
329     Visual *client_visual = vis ? vis->visual : visual;
330
331     attr.bit_gravity = NorthWestGravity;
332     attr.win_gravity = NorthWestGravity;
333     attr.backing_store = NotUseful;
334     attr.event_mask = (ExposureMask | PointerMotionMask |
335                        ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
336     mask = CWEventMask | CWBitGravity | CWWinGravity | CWBackingStore;
337
338     if ((cx = data->client_rect.right - data->client_rect.left) <= 0) cx = 1;
339     else if (cx > 65535) cx = 65535;
340     if ((cy = data->client_rect.bottom - data->client_rect.top) <= 0) cy = 1;
341     else if (cy > 65535) cy = 65535;
342
343     wine_tsx11_lock();
344
345     if (vis)
346     {
347         attr.colormap = XCreateColormap( display, root_window, vis->visual,
348                                          (vis->class == PseudoColor || vis->class == GrayScale ||
349                                           vis->class == DirectColor) ? AllocAll : AllocNone );
350         mask |= CWColormap;
351     }
352
353     client = XCreateWindow( display, data->whole_window,
354                             data->client_rect.left - data->whole_rect.left,
355                             data->client_rect.top - data->whole_rect.top,
356                             cx, cy, 0, screen_depth, InputOutput,
357                             client_visual, mask, &attr );
358     if (!client)
359     {
360         wine_tsx11_unlock();
361         return 0;
362     }
363
364     if (data->client_window)
365     {
366         XDeleteContext( display, data->client_window, winContext );
367         XDestroyWindow( display, data->client_window );
368     }
369     data->client_window = client;
370     data->visualid = XVisualIDFromVisual( client_visual );
371
372     if (data->colormap) XFreeColormap( display, data->colormap );
373     data->colormap = vis ? attr.colormap : 0;
374
375     XMapWindow( display, data->client_window );
376     XSaveContext( display, data->client_window, winContext, (char *)data->hwnd );
377     wine_tsx11_unlock();
378
379     SetPropA( data->hwnd, client_window_prop, (HANDLE)data->client_window );
380     return data->client_window;
381 }
382
383
384 /***********************************************************************
385  *              sync_window_style
386  *
387  * Change the X window attributes when the window style has changed.
388  */
389 static void sync_window_style( Display *display, struct x11drv_win_data *data )
390 {
391     if (data->whole_window != root_window)
392     {
393         XSetWindowAttributes attr;
394         int mask = get_window_attributes( display, data, &attr );
395
396         wine_tsx11_lock();
397         XChangeWindowAttributes( display, data->whole_window, mask, &attr );
398         wine_tsx11_unlock();
399     }
400 }
401
402
403 /***********************************************************************
404  *              sync_window_region
405  *
406  * Update the X11 window region.
407  */
408 static void sync_window_region( Display *display, struct x11drv_win_data *data, HRGN win_region )
409 {
410 #ifdef HAVE_LIBXSHAPE
411     HRGN hrgn = win_region;
412
413     if (!data->whole_window) return;
414     data->shaped = FALSE;
415
416     if (IsRectEmpty( &data->window_rect ))  /* set an empty shape */
417     {
418         static XRectangle empty_rect;
419         wine_tsx11_lock();
420         XShapeCombineRectangles( display, data->whole_window, ShapeBounding, 0, 0,
421                                  &empty_rect, 1, ShapeSet, YXBanded );
422         wine_tsx11_unlock();
423         return;
424     }
425
426     if (hrgn == (HRGN)1)  /* hack: win_region == 1 means retrieve region from server */
427     {
428         if (!(hrgn = CreateRectRgn( 0, 0, 0, 0 ))) return;
429         if (GetWindowRgn( data->hwnd, hrgn ) == ERROR)
430         {
431             DeleteObject( hrgn );
432             hrgn = 0;
433         }
434     }
435
436     if (!hrgn)
437     {
438         wine_tsx11_lock();
439         XShapeCombineMask( display, data->whole_window, ShapeBounding, 0, 0, None, ShapeSet );
440         wine_tsx11_unlock();
441     }
442     else
443     {
444         RGNDATA *pRegionData;
445
446         if (GetWindowLongW( data->hwnd, GWL_EXSTYLE ) & WS_EX_LAYOUTRTL) MirrorRgn( data->hwnd, hrgn );
447         if ((pRegionData = X11DRV_GetRegionData( hrgn, 0 )))
448         {
449             wine_tsx11_lock();
450             XShapeCombineRectangles( display, data->whole_window, ShapeBounding,
451                                      data->window_rect.left - data->whole_rect.left,
452                                      data->window_rect.top - data->whole_rect.top,
453                                      (XRectangle *)pRegionData->Buffer,
454                                      pRegionData->rdh.nCount, ShapeSet, YXBanded );
455             wine_tsx11_unlock();
456             HeapFree(GetProcessHeap(), 0, pRegionData);
457             data->shaped = TRUE;
458         }
459     }
460     if (hrgn && hrgn != win_region) DeleteObject( hrgn );
461 #endif  /* HAVE_LIBXSHAPE */
462 }
463
464
465 /***********************************************************************
466  *              sync_window_opacity
467  */
468 static void sync_window_opacity( Display *display, Window win,
469                                  COLORREF key, BYTE alpha, DWORD flags )
470 {
471     unsigned long opacity = 0xffffffff;
472
473     if (flags & LWA_ALPHA) opacity = (0xffffffff / 0xff) * alpha;
474
475     if (flags & LWA_COLORKEY) FIXME("LWA_COLORKEY not supported\n");
476
477     wine_tsx11_lock();
478     if (opacity == 0xffffffff)
479         XDeleteProperty( display, win, x11drv_atom(_NET_WM_WINDOW_OPACITY) );
480     else
481         XChangeProperty( display, win, x11drv_atom(_NET_WM_WINDOW_OPACITY),
482                          XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&opacity, 1 );
483     wine_tsx11_unlock();
484 }
485
486
487 /***********************************************************************
488  *              sync_window_text
489  */
490 static void sync_window_text( Display *display, Window win, const WCHAR *text )
491 {
492     UINT count;
493     char *buffer, *utf8_buffer;
494     XTextProperty prop;
495
496     /* allocate new buffer for window text */
497     count = WideCharToMultiByte(CP_UNIXCP, 0, text, -1, NULL, 0, NULL, NULL);
498     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, count ))) return;
499     WideCharToMultiByte(CP_UNIXCP, 0, text, -1, buffer, count, NULL, NULL);
500
501     count = WideCharToMultiByte(CP_UTF8, 0, text, strlenW(text), NULL, 0, NULL, NULL);
502     if (!(utf8_buffer = HeapAlloc( GetProcessHeap(), 0, count )))
503     {
504         HeapFree( GetProcessHeap(), 0, buffer );
505         return;
506     }
507     WideCharToMultiByte(CP_UTF8, 0, text, strlenW(text), utf8_buffer, count, NULL, NULL);
508
509     wine_tsx11_lock();
510     if (XmbTextListToTextProperty( display, &buffer, 1, XStdICCTextStyle, &prop ) == Success)
511     {
512         XSetWMName( display, win, &prop );
513         XSetWMIconName( display, win, &prop );
514         XFree( prop.value );
515     }
516     /*
517       Implements a NET_WM UTF-8 title. It should be without a trailing \0,
518       according to the standard
519       ( http://www.pps.jussieu.fr/~jch/software/UTF8_STRING/UTF8_STRING.text ).
520     */
521     XChangeProperty( display, win, x11drv_atom(_NET_WM_NAME), x11drv_atom(UTF8_STRING),
522                      8, PropModeReplace, (unsigned char *) utf8_buffer, count);
523     wine_tsx11_unlock();
524
525     HeapFree( GetProcessHeap(), 0, utf8_buffer );
526     HeapFree( GetProcessHeap(), 0, buffer );
527 }
528
529
530 /***********************************************************************
531  *              set_win_format
532  */
533 static BOOL set_win_format( HWND hwnd, XID fbconfig_id )
534 {
535     struct x11drv_win_data *data;
536     XVisualInfo *vis;
537     int w, h;
538
539     if (!(data = X11DRV_get_win_data(hwnd)) &&
540         !(data = X11DRV_create_win_data(hwnd))) return FALSE;
541
542     if (!(vis = visual_from_fbconfig_id(fbconfig_id))) return FALSE;
543
544     if (data->whole_window)
545     {
546         Display *display = thread_display();
547         Window client = data->client_window;
548
549         if (vis->visualid != data->visualid)
550         {
551             client = create_client_window( display, data, vis );
552             TRACE( "re-created client window %lx for %p fbconfig %lx\n", client, data->hwnd, fbconfig_id );
553         }
554         wine_tsx11_lock();
555         XFree(vis);
556         XFlush( display );
557         wine_tsx11_unlock();
558         if (client) goto done;
559         return FALSE;
560     }
561
562     w = data->client_rect.right - data->client_rect.left;
563     h = data->client_rect.bottom - data->client_rect.top;
564
565     if(w <= 0) w = 1;
566     if(h <= 0) h = 1;
567
568 #ifdef SONAME_LIBXCOMPOSITE
569     if(usexcomposite)
570     {
571         XSetWindowAttributes attrib;
572         static Window dummy_parent;
573
574         wine_tsx11_lock();
575         attrib.override_redirect = True;
576         if (!dummy_parent)
577         {
578             dummy_parent = XCreateWindow( gdi_display, root_window, -1, -1, 1, 1, 0, screen_depth,
579                                          InputOutput, visual, CWOverrideRedirect, &attrib );
580             XMapWindow( gdi_display, dummy_parent );
581         }
582         data->colormap = XCreateColormap(gdi_display, dummy_parent, vis->visual,
583                                          (vis->class == PseudoColor ||
584                                           vis->class == GrayScale ||
585                                           vis->class == DirectColor) ?
586                                          AllocAll : AllocNone);
587         attrib.colormap = data->colormap;
588         XInstallColormap(gdi_display, attrib.colormap);
589
590         if(data->gl_drawable) XDestroyWindow(gdi_display, data->gl_drawable);
591         data->gl_drawable = XCreateWindow(gdi_display, dummy_parent, -w, 0, w, h, 0,
592                                           vis->depth, InputOutput, vis->visual,
593                                           CWColormap | CWOverrideRedirect,
594                                           &attrib);
595         if(data->gl_drawable)
596         {
597             pXCompositeRedirectWindow(gdi_display, data->gl_drawable,
598                                       CompositeRedirectManual);
599             XMapWindow(gdi_display, data->gl_drawable);
600         }
601         XFree(vis);
602         XFlush( gdi_display );
603         wine_tsx11_unlock();
604     }
605     else
606 #endif
607     {
608         WARN("XComposite is not available, using GLXPixmap hack\n");
609
610         wine_tsx11_lock();
611
612         if(data->pixmap) XFreePixmap(gdi_display, data->pixmap);
613         data->pixmap = XCreatePixmap(gdi_display, root_window, w, h, vis->depth);
614         if(!data->pixmap)
615         {
616             XFree(vis);
617             wine_tsx11_unlock();
618             return FALSE;
619         }
620
621         if(data->gl_drawable) destroy_glxpixmap(gdi_display, data->gl_drawable);
622         data->gl_drawable = create_glxpixmap(gdi_display, vis, data->pixmap);
623         if(!data->gl_drawable)
624         {
625             XFreePixmap(gdi_display, data->pixmap);
626             data->pixmap = 0;
627         }
628         XFree(vis);
629         XFlush( gdi_display );
630         wine_tsx11_unlock();
631         if (data->pixmap) SetPropA(hwnd, pixmap_prop, (HANDLE)data->pixmap);
632     }
633
634     if (!data->gl_drawable) return FALSE;
635
636     TRACE("Created GL drawable 0x%lx, using FBConfigID 0x%lx\n",
637           data->gl_drawable, fbconfig_id);
638     SetPropA(hwnd, gl_drawable_prop, (HANDLE)data->gl_drawable);
639
640 done:
641     data->fbconfig_id = fbconfig_id;
642     SetPropA(hwnd, fbconfig_id_prop, (HANDLE)data->fbconfig_id);
643     /* force DCE invalidation */
644     SetWindowPos( hwnd, 0, 0, 0, 0, 0,
645                   SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE |
646                   SWP_NOREDRAW | SWP_DEFERERASE | SWP_NOSENDCHANGING | SWP_STATECHANGED);
647     return TRUE;
648 }
649
650 /***********************************************************************
651  *              sync_gl_drawable
652  */
653 static void sync_gl_drawable(struct x11drv_win_data *data)
654 {
655     int w = data->client_rect.right - data->client_rect.left;
656     int h = data->client_rect.bottom - data->client_rect.top;
657     XVisualInfo *vis;
658     Drawable glxp;
659     Pixmap pix;
660
661     if (w <= 0) w = 1;
662     if (h <= 0) h = 1;
663
664     TRACE("Resizing GL drawable 0x%lx to %dx%d\n", data->gl_drawable, w, h);
665 #ifdef SONAME_LIBXCOMPOSITE
666     if(usexcomposite)
667     {
668         wine_tsx11_lock();
669         XMoveResizeWindow(gdi_display, data->gl_drawable, -w, 0, w, h);
670         wine_tsx11_unlock();
671         return;
672     }
673 #endif
674
675     if (!(vis = visual_from_fbconfig_id(data->fbconfig_id))) return;
676
677     wine_tsx11_lock();
678     pix = XCreatePixmap(gdi_display, root_window, w, h, vis->depth);
679     if(!pix)
680     {
681         ERR("Failed to create pixmap for offscreen rendering\n");
682         XFree(vis);
683         wine_tsx11_unlock();
684         return;
685     }
686
687     glxp = create_glxpixmap(gdi_display, vis, pix);
688     if(!glxp)
689     {
690         ERR("Failed to create drawable for offscreen rendering\n");
691         XFreePixmap(gdi_display, pix);
692         XFree(vis);
693         wine_tsx11_unlock();
694         return;
695     }
696
697     XFree(vis);
698
699     mark_drawable_dirty(data->gl_drawable, glxp);
700
701     XFreePixmap(gdi_display, data->pixmap);
702     destroy_glxpixmap(gdi_display, data->gl_drawable);
703     TRACE( "Recreated GL drawable %lx to replace %lx\n", glxp, data->gl_drawable );
704
705     data->pixmap = pix;
706     data->gl_drawable = glxp;
707
708     XFlush( gdi_display );
709     wine_tsx11_unlock();
710
711     SetPropA(data->hwnd, gl_drawable_prop, (HANDLE)data->gl_drawable);
712     SetPropA(data->hwnd, pixmap_prop, (HANDLE)data->pixmap);
713 }
714
715
716 /***********************************************************************
717  *              get_window_changes
718  *
719  * fill the window changes structure
720  */
721 static int get_window_changes( XWindowChanges *changes, const RECT *old, const RECT *new )
722 {
723     int mask = 0;
724
725     if (old->right - old->left != new->right - new->left )
726     {
727         if ((changes->width = new->right - new->left) <= 0) changes->width = 1;
728         else if (changes->width > 65535) changes->width = 65535;
729         mask |= CWWidth;
730     }
731     if (old->bottom - old->top != new->bottom - new->top)
732     {
733         if ((changes->height = new->bottom - new->top) <= 0) changes->height = 1;
734         else if (changes->height > 65535) changes->height = 65535;
735         mask |= CWHeight;
736     }
737     if (old->left != new->left)
738     {
739         changes->x = new->left;
740         mask |= CWX;
741     }
742     if (old->top != new->top)
743     {
744         changes->y = new->top;
745         mask |= CWY;
746     }
747     return mask;
748 }
749
750
751 /***********************************************************************
752  *              create_icon_window
753  */
754 static Window create_icon_window( Display *display, struct x11drv_win_data *data )
755 {
756     XSetWindowAttributes attr;
757
758     attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
759                        ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
760     attr.bit_gravity = NorthWestGravity;
761     attr.backing_store = NotUseful/*WhenMapped*/;
762     attr.colormap      = X11DRV_PALETTE_PaletteXColormap; /* Needed due to our visual */
763
764     wine_tsx11_lock();
765     data->icon_window = XCreateWindow( display, root_window, 0, 0,
766                                        GetSystemMetrics( SM_CXICON ),
767                                        GetSystemMetrics( SM_CYICON ),
768                                        0, screen_depth,
769                                        InputOutput, visual,
770                                        CWEventMask | CWBitGravity | CWBackingStore | CWColormap, &attr );
771     XSaveContext( display, data->icon_window, winContext, (char *)data->hwnd );
772     XFlush( display );  /* make sure the window exists before we start painting to it */
773     wine_tsx11_unlock();
774
775     TRACE( "created %lx\n", data->icon_window );
776     SetPropA( data->hwnd, icon_window_prop, (HANDLE)data->icon_window );
777     return data->icon_window;
778 }
779
780
781
782 /***********************************************************************
783  *              destroy_icon_window
784  */
785 static void destroy_icon_window( Display *display, struct x11drv_win_data *data )
786 {
787     if (!data->icon_window) return;
788     wine_tsx11_lock();
789     XDeleteContext( display, data->icon_window, winContext );
790     XDestroyWindow( display, data->icon_window );
791     data->icon_window = 0;
792     wine_tsx11_unlock();
793     RemovePropA( data->hwnd, icon_window_prop );
794 }
795
796
797 /***********************************************************************
798  *              get_bitmap_argb
799  *
800  * Return the bitmap bits in ARGB format. Helper for setting icon hints.
801  */
802 static unsigned long *get_bitmap_argb( HDC hdc, HBITMAP color, HBITMAP mask, unsigned int *size )
803 {
804     BITMAP bm;
805     BITMAPINFO *info;
806     unsigned int *ptr, *bits = NULL;
807     unsigned char *mask_bits = NULL;
808     int i, j, has_alpha = 0;
809
810     if (!GetObjectW( color, sizeof(bm), &bm )) return NULL;
811     if (!(info = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( BITMAPINFO, bmiColors[256] )))) return NULL;
812     info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
813     info->bmiHeader.biWidth = bm.bmWidth;
814     info->bmiHeader.biHeight = -bm.bmHeight;
815     info->bmiHeader.biPlanes = 1;
816     info->bmiHeader.biBitCount = 32;
817     info->bmiHeader.biCompression = BI_RGB;
818     info->bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
819     info->bmiHeader.biXPelsPerMeter = 0;
820     info->bmiHeader.biYPelsPerMeter = 0;
821     info->bmiHeader.biClrUsed = 0;
822     info->bmiHeader.biClrImportant = 0;
823     *size = bm.bmWidth * bm.bmHeight + 2;
824     if (!(bits = HeapAlloc( GetProcessHeap(), 0, *size * sizeof(long) ))) goto failed;
825     if (!GetDIBits( hdc, color, 0, bm.bmHeight, bits + 2, info, DIB_RGB_COLORS )) goto failed;
826
827     bits[0] = bm.bmWidth;
828     bits[1] = bm.bmHeight;
829
830     for (i = 0; i < bm.bmWidth * bm.bmHeight; i++)
831         if ((has_alpha = (bits[i + 2] & 0xff000000) != 0)) break;
832
833     if (!has_alpha)
834     {
835         unsigned int width_bytes = (bm.bmWidth + 31) / 32 * 4;
836         /* generate alpha channel from the mask */
837         info->bmiHeader.biBitCount = 1;
838         info->bmiHeader.biSizeImage = width_bytes * bm.bmHeight;
839         if (!(mask_bits = HeapAlloc( GetProcessHeap(), 0, info->bmiHeader.biSizeImage ))) goto failed;
840         if (!GetDIBits( hdc, mask, 0, bm.bmHeight, mask_bits, info, DIB_RGB_COLORS )) goto failed;
841         ptr = bits + 2;
842         for (i = 0; i < bm.bmHeight; i++)
843             for (j = 0; j < bm.bmWidth; j++, ptr++)
844                 if (!((mask_bits[i * width_bytes + j / 8] << (j % 8)) & 0x80)) *ptr |= 0xff000000;
845         HeapFree( GetProcessHeap(), 0, mask_bits );
846     }
847     HeapFree( GetProcessHeap(), 0, info );
848
849     /* convert to array of longs */
850     if (bits && sizeof(long) > sizeof(int))
851         for (i = *size - 1; i >= 0; i--) ((unsigned long *)bits)[i] = bits[i];
852
853     return (unsigned long *)bits;
854
855 failed:
856     HeapFree( GetProcessHeap(), 0, info );
857     HeapFree( GetProcessHeap(), 0, bits );
858     HeapFree( GetProcessHeap(), 0, mask_bits );
859     return NULL;
860 }
861
862
863 /***********************************************************************
864  *              set_icon_hints
865  *
866  * Set the icon wm hints
867  */
868 static void set_icon_hints( Display *display, struct x11drv_win_data *data,
869                             HICON icon_big, HICON icon_small )
870 {
871     XWMHints *hints = data->wm_hints;
872
873     if (!icon_big)
874     {
875         icon_big = (HICON)SendMessageW( data->hwnd, WM_GETICON, ICON_BIG, 0 );
876         if (!icon_big) icon_big = (HICON)GetClassLongPtrW( data->hwnd, GCLP_HICON );
877     }
878     if (!icon_small)
879     {
880         icon_small = (HICON)SendMessageW( data->hwnd, WM_GETICON, ICON_SMALL, 0 );
881         if (!icon_small) icon_small = (HICON)GetClassLongPtrW( data->hwnd, GCLP_HICONSM );
882     }
883
884     if (data->hWMIconBitmap) DeleteObject( data->hWMIconBitmap );
885     if (data->hWMIconMask) DeleteObject( data->hWMIconMask);
886     data->hWMIconBitmap = 0;
887     data->hWMIconMask = 0;
888
889     if (!icon_big)
890     {
891         if (!data->icon_window) create_icon_window( display, data );
892         hints->icon_window = data->icon_window;
893         hints->flags = (hints->flags & ~(IconPixmapHint | IconMaskHint)) | IconWindowHint;
894     }
895     else
896     {
897         HBITMAP hbmOrig;
898         RECT rcMask;
899         BITMAP bm;
900         ICONINFO ii, ii_small;
901         HDC hDC;
902         unsigned int size;
903         unsigned long *bits;
904
905         if (!GetIconInfo(icon_big, &ii)) return;
906
907         GetObjectW(ii.hbmMask, sizeof(bm), &bm);
908         rcMask.top    = 0;
909         rcMask.left   = 0;
910         rcMask.right  = bm.bmWidth;
911         rcMask.bottom = bm.bmHeight;
912
913         hDC = CreateCompatibleDC(0);
914         bits = get_bitmap_argb( hDC, ii.hbmColor, ii.hbmMask, &size );
915         if (bits && GetIconInfo( icon_small, &ii_small ))
916         {
917             unsigned int size_small;
918             unsigned long *bits_small, *new;
919
920             if ((bits_small = get_bitmap_argb( hDC, ii_small.hbmColor, ii_small.hbmMask, &size_small )) &&
921                 (bits_small[0] != bits[0] || bits_small[1] != bits[1]))  /* size must be different */
922             {
923                 if ((new = HeapReAlloc( GetProcessHeap(), 0, bits,
924                                         (size + size_small) * sizeof(unsigned long) )))
925                 {
926                     bits = new;
927                     memcpy( bits + size, bits_small, size_small * sizeof(unsigned long) );
928                     size += size_small;
929                 }
930             }
931             HeapFree( GetProcessHeap(), 0, bits_small );
932             DeleteObject( ii_small.hbmColor );
933             DeleteObject( ii_small.hbmMask );
934         }
935         wine_tsx11_lock();
936         if (bits)
937             XChangeProperty( display, data->whole_window, x11drv_atom(_NET_WM_ICON),
938                              XA_CARDINAL, 32, PropModeReplace, (unsigned char *)bits, size );
939         else
940             XDeleteProperty( display, data->whole_window, x11drv_atom(_NET_WM_ICON) );
941         wine_tsx11_unlock();
942         HeapFree( GetProcessHeap(), 0, bits );
943
944         hbmOrig = SelectObject(hDC, ii.hbmMask);
945         InvertRect(hDC, &rcMask);
946         SelectObject(hDC, ii.hbmColor);  /* force the color bitmap to x11drv mode too */
947         SelectObject(hDC, hbmOrig);
948
949         data->hWMIconBitmap = ii.hbmColor;
950         data->hWMIconMask = ii.hbmMask;
951
952         hints->icon_pixmap = X11DRV_get_pixmap(data->hWMIconBitmap);
953         hints->icon_mask = X11DRV_get_pixmap(data->hWMIconMask);
954         destroy_icon_window( display, data );
955         hints->flags = (hints->flags & ~IconWindowHint) | IconPixmapHint | IconMaskHint;
956
957         DeleteDC(hDC);
958     }
959 }
960
961
962 /***********************************************************************
963  *              set_size_hints
964  *
965  * set the window size hints
966  */
967 static void set_size_hints( Display *display, struct x11drv_win_data *data, DWORD style )
968 {
969     XSizeHints* size_hints;
970
971     if (!(size_hints = XAllocSizeHints())) return;
972
973     size_hints->win_gravity = StaticGravity;
974     size_hints->flags |= PWinGravity;
975
976     /* don't update size hints if window is not in normal state */
977     if (!(style & (WS_MINIMIZE | WS_MAXIMIZE)))
978     {
979         if (data->hwnd != GetDesktopWindow())  /* don't force position of desktop */
980         {
981             size_hints->x = data->whole_rect.left;
982             size_hints->y = data->whole_rect.top;
983             size_hints->flags |= PPosition;
984         }
985
986         if (!is_window_resizable( data, style ))
987         {
988             size_hints->max_width = data->whole_rect.right - data->whole_rect.left;
989             size_hints->max_height = data->whole_rect.bottom - data->whole_rect.top;
990             if (size_hints->max_width <= 0 ||size_hints->max_height <= 0)
991                 size_hints->max_width = size_hints->max_height = 1;
992             size_hints->min_width = size_hints->max_width;
993             size_hints->min_height = size_hints->max_height;
994             size_hints->flags |= PMinSize | PMaxSize;
995         }
996     }
997     XSetWMNormalHints( display, data->whole_window, size_hints );
998     XFree( size_hints );
999 }
1000
1001
1002 /***********************************************************************
1003  *              get_process_name
1004  *
1005  * get the name of the current process for setting class hints
1006  */
1007 static char *get_process_name(void)
1008 {
1009     static char *name;
1010
1011     if (!name)
1012     {
1013         WCHAR module[MAX_PATH];
1014         DWORD len = GetModuleFileNameW( 0, module, MAX_PATH );
1015         if (len && len < MAX_PATH)
1016         {
1017             char *ptr;
1018             WCHAR *p, *appname = module;
1019
1020             if ((p = strrchrW( appname, '/' ))) appname = p + 1;
1021             if ((p = strrchrW( appname, '\\' ))) appname = p + 1;
1022             len = WideCharToMultiByte( CP_UNIXCP, 0, appname, -1, NULL, 0, NULL, NULL );
1023             if ((ptr = HeapAlloc( GetProcessHeap(), 0, len )))
1024             {
1025                 WideCharToMultiByte( CP_UNIXCP, 0, appname, -1, ptr, len, NULL, NULL );
1026                 name = ptr;
1027             }
1028         }
1029     }
1030     return name;
1031 }
1032
1033
1034 /***********************************************************************
1035  *              set_initial_wm_hints
1036  *
1037  * Set the window manager hints that don't change over the lifetime of a window.
1038  */
1039 static void set_initial_wm_hints( Display *display, struct x11drv_win_data *data )
1040 {
1041     long i;
1042     Atom protocols[3];
1043     Atom dndVersion = WINE_XDND_VERSION;
1044     XClassHint *class_hints;
1045     char *process_name = get_process_name();
1046
1047     wine_tsx11_lock();
1048
1049     /* wm protocols */
1050     i = 0;
1051     protocols[i++] = x11drv_atom(WM_DELETE_WINDOW);
1052     protocols[i++] = x11drv_atom(_NET_WM_PING);
1053     if (use_take_focus) protocols[i++] = x11drv_atom(WM_TAKE_FOCUS);
1054     XChangeProperty( display, data->whole_window, x11drv_atom(WM_PROTOCOLS),
1055                      XA_ATOM, 32, PropModeReplace, (unsigned char *)protocols, i );
1056
1057     /* class hints */
1058     if ((class_hints = XAllocClassHint()))
1059     {
1060         static char wine[] = "Wine";
1061
1062         class_hints->res_name = process_name;
1063         class_hints->res_class = wine;
1064         XSetClassHint( display, data->whole_window, class_hints );
1065         XFree( class_hints );
1066     }
1067
1068     /* set the WM_CLIENT_MACHINE and WM_LOCALE_NAME properties */
1069     XSetWMProperties(display, data->whole_window, NULL, NULL, NULL, 0, NULL, NULL, NULL);
1070     /* set the pid. together, these properties are needed so the window manager can kill us if we freeze */
1071     i = getpid();
1072     XChangeProperty(display, data->whole_window, x11drv_atom(_NET_WM_PID),
1073                     XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&i, 1);
1074
1075     XChangeProperty( display, data->whole_window, x11drv_atom(XdndAware),
1076                      XA_ATOM, 32, PropModeReplace, (unsigned char*)&dndVersion, 1 );
1077
1078     update_user_time( 0 );  /* make sure that the user time window exists */
1079     if (user_time_window)
1080         XChangeProperty( display, data->whole_window, x11drv_atom(_NET_WM_USER_TIME_WINDOW),
1081                          XA_WINDOW, 32, PropModeReplace, (unsigned char *)&user_time_window, 1 );
1082
1083     data->wm_hints = XAllocWMHints();
1084     wine_tsx11_unlock();
1085
1086     if (data->wm_hints)
1087     {
1088         data->wm_hints->flags = 0;
1089         set_icon_hints( display, data, 0, 0 );
1090     }
1091 }
1092
1093
1094 /***********************************************************************
1095  *              get_owner_whole_window
1096  *
1097  * Retrieve an owner's window, creating it if necessary.
1098  */
1099 static Window get_owner_whole_window( HWND owner, BOOL force_managed )
1100 {
1101     struct x11drv_win_data *data;
1102
1103     if (!owner) return 0;
1104
1105     if (!(data = X11DRV_get_win_data( owner )))
1106     {
1107         if (GetWindowThreadProcessId( owner, NULL ) != GetCurrentThreadId() ||
1108             !(data = X11DRV_create_win_data( owner )))
1109             return (Window)GetPropA( owner, whole_window_prop );
1110     }
1111     else if (!data->managed && force_managed)  /* make it managed */
1112     {
1113         SetWindowPos( owner, 0, 0, 0, 0, 0,
1114                       SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE |
1115                       SWP_NOREDRAW | SWP_DEFERERASE | SWP_NOSENDCHANGING | SWP_STATECHANGED );
1116     }
1117     return data->whole_window;
1118 }
1119
1120
1121 /***********************************************************************
1122  *              set_wm_hints
1123  *
1124  * Set the window manager hints for a newly-created window
1125  */
1126 static void set_wm_hints( Display *display, struct x11drv_win_data *data )
1127 {
1128     Window group_leader = data->whole_window;
1129     Window owner_win = 0;
1130     Atom window_type;
1131     MwmHints mwm_hints;
1132     DWORD style, ex_style;
1133     HWND owner;
1134
1135     if (data->hwnd == GetDesktopWindow())
1136     {
1137         /* force some styles for the desktop to get the correct decorations */
1138         style = WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1139         ex_style = WS_EX_APPWINDOW;
1140         owner = 0;
1141     }
1142     else
1143     {
1144         style = GetWindowLongW( data->hwnd, GWL_STYLE );
1145         ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
1146         owner = GetWindow( data->hwnd, GW_OWNER );
1147         if ((owner_win = get_owner_whole_window( owner, data->managed ))) group_leader = owner_win;
1148     }
1149
1150     wine_tsx11_lock();
1151
1152     if (owner_win) XSetTransientForHint( display, data->whole_window, owner_win );
1153
1154     /* size hints */
1155     set_size_hints( display, data, style );
1156
1157     /* Only use dialog type for owned popups. Metacity allows making fullscreen
1158      * only normal windows, and doesn't handle correctly TRANSIENT_FOR hint for
1159      * dialogs owned by fullscreen windows.
1160      */
1161     if ((style & WS_POPUP) && owner) window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_DIALOG);
1162     else window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_NORMAL);
1163
1164     XChangeProperty(display, data->whole_window, x11drv_atom(_NET_WM_WINDOW_TYPE),
1165                     XA_ATOM, 32, PropModeReplace, (unsigned char*)&window_type, 1);
1166
1167     mwm_hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
1168     mwm_hints.decorations = get_mwm_decorations( data, style, ex_style );
1169     mwm_hints.functions = MWM_FUNC_MOVE;
1170     if (is_window_resizable( data, style )) mwm_hints.functions |= MWM_FUNC_RESIZE;
1171     if (!(style & WS_DISABLED))
1172     {
1173         if (style & WS_MINIMIZEBOX) mwm_hints.functions |= MWM_FUNC_MINIMIZE;
1174         if (style & WS_MAXIMIZEBOX) mwm_hints.functions |= MWM_FUNC_MAXIMIZE;
1175         if (style & WS_SYSMENU)     mwm_hints.functions |= MWM_FUNC_CLOSE;
1176     }
1177
1178     XChangeProperty( display, data->whole_window, x11drv_atom(_MOTIF_WM_HINTS),
1179                      x11drv_atom(_MOTIF_WM_HINTS), 32, PropModeReplace,
1180                      (unsigned char*)&mwm_hints, sizeof(mwm_hints)/sizeof(long) );
1181
1182     /* wm hints */
1183     if (data->wm_hints)
1184     {
1185         data->wm_hints->flags |= InputHint | StateHint | WindowGroupHint;
1186         data->wm_hints->input = !use_take_focus && !(style & WS_DISABLED);
1187         data->wm_hints->initial_state = (style & WS_MINIMIZE) ? IconicState : NormalState;
1188         data->wm_hints->window_group = group_leader;
1189         XSetWMHints( display, data->whole_window, data->wm_hints );
1190     }
1191
1192     wine_tsx11_unlock();
1193 }
1194
1195
1196 /***********************************************************************
1197  *     init_clip_window
1198  */
1199 Window init_clip_window(void)
1200 {
1201     struct x11drv_thread_data *data = x11drv_init_thread_data();
1202
1203     if (!data->clip_window &&
1204         (data->clip_window = (Window)GetPropA( GetDesktopWindow(), clip_window_prop )))
1205     {
1206         wine_tsx11_lock();
1207         XSelectInput( data->display, data->clip_window, StructureNotifyMask );
1208         wine_tsx11_unlock();
1209     }
1210     return data->clip_window;
1211 }
1212
1213
1214 /***********************************************************************
1215  *     update_user_time
1216  */
1217 void update_user_time( Time time )
1218 {
1219     wine_tsx11_lock();
1220     if (!user_time_window)
1221     {
1222         user_time_window = XCreateWindow( gdi_display, root_window, -1, -1, 1, 1, 0, 0, InputOnly,
1223                                           DefaultVisual(gdi_display,DefaultScreen(gdi_display)), 0, NULL );
1224         TRACE( "user time window %lx\n", user_time_window );
1225     }
1226     if (time && (!last_user_time || (long)(time - last_user_time) > 0))
1227     {
1228         last_user_time = time;
1229         XChangeProperty( gdi_display, user_time_window, x11drv_atom(_NET_WM_USER_TIME),
1230                          XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&time, 1 );
1231     }
1232     wine_tsx11_unlock();
1233 }
1234
1235 /***********************************************************************
1236  *     update_net_wm_states
1237  */
1238 void update_net_wm_states( Display *display, struct x11drv_win_data *data )
1239 {
1240     static const unsigned int state_atoms[NB_NET_WM_STATES] =
1241     {
1242         XATOM__NET_WM_STATE_FULLSCREEN,
1243         XATOM__NET_WM_STATE_ABOVE,
1244         XATOM__NET_WM_STATE_MAXIMIZED_VERT,
1245         XATOM__NET_WM_STATE_SKIP_PAGER,
1246         XATOM__NET_WM_STATE_SKIP_TASKBAR
1247     };
1248
1249     DWORD i, style, ex_style, new_state = 0;
1250
1251     if (!data->managed) return;
1252     if (data->whole_window == root_window) return;
1253
1254     style = GetWindowLongW( data->hwnd, GWL_STYLE );
1255     if (is_window_rect_fullscreen( &data->whole_rect ))
1256     {
1257         if ((style & WS_MAXIMIZE) && (style & WS_CAPTION) == WS_CAPTION)
1258             new_state |= (1 << NET_WM_STATE_MAXIMIZED);
1259         else if (!(style & WS_MINIMIZE))
1260             new_state |= (1 << NET_WM_STATE_FULLSCREEN);
1261     }
1262     else if (style & WS_MAXIMIZE)
1263         new_state |= (1 << NET_WM_STATE_MAXIMIZED);
1264
1265     ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
1266     if (ex_style & WS_EX_TOPMOST)
1267         new_state |= (1 << NET_WM_STATE_ABOVE);
1268     if (ex_style & (WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE))
1269         new_state |= (1 << NET_WM_STATE_SKIP_TASKBAR) | (1 << NET_WM_STATE_SKIP_PAGER);
1270     if (!(ex_style & WS_EX_APPWINDOW) && GetWindow( data->hwnd, GW_OWNER ))
1271         new_state |= (1 << NET_WM_STATE_SKIP_TASKBAR);
1272
1273     if (!data->mapped)  /* set the _NET_WM_STATE atom directly */
1274     {
1275         Atom atoms[NB_NET_WM_STATES+1];
1276         DWORD count;
1277
1278         for (i = count = 0; i < NB_NET_WM_STATES; i++)
1279         {
1280             if (!(new_state & (1 << i))) continue;
1281             TRACE( "setting wm state %u for unmapped window %p/%lx\n",
1282                    i, data->hwnd, data->whole_window );
1283             atoms[count++] = X11DRV_Atoms[state_atoms[i] - FIRST_XATOM];
1284             if (state_atoms[i] == XATOM__NET_WM_STATE_MAXIMIZED_VERT)
1285                 atoms[count++] = x11drv_atom(_NET_WM_STATE_MAXIMIZED_HORZ);
1286         }
1287         wine_tsx11_lock();
1288         XChangeProperty( display, data->whole_window, x11drv_atom(_NET_WM_STATE), XA_ATOM,
1289                          32, PropModeReplace, (unsigned char *)atoms, count );
1290         wine_tsx11_unlock();
1291     }
1292     else  /* ask the window manager to do it for us */
1293     {
1294         XEvent xev;
1295
1296         xev.xclient.type = ClientMessage;
1297         xev.xclient.window = data->whole_window;
1298         xev.xclient.message_type = x11drv_atom(_NET_WM_STATE);
1299         xev.xclient.serial = 0;
1300         xev.xclient.display = display;
1301         xev.xclient.send_event = True;
1302         xev.xclient.format = 32;
1303         xev.xclient.data.l[3] = 1;
1304
1305         for (i = 0; i < NB_NET_WM_STATES; i++)
1306         {
1307             if (!((data->net_wm_state ^ new_state) & (1 << i))) continue;  /* unchanged */
1308
1309             TRACE( "setting wm state %u for window %p/%lx to %u prev %u\n",
1310                    i, data->hwnd, data->whole_window,
1311                    (new_state & (1 << i)) != 0, (data->net_wm_state & (1 << i)) != 0 );
1312
1313             xev.xclient.data.l[0] = (new_state & (1 << i)) ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
1314             xev.xclient.data.l[1] = X11DRV_Atoms[state_atoms[i] - FIRST_XATOM];
1315             xev.xclient.data.l[2] = ((state_atoms[i] == XATOM__NET_WM_STATE_MAXIMIZED_VERT) ?
1316                                      x11drv_atom(_NET_WM_STATE_MAXIMIZED_HORZ) : 0);
1317             wine_tsx11_lock();
1318             XSendEvent( display, root_window, False,
1319                         SubstructureRedirectMask | SubstructureNotifyMask, &xev );
1320             wine_tsx11_unlock();
1321         }
1322     }
1323     data->net_wm_state = new_state;
1324 }
1325
1326
1327 /***********************************************************************
1328  *     set_xembed_flags
1329  */
1330 static void set_xembed_flags( Display *display, struct x11drv_win_data *data, unsigned long flags )
1331 {
1332     unsigned long info[2];
1333
1334     if (!data->whole_window) return;
1335
1336     info[0] = 0; /* protocol version */
1337     info[1] = flags;
1338     wine_tsx11_lock();
1339     XChangeProperty( display, data->whole_window, x11drv_atom(_XEMBED_INFO),
1340                      x11drv_atom(_XEMBED_INFO), 32, PropModeReplace, (unsigned char*)info, 2 );
1341     wine_tsx11_unlock();
1342 }
1343
1344
1345 /***********************************************************************
1346  *     map_window
1347  */
1348 static void map_window( Display *display, struct x11drv_win_data *data, DWORD new_style )
1349 {
1350     TRACE( "win %p/%lx\n", data->hwnd, data->whole_window );
1351
1352     remove_startup_notification( display, data->whole_window );
1353
1354     wait_for_withdrawn_state( display, data, TRUE );
1355
1356     if (!data->embedded)
1357     {
1358         update_net_wm_states( display, data );
1359         sync_window_style( display, data );
1360         wine_tsx11_lock();
1361         XMapWindow( display, data->whole_window );
1362         wine_tsx11_unlock();
1363     }
1364     else set_xembed_flags( display, data, XEMBED_MAPPED );
1365
1366     data->mapped = TRUE;
1367     data->iconic = (new_style & WS_MINIMIZE) != 0;
1368 }
1369
1370
1371 /***********************************************************************
1372  *     unmap_window
1373  */
1374 static void unmap_window( Display *display, struct x11drv_win_data *data )
1375 {
1376     TRACE( "win %p/%lx\n", data->hwnd, data->whole_window );
1377
1378     if (!data->embedded)
1379     {
1380         wait_for_withdrawn_state( display, data, FALSE );
1381         wine_tsx11_lock();
1382         if (data->managed) XWithdrawWindow( display, data->whole_window, DefaultScreen(display) );
1383         else XUnmapWindow( display, data->whole_window );
1384         wine_tsx11_unlock();
1385     }
1386     else set_xembed_flags( display, data, 0 );
1387
1388     data->mapped = FALSE;
1389     data->net_wm_state = 0;
1390 }
1391
1392
1393 /***********************************************************************
1394  *     make_window_embedded
1395  */
1396 void make_window_embedded( Display *display, struct x11drv_win_data *data )
1397 {
1398     BOOL was_mapped = data->mapped;
1399     /* the window cannot be mapped before being embedded */
1400     if (data->mapped) unmap_window( display, data );
1401
1402     data->embedded = TRUE;
1403     data->managed = TRUE;
1404     SetPropA( data->hwnd, managed_prop, (HANDLE)1 );
1405     sync_window_style( display, data );
1406
1407     if (was_mapped)
1408         map_window( display, data, 0 );
1409     else
1410         set_xembed_flags( display, data, 0 );
1411 }
1412
1413
1414 /***********************************************************************
1415  *              X11DRV_window_to_X_rect
1416  *
1417  * Convert a rect from client to X window coordinates
1418  */
1419 static void X11DRV_window_to_X_rect( struct x11drv_win_data *data, RECT *rect )
1420 {
1421     RECT rc;
1422
1423     if (!data->managed) return;
1424     if (IsRectEmpty( rect )) return;
1425
1426     get_x11_rect_offset( data, &rc );
1427
1428     rect->left   -= rc.left;
1429     rect->right  -= rc.right;
1430     rect->top    -= rc.top;
1431     rect->bottom -= rc.bottom;
1432     if (rect->top >= rect->bottom) rect->bottom = rect->top + 1;
1433     if (rect->left >= rect->right) rect->right = rect->left + 1;
1434 }
1435
1436
1437 /***********************************************************************
1438  *              X11DRV_X_to_window_rect
1439  *
1440  * Opposite of X11DRV_window_to_X_rect
1441  */
1442 void X11DRV_X_to_window_rect( struct x11drv_win_data *data, RECT *rect )
1443 {
1444     RECT rc;
1445
1446     if (!data->managed) return;
1447     if (IsRectEmpty( rect )) return;
1448
1449     get_x11_rect_offset( data, &rc );
1450
1451     rect->left   += rc.left;
1452     rect->right  += rc.right;
1453     rect->top    += rc.top;
1454     rect->bottom += rc.bottom;
1455     if (rect->top >= rect->bottom) rect->bottom = rect->top + 1;
1456     if (rect->left >= rect->right) rect->right = rect->left + 1;
1457 }
1458
1459
1460 /***********************************************************************
1461  *              sync_window_position
1462  *
1463  * Synchronize the X window position with the Windows one
1464  */
1465 static void sync_window_position( Display *display, struct x11drv_win_data *data,
1466                                   UINT swp_flags, const RECT *old_window_rect,
1467                                   const RECT *old_whole_rect, const RECT *old_client_rect )
1468 {
1469     DWORD style = GetWindowLongW( data->hwnd, GWL_STYLE );
1470     XWindowChanges changes;
1471     unsigned int mask = 0;
1472
1473     if (data->managed && data->iconic) return;
1474
1475     /* resizing a managed maximized window is not allowed */
1476     if (!(style & WS_MAXIMIZE) || !data->managed)
1477     {
1478         changes.width = data->whole_rect.right - data->whole_rect.left;
1479         changes.height = data->whole_rect.bottom - data->whole_rect.top;
1480         /* if window rect is empty force size to 1x1 */
1481         if (changes.width <= 0 || changes.height <= 0) changes.width = changes.height = 1;
1482         if (changes.width > 65535) changes.width = 65535;
1483         if (changes.height > 65535) changes.height = 65535;
1484         mask |= CWWidth | CWHeight;
1485     }
1486
1487     /* only the size is allowed to change for the desktop window */
1488     if (data->whole_window != root_window)
1489     {
1490         changes.x = data->whole_rect.left - virtual_screen_rect.left;
1491         changes.y = data->whole_rect.top - virtual_screen_rect.top;
1492         mask |= CWX | CWY;
1493     }
1494
1495     if (!(swp_flags & SWP_NOZORDER) || (swp_flags & SWP_SHOWWINDOW))
1496     {
1497         /* find window that this one must be after */
1498         HWND prev = GetWindow( data->hwnd, GW_HWNDPREV );
1499         while (prev && !(GetWindowLongW( prev, GWL_STYLE ) & WS_VISIBLE))
1500             prev = GetWindow( prev, GW_HWNDPREV );
1501         if (!prev)  /* top child */
1502         {
1503             changes.stack_mode = Above;
1504             mask |= CWStackMode;
1505         }
1506         /* should use stack_mode Below but most window managers don't get it right */
1507         /* and Above with a sibling doesn't work so well either, so we ignore it */
1508     }
1509
1510     wine_tsx11_lock();
1511     set_size_hints( display, data, style );
1512     data->configure_serial = NextRequest( display );
1513     XReconfigureWMWindow( display, data->whole_window,
1514                           DefaultScreen(display), mask, &changes );
1515 #ifdef HAVE_LIBXSHAPE
1516     if (IsRectEmpty( old_window_rect ) != IsRectEmpty( &data->window_rect ))
1517         sync_window_region( display, data, (HRGN)1 );
1518     if (data->shaped)
1519     {
1520         int old_x_offset = old_window_rect->left - old_whole_rect->left;
1521         int old_y_offset = old_window_rect->top - old_whole_rect->top;
1522         int new_x_offset = data->window_rect.left - data->whole_rect.left;
1523         int new_y_offset = data->window_rect.top - data->whole_rect.top;
1524         if (old_x_offset != new_x_offset || old_y_offset != new_y_offset)
1525             XShapeOffsetShape( display, data->whole_window, ShapeBounding,
1526                                new_x_offset - old_x_offset, new_y_offset - old_y_offset );
1527     }
1528 #endif
1529     wine_tsx11_unlock();
1530
1531     TRACE( "win %p/%lx pos %d,%d,%dx%d after %lx changes=%x serial=%lu\n",
1532            data->hwnd, data->whole_window, data->whole_rect.left, data->whole_rect.top,
1533            data->whole_rect.right - data->whole_rect.left,
1534            data->whole_rect.bottom - data->whole_rect.top,
1535            changes.sibling, mask, data->configure_serial );
1536 }
1537
1538
1539 /***********************************************************************
1540  *              sync_client_position
1541  *
1542  * Synchronize the X client window position with the Windows one
1543  */
1544 static void sync_client_position( Display *display, struct x11drv_win_data *data,
1545                                   UINT swp_flags, const RECT *old_client_rect,
1546                                   const RECT *old_whole_rect )
1547 {
1548     int mask;
1549     XWindowChanges changes;
1550     RECT old = *old_client_rect;
1551     RECT new = data->client_rect;
1552
1553     OffsetRect( &old, -old_whole_rect->left, -old_whole_rect->top );
1554     OffsetRect( &new, -data->whole_rect.left, -data->whole_rect.top );
1555     if (!(mask = get_window_changes( &changes, &old, &new ))) return;
1556
1557     if (data->client_window)
1558     {
1559         TRACE( "setting client win %lx pos %d,%d,%dx%d changes=%x\n",
1560                data->client_window, new.left, new.top,
1561                new.right - new.left, new.bottom - new.top, mask );
1562         wine_tsx11_lock();
1563         XConfigureWindow( display, data->client_window, mask, &changes );
1564         wine_tsx11_unlock();
1565     }
1566
1567     if (data->gl_drawable && (mask & (CWWidth|CWHeight))) sync_gl_drawable( data );
1568 }
1569
1570
1571 /***********************************************************************
1572  *              move_window_bits
1573  *
1574  * Move the window bits when a window is moved.
1575  */
1576 static void move_window_bits( struct x11drv_win_data *data, const RECT *old_rect, const RECT *new_rect,
1577                               const RECT *old_client_rect )
1578 {
1579     RECT src_rect = *old_rect;
1580     RECT dst_rect = *new_rect;
1581     HDC hdc_src, hdc_dst;
1582     INT code;
1583     HRGN rgn;
1584     HWND parent = 0;
1585
1586     if (!data->whole_window)
1587     {
1588         OffsetRect( &dst_rect, -data->window_rect.left, -data->window_rect.top );
1589         parent = GetAncestor( data->hwnd, GA_PARENT );
1590         hdc_src = GetDCEx( parent, 0, DCX_CACHE );
1591         hdc_dst = GetDCEx( data->hwnd, 0, DCX_CACHE | DCX_WINDOW );
1592     }
1593     else
1594     {
1595         OffsetRect( &dst_rect, -data->client_rect.left, -data->client_rect.top );
1596         /* make src rect relative to the old position of the window */
1597         OffsetRect( &src_rect, -old_client_rect->left, -old_client_rect->top );
1598         if (dst_rect.left == src_rect.left && dst_rect.top == src_rect.top) return;
1599         hdc_src = hdc_dst = GetDCEx( data->hwnd, 0, DCX_CACHE );
1600     }
1601
1602     rgn = CreateRectRgnIndirect( &dst_rect );
1603     SelectClipRgn( hdc_dst, rgn );
1604     DeleteObject( rgn );
1605     ExcludeUpdateRgn( hdc_dst, data->hwnd );
1606
1607     code = X11DRV_START_EXPOSURES;
1608     ExtEscape( hdc_dst, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
1609
1610     TRACE( "copying bits for win %p/%lx/%lx %s -> %s\n",
1611            data->hwnd, data->whole_window, data->client_window,
1612            wine_dbgstr_rect(&src_rect), wine_dbgstr_rect(&dst_rect) );
1613     BitBlt( hdc_dst, dst_rect.left, dst_rect.top,
1614             dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top,
1615             hdc_src, src_rect.left, src_rect.top, SRCCOPY );
1616
1617     rgn = 0;
1618     code = X11DRV_END_EXPOSURES;
1619     ExtEscape( hdc_dst, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, sizeof(rgn), (LPSTR)&rgn );
1620
1621     ReleaseDC( data->hwnd, hdc_dst );
1622     if (hdc_src != hdc_dst) ReleaseDC( parent, hdc_src );
1623
1624     if (rgn)
1625     {
1626         if (!data->whole_window)
1627         {
1628             /* map region to client rect since we are using DCX_WINDOW */
1629             OffsetRgn( rgn, data->window_rect.left - data->client_rect.left,
1630                        data->window_rect.top - data->client_rect.top );
1631             RedrawWindow( data->hwnd, NULL, rgn,
1632                           RDW_INVALIDATE | RDW_FRAME | RDW_ERASE | RDW_ALLCHILDREN );
1633         }
1634         else RedrawWindow( data->hwnd, NULL, rgn, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN );
1635         DeleteObject( rgn );
1636     }
1637 }
1638
1639
1640 /**********************************************************************
1641  *              create_whole_window
1642  *
1643  * Create the whole X window for a given window
1644  */
1645 static Window create_whole_window( Display *display, struct x11drv_win_data *data )
1646 {
1647     int cx, cy, mask;
1648     XSetWindowAttributes attr;
1649     WCHAR text[1024];
1650     COLORREF key;
1651     BYTE alpha;
1652     DWORD layered_flags;
1653     HRGN win_rgn;
1654
1655     if (!data->managed && is_window_managed( data->hwnd, SWP_NOACTIVATE, &data->window_rect ))
1656     {
1657         TRACE( "making win %p/%lx managed\n", data->hwnd, data->whole_window );
1658         data->managed = TRUE;
1659         SetPropA( data->hwnd, managed_prop, (HANDLE)1 );
1660     }
1661
1662     if ((win_rgn = CreateRectRgn( 0, 0, 0, 0 )) &&
1663         GetWindowRgn( data->hwnd, win_rgn ) == ERROR)
1664     {
1665         DeleteObject( win_rgn );
1666         win_rgn = 0;
1667     }
1668     data->shaped = (win_rgn != 0);
1669
1670     mask = get_window_attributes( display, data, &attr );
1671
1672     data->whole_rect = data->window_rect;
1673     X11DRV_window_to_X_rect( data, &data->whole_rect );
1674     if (!(cx = data->whole_rect.right - data->whole_rect.left)) cx = 1;
1675     else if (cx > 65535) cx = 65535;
1676     if (!(cy = data->whole_rect.bottom - data->whole_rect.top)) cy = 1;
1677     else if (cy > 65535) cy = 65535;
1678
1679     wine_tsx11_lock();
1680     data->whole_window = XCreateWindow( display, root_window,
1681                                         data->whole_rect.left - virtual_screen_rect.left,
1682                                         data->whole_rect.top - virtual_screen_rect.top,
1683                                         cx, cy, 0, screen_depth, InputOutput,
1684                                         visual, mask, &attr );
1685
1686     if (data->whole_window) XSaveContext( display, data->whole_window, winContext, (char *)data->hwnd );
1687     wine_tsx11_unlock();
1688
1689     if (!data->whole_window) goto done;
1690
1691     if (!create_client_window( display, data, NULL ))
1692     {
1693         wine_tsx11_lock();
1694         XDeleteContext( display, data->whole_window, winContext );
1695         XDestroyWindow( display, data->whole_window );
1696         data->whole_window = 0;
1697         wine_tsx11_unlock();
1698         goto done;
1699     }
1700
1701     set_initial_wm_hints( display, data );
1702     set_wm_hints( display, data );
1703
1704     SetPropA( data->hwnd, whole_window_prop, (HANDLE)data->whole_window );
1705
1706     /* set the window text */
1707     if (!InternalGetWindowText( data->hwnd, text, sizeof(text)/sizeof(WCHAR) )) text[0] = 0;
1708     sync_window_text( display, data->whole_window, text );
1709
1710     /* set the window region */
1711     if (win_rgn || IsRectEmpty( &data->window_rect )) sync_window_region( display, data, win_rgn );
1712
1713     /* set the window opacity */
1714     if (!GetLayeredWindowAttributes( data->hwnd, &key, &alpha, &layered_flags )) layered_flags = 0;
1715     sync_window_opacity( display, data->whole_window, key, alpha, layered_flags );
1716
1717     init_clip_window();  /* make sure the clip window is initialized in this thread */
1718
1719     wine_tsx11_lock();
1720     XFlush( display );  /* make sure the window exists before we start painting to it */
1721     wine_tsx11_unlock();
1722
1723     sync_window_cursor( data->whole_window );
1724
1725 done:
1726     if (win_rgn) DeleteObject( win_rgn );
1727     return data->whole_window;
1728 }
1729
1730
1731 /**********************************************************************
1732  *              destroy_whole_window
1733  *
1734  * Destroy the whole X window for a given window.
1735  */
1736 static void destroy_whole_window( Display *display, struct x11drv_win_data *data, BOOL already_destroyed )
1737 {
1738     if (!data->whole_window)
1739     {
1740         if (data->embedded)
1741         {
1742             Window xwin = (Window)GetPropA( data->hwnd, foreign_window_prop );
1743             if (xwin)
1744             {
1745                 wine_tsx11_lock();
1746                 if (!already_destroyed) XSelectInput( display, xwin, 0 );
1747                 XDeleteContext( display, xwin, winContext );
1748                 wine_tsx11_unlock();
1749                 RemovePropA( data->hwnd, foreign_window_prop );
1750             }
1751         }
1752         return;
1753     }
1754
1755
1756     TRACE( "win %p xwin %lx/%lx\n", data->hwnd, data->whole_window, data->client_window );
1757     wine_tsx11_lock();
1758     XDeleteContext( display, data->whole_window, winContext );
1759     XDeleteContext( display, data->client_window, winContext );
1760     if (!already_destroyed) XDestroyWindow( display, data->whole_window );
1761     data->whole_window = data->client_window = 0;
1762     data->wm_state = WithdrawnState;
1763     data->net_wm_state = 0;
1764     data->mapped = FALSE;
1765     if (data->xic)
1766     {
1767         XUnsetICFocus( data->xic );
1768         XDestroyIC( data->xic );
1769         data->xic = 0;
1770     }
1771     /* Outlook stops processing messages after destroying a dialog, so we need an explicit flush */
1772     XFlush( display );
1773     XFree( data->wm_hints );
1774     data->wm_hints = NULL;
1775     wine_tsx11_unlock();
1776     RemovePropA( data->hwnd, whole_window_prop );
1777     RemovePropA( data->hwnd, client_window_prop );
1778 }
1779
1780
1781 /*****************************************************************
1782  *              SetWindowText   (X11DRV.@)
1783  */
1784 void CDECL X11DRV_SetWindowText( HWND hwnd, LPCWSTR text )
1785 {
1786     Window win;
1787
1788     if ((win = X11DRV_get_whole_window( hwnd )) && win != DefaultRootWindow(gdi_display))
1789     {
1790         Display *display = thread_init_display();
1791         sync_window_text( display, win, text );
1792     }
1793 }
1794
1795
1796 /***********************************************************************
1797  *              SetWindowStyle   (X11DRV.@)
1798  *
1799  * Update the X state of a window to reflect a style change
1800  */
1801 void CDECL X11DRV_SetWindowStyle( HWND hwnd, INT offset, STYLESTRUCT *style )
1802 {
1803     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
1804     DWORD changed;
1805
1806     if (hwnd == GetDesktopWindow()) return;
1807     changed = style->styleNew ^ style->styleOld;
1808
1809     /* if WS_VISIBLE was set through WM_SETREDRAW, map the window if it's the first time */
1810     if (offset == GWL_STYLE && (changed & WS_VISIBLE) && (style->styleNew & WS_VISIBLE) && !data)
1811     {
1812         if (!(data = X11DRV_create_win_data( hwnd ))) return;
1813
1814         if (data->whole_window && is_window_rect_mapped( &data->window_rect ))
1815         {
1816             Display *display = thread_display();
1817             set_wm_hints( display, data );
1818             if (!data->mapped) map_window( display, data, style->styleNew );
1819         }
1820     }
1821     if (!data || !data->whole_window) return;
1822
1823     if (offset == GWL_STYLE && (changed & WS_DISABLED))
1824         set_wm_hints( thread_display(), data );
1825
1826     if (offset == GWL_EXSTYLE && (changed & WS_EX_LAYERED)) /* changing WS_EX_LAYERED resets attributes */
1827         sync_window_opacity( thread_display(), data->whole_window, 0, 0, 0 );
1828 }
1829
1830
1831 /***********************************************************************
1832  *              DestroyWindow   (X11DRV.@)
1833  */
1834 void CDECL X11DRV_DestroyWindow( HWND hwnd )
1835 {
1836     struct x11drv_thread_data *thread_data = x11drv_thread_data();
1837     struct x11drv_win_data *data;
1838
1839     if (!(data = X11DRV_get_win_data( hwnd ))) return;
1840
1841     if (data->pixmap)
1842     {
1843         wine_tsx11_lock();
1844         destroy_glxpixmap(gdi_display, data->gl_drawable);
1845         XFreePixmap(gdi_display, data->pixmap);
1846         wine_tsx11_unlock();
1847     }
1848     else if (data->gl_drawable)
1849     {
1850         wine_tsx11_lock();
1851         XDestroyWindow(gdi_display, data->gl_drawable);
1852         wine_tsx11_unlock();
1853     }
1854
1855     destroy_whole_window( thread_data->display, data, FALSE );
1856     destroy_icon_window( thread_data->display, data );
1857
1858     if (data->colormap)
1859     {
1860         wine_tsx11_lock();
1861         XFreeColormap( thread_data->display, data->colormap );
1862         wine_tsx11_unlock();
1863     }
1864
1865     if (thread_data->last_focus == hwnd) thread_data->last_focus = 0;
1866     if (thread_data->last_xic_hwnd == hwnd) thread_data->last_xic_hwnd = 0;
1867     if (data->hWMIconBitmap) DeleteObject( data->hWMIconBitmap );
1868     if (data->hWMIconMask) DeleteObject( data->hWMIconMask);
1869     wine_tsx11_lock();
1870     XDeleteContext( thread_data->display, (XID)hwnd, win_data_context );
1871     wine_tsx11_unlock();
1872     HeapFree( GetProcessHeap(), 0, data );
1873 }
1874
1875
1876 /***********************************************************************
1877  *              X11DRV_DestroyNotify
1878  */
1879 void X11DRV_DestroyNotify( HWND hwnd, XEvent *event )
1880 {
1881     Display *display = event->xdestroywindow.display;
1882     struct x11drv_win_data *data;
1883
1884     if (!(data = X11DRV_get_win_data( hwnd ))) return;
1885     if (!data->embedded) FIXME( "window %p/%lx destroyed from the outside\n", hwnd, data->whole_window );
1886
1887     destroy_whole_window( display, data, TRUE );
1888     if (data->embedded) SendMessageW( hwnd, WM_CLOSE, 0, 0 );
1889 }
1890
1891
1892 static struct x11drv_win_data *alloc_win_data( Display *display, HWND hwnd )
1893 {
1894     struct x11drv_win_data *data;
1895
1896     if ((data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data))))
1897     {
1898         data->hwnd = hwnd;
1899         wine_tsx11_lock();
1900         if (!winContext) winContext = XUniqueContext();
1901         if (!win_data_context) win_data_context = XUniqueContext();
1902         XSaveContext( display, (XID)hwnd, win_data_context, (char *)data );
1903         wine_tsx11_unlock();
1904     }
1905     return data;
1906 }
1907
1908
1909 /* initialize the desktop window id in the desktop manager process */
1910 static struct x11drv_win_data *create_desktop_win_data( Display *display, HWND hwnd )
1911 {
1912     struct x11drv_win_data *data;
1913
1914     if (!(data = alloc_win_data( display, hwnd ))) return NULL;
1915     data->whole_window = data->client_window = root_window;
1916     data->managed = TRUE;
1917     SetPropA( data->hwnd, managed_prop, (HANDLE)1 );
1918     SetPropA( data->hwnd, whole_window_prop, (HANDLE)root_window );
1919     SetPropA( data->hwnd, client_window_prop, (HANDLE)root_window );
1920     set_initial_wm_hints( display, data );
1921     return data;
1922 }
1923
1924 /**********************************************************************
1925  *              CreateDesktopWindow   (X11DRV.@)
1926  */
1927 BOOL CDECL X11DRV_CreateDesktopWindow( HWND hwnd )
1928 {
1929     unsigned int width, height;
1930
1931     /* retrieve the real size of the desktop */
1932     SERVER_START_REQ( get_window_rectangles )
1933     {
1934         req->handle = wine_server_user_handle( hwnd );
1935         req->relative = COORDS_CLIENT;
1936         wine_server_call( req );
1937         width  = reply->window.right;
1938         height = reply->window.bottom;
1939     }
1940     SERVER_END_REQ;
1941
1942     if (!width && !height)  /* not initialized yet */
1943     {
1944         SERVER_START_REQ( set_window_pos )
1945         {
1946             req->handle        = wine_server_user_handle( hwnd );
1947             req->previous      = 0;
1948             req->flags         = SWP_NOZORDER;
1949             req->window.left   = virtual_screen_rect.left;
1950             req->window.top    = virtual_screen_rect.top;
1951             req->window.right  = virtual_screen_rect.right;
1952             req->window.bottom = virtual_screen_rect.bottom;
1953             req->client        = req->window;
1954             wine_server_call( req );
1955         }
1956         SERVER_END_REQ;
1957     }
1958     else
1959     {
1960         Window win = (Window)GetPropA( hwnd, whole_window_prop );
1961         if (win && win != root_window) X11DRV_init_desktop( win, width, height );
1962     }
1963     return TRUE;
1964 }
1965
1966
1967 /**********************************************************************
1968  *              CreateWindow   (X11DRV.@)
1969  */
1970 BOOL CDECL X11DRV_CreateWindow( HWND hwnd )
1971 {
1972     if (hwnd == GetDesktopWindow())
1973     {
1974         struct x11drv_thread_data *data = x11drv_init_thread_data();
1975         XSetWindowAttributes attr;
1976
1977         if (root_window != DefaultRootWindow( gdi_display ))
1978         {
1979             /* the desktop win data can't be created lazily */
1980             if (!create_desktop_win_data( data->display, hwnd )) return FALSE;
1981         }
1982
1983         /* create the cursor clipping window */
1984         attr.override_redirect = TRUE;
1985         attr.event_mask = StructureNotifyMask | FocusChangeMask;
1986         wine_tsx11_lock();
1987         data->clip_window = XCreateWindow( data->display, root_window, 0, 0, 1, 1, 0, 0,
1988                                            InputOnly, visual, CWOverrideRedirect | CWEventMask, &attr );
1989         wine_tsx11_unlock();
1990         SetPropA( hwnd, clip_window_prop, (HANDLE)data->clip_window );
1991     }
1992     return TRUE;
1993 }
1994
1995
1996 /***********************************************************************
1997  *              X11DRV_get_win_data
1998  *
1999  * Return the X11 data structure associated with a window.
2000  */
2001 struct x11drv_win_data *X11DRV_get_win_data( HWND hwnd )
2002 {
2003     struct x11drv_thread_data *thread_data = x11drv_thread_data();
2004     char *data;
2005
2006     if (!thread_data) return NULL;
2007     if (!hwnd) return NULL;
2008     if (XFindContext( thread_data->display, (XID)hwnd, win_data_context, &data )) data = NULL;
2009     return (struct x11drv_win_data *)data;
2010 }
2011
2012
2013 /***********************************************************************
2014  *              X11DRV_create_win_data
2015  *
2016  * Create an X11 data window structure for an existing window.
2017  */
2018 struct x11drv_win_data *X11DRV_create_win_data( HWND hwnd )
2019 {
2020     Display *display;
2021     struct x11drv_win_data *data;
2022     HWND parent;
2023
2024     if (!(parent = GetAncestor( hwnd, GA_PARENT ))) return NULL;  /* desktop */
2025
2026     /* don't create win data for HWND_MESSAGE windows */
2027     if (parent != GetDesktopWindow() && !GetAncestor( parent, GA_PARENT )) return NULL;
2028
2029     display = thread_init_display();
2030     if (!(data = alloc_win_data( display, hwnd ))) return NULL;
2031
2032     GetWindowRect( hwnd, &data->window_rect );
2033     MapWindowPoints( 0, parent, (POINT *)&data->window_rect, 2 );
2034     data->whole_rect = data->window_rect;
2035     GetClientRect( hwnd, &data->client_rect );
2036     MapWindowPoints( hwnd, parent, (POINT *)&data->client_rect, 2 );
2037
2038     if (parent == GetDesktopWindow())
2039     {
2040         if (!create_whole_window( display, data ))
2041         {
2042             HeapFree( GetProcessHeap(), 0, data );
2043             return NULL;
2044         }
2045         TRACE( "win %p/%lx/%lx window %s whole %s client %s\n",
2046                hwnd, data->whole_window, data->client_window, wine_dbgstr_rect( &data->window_rect ),
2047                wine_dbgstr_rect( &data->whole_rect ), wine_dbgstr_rect( &data->client_rect ));
2048     }
2049     return data;
2050 }
2051
2052
2053 /* window procedure for foreign windows */
2054 static LRESULT WINAPI foreign_window_proc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2055 {
2056     switch(msg)
2057     {
2058     case WM_WINDOWPOSCHANGED:
2059         update_systray_balloon_position();
2060         break;
2061     case WM_PARENTNOTIFY:
2062         if (LOWORD(wparam) == WM_DESTROY)
2063         {
2064             TRACE( "%p: got parent notify destroy for win %lx\n", hwnd, lparam );
2065             PostMessageW( hwnd, WM_CLOSE, 0, 0 );  /* so that we come back here once the child is gone */
2066         }
2067         return 0;
2068     case WM_CLOSE:
2069         if (GetWindow( hwnd, GW_CHILD )) return 0;  /* refuse to die if we still have children */
2070         break;
2071     }
2072     return DefWindowProcW( hwnd, msg, wparam, lparam );
2073 }
2074
2075
2076 /***********************************************************************
2077  *              create_foreign_window
2078  *
2079  * Create a foreign window for the specified X window and its ancestors
2080  */
2081 HWND create_foreign_window( Display *display, Window xwin )
2082 {
2083     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};
2084     static BOOL class_registered;
2085     struct x11drv_win_data *data;
2086     HWND hwnd, parent;
2087     Window xparent, xroot;
2088     Window *xchildren;
2089     unsigned int nchildren;
2090     XWindowAttributes attr;
2091     DWORD style = WS_CLIPCHILDREN;
2092
2093     if (!class_registered)
2094     {
2095         WNDCLASSEXW class;
2096
2097         memset( &class, 0, sizeof(class) );
2098         class.cbSize        = sizeof(class);
2099         class.lpfnWndProc   = foreign_window_proc;
2100         class.lpszClassName = classW;
2101         if (!RegisterClassExW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS)
2102         {
2103             ERR( "Could not register foreign window class\n" );
2104             return FALSE;
2105         }
2106         class_registered = TRUE;
2107     }
2108
2109     wine_tsx11_lock();
2110     if (XFindContext( display, xwin, winContext, (char **)&hwnd )) hwnd = 0;
2111     if (hwnd)  /* already created */
2112     {
2113         wine_tsx11_unlock();
2114         return hwnd;
2115     }
2116
2117     XSelectInput( display, xwin, StructureNotifyMask );
2118     if (!XGetWindowAttributes( display, xwin, &attr ) ||
2119         !XQueryTree( display, xwin, &xroot, &xparent, &xchildren, &nchildren ))
2120     {
2121         XSelectInput( display, xwin, 0 );
2122         wine_tsx11_unlock();
2123         return 0;
2124     }
2125     XFree( xchildren );
2126     wine_tsx11_unlock();
2127
2128     if (xparent == xroot)
2129     {
2130         parent = GetDesktopWindow();
2131         style |= WS_POPUP;
2132         attr.x += virtual_screen_rect.left;
2133         attr.y += virtual_screen_rect.top;
2134     }
2135     else
2136     {
2137         parent = create_foreign_window( display, xparent );
2138         style |= WS_CHILD;
2139     }
2140
2141     hwnd = CreateWindowW( classW, NULL, style, attr.x, attr.y, attr.width, attr.height,
2142                           parent, 0, 0, NULL );
2143
2144     if (!(data = alloc_win_data( display, hwnd )))
2145     {
2146         DestroyWindow( hwnd );
2147         return 0;
2148     }
2149     SetRect( &data->window_rect, attr.x, attr.y, attr.x + attr.width, attr.y + attr.height );
2150     data->whole_rect = data->client_rect = data->window_rect;
2151     data->whole_window = data->client_window = 0;
2152     data->embedded = TRUE;
2153     data->mapped = TRUE;
2154
2155     SetPropA( hwnd, foreign_window_prop, (HANDLE)xwin );
2156     wine_tsx11_lock();
2157     XSaveContext( display, xwin, winContext, (char *)data->hwnd );
2158     wine_tsx11_unlock();
2159
2160     ShowWindow( hwnd, SW_SHOW );
2161
2162     TRACE( "win %lx parent %p style %08x %s -> hwnd %p\n",
2163            xwin, parent, style, wine_dbgstr_rect(&data->window_rect), hwnd );
2164
2165     return hwnd;
2166 }
2167
2168
2169 /***********************************************************************
2170  *              X11DRV_get_whole_window
2171  *
2172  * Return the X window associated with the full area of a window
2173  */
2174 Window X11DRV_get_whole_window( HWND hwnd )
2175 {
2176     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2177
2178     if (!data)
2179     {
2180         if (hwnd == GetDesktopWindow()) return root_window;
2181         return (Window)GetPropA( hwnd, whole_window_prop );
2182     }
2183     return data->whole_window;
2184 }
2185
2186
2187 /***********************************************************************
2188  *              X11DRV_get_client_window
2189  *
2190  * Return the X window associated with the client area of a window
2191  */
2192 static Window X11DRV_get_client_window( HWND hwnd )
2193 {
2194     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2195
2196     if (!data)
2197     {
2198         if (hwnd == GetDesktopWindow()) return root_window;
2199         return (Window)GetPropA( hwnd, client_window_prop );
2200     }
2201     return data->client_window;
2202 }
2203
2204
2205 /***********************************************************************
2206  *              X11DRV_get_ic
2207  *
2208  * Return the X input context associated with a window
2209  */
2210 XIC X11DRV_get_ic( HWND hwnd )
2211 {
2212     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2213     XIM xim;
2214
2215     if (!data) return 0;
2216
2217     x11drv_thread_data()->last_xic_hwnd = hwnd;
2218     if (data->xic) return data->xic;
2219     if (!(xim = x11drv_thread_data()->xim)) return 0;
2220     return X11DRV_CreateIC( xim, data );
2221 }
2222
2223
2224 /***********************************************************************
2225  *              X11DRV_GetDC   (X11DRV.@)
2226  */
2227 void CDECL X11DRV_GetDC( HDC hdc, HWND hwnd, HWND top, const RECT *win_rect,
2228                          const RECT *top_rect, DWORD flags )
2229 {
2230     struct x11drv_escape_set_drawable escape;
2231     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2232     HWND parent;
2233
2234     escape.code        = X11DRV_SET_DRAWABLE;
2235     escape.mode        = IncludeInferiors;
2236     escape.fbconfig_id = 0;
2237     escape.gl_drawable = 0;
2238     escape.pixmap      = 0;
2239     escape.gl_copy     = FALSE;
2240
2241     escape.dc_rect.left         = win_rect->left - top_rect->left;
2242     escape.dc_rect.top          = win_rect->top - top_rect->top;
2243     escape.dc_rect.right        = win_rect->right - top_rect->left;
2244     escape.dc_rect.bottom       = win_rect->bottom - top_rect->top;
2245     escape.drawable_rect.left   = top_rect->left;
2246     escape.drawable_rect.top    = top_rect->top;
2247     escape.drawable_rect.right  = top_rect->right;
2248     escape.drawable_rect.bottom = top_rect->bottom;
2249
2250     if (top == hwnd)
2251     {
2252         escape.fbconfig_id = data ? data->fbconfig_id : (XID)GetPropA( hwnd, fbconfig_id_prop );
2253         /* GL draws to the client area even for window DCs */
2254         escape.gl_drawable = data ? data->client_window : X11DRV_get_client_window( hwnd );
2255         if (data && IsIconic( hwnd ) && data->icon_window)
2256         {
2257             escape.drawable = data->icon_window;
2258         }
2259         else if (flags & DCX_WINDOW)
2260             escape.drawable = data ? data->whole_window : X11DRV_get_whole_window( hwnd );
2261         else
2262             escape.drawable = escape.gl_drawable;
2263
2264         /* special case: when repainting the root window, clip out top-level windows */
2265         if (data && data->whole_window == root_window) escape.mode = ClipByChildren;
2266     }
2267     else
2268     {
2269         /* find the first ancestor that has a drawable */
2270         for (parent = hwnd; parent && parent != top; parent = GetAncestor( parent, GA_PARENT ))
2271             if ((escape.drawable = X11DRV_get_client_window( parent ))) break;
2272
2273         if (escape.drawable)
2274         {
2275             POINT pt = { 0, 0 };
2276             MapWindowPoints( top, parent, &pt, 1 );
2277             OffsetRect( &escape.dc_rect, pt.x, pt.y );
2278             OffsetRect( &escape.drawable_rect, -pt.x, -pt.y );
2279         }
2280         else escape.drawable = X11DRV_get_client_window( top );
2281
2282         escape.fbconfig_id = data ? data->fbconfig_id : (XID)GetPropA( hwnd, fbconfig_id_prop );
2283         escape.gl_drawable = data ? data->gl_drawable : (Drawable)GetPropA( hwnd, gl_drawable_prop );
2284         escape.pixmap      = data ? data->pixmap : (Pixmap)GetPropA( hwnd, pixmap_prop );
2285         escape.gl_copy     = (escape.gl_drawable != 0);
2286         if (flags & DCX_CLIPCHILDREN) escape.mode = ClipByChildren;
2287     }
2288
2289     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
2290 }
2291
2292
2293 /***********************************************************************
2294  *              X11DRV_ReleaseDC  (X11DRV.@)
2295  */
2296 void CDECL X11DRV_ReleaseDC( HWND hwnd, HDC hdc )
2297 {
2298     struct x11drv_escape_set_drawable escape;
2299
2300     escape.code = X11DRV_SET_DRAWABLE;
2301     escape.drawable = root_window;
2302     escape.mode = IncludeInferiors;
2303     escape.drawable_rect = virtual_screen_rect;
2304     SetRect( &escape.dc_rect, 0, 0, virtual_screen_rect.right - virtual_screen_rect.left,
2305              virtual_screen_rect.bottom - virtual_screen_rect.top );
2306     OffsetRect( &escape.dc_rect, -escape.drawable_rect.left, -escape.drawable_rect.top );
2307     escape.fbconfig_id = 0;
2308     escape.gl_drawable = 0;
2309     escape.pixmap = 0;
2310     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
2311 }
2312
2313
2314 /***********************************************************************
2315  *              SetCapture  (X11DRV.@)
2316  */
2317 void CDECL X11DRV_SetCapture( HWND hwnd, UINT flags )
2318 {
2319     struct x11drv_thread_data *thread_data = x11drv_thread_data();
2320
2321     if (!thread_data) return;
2322     if (!(flags & (GUI_INMOVESIZE | GUI_INMENUMODE))) return;
2323
2324     if (hwnd)
2325     {
2326         Window grab_win = X11DRV_get_client_window( GetAncestor( hwnd, GA_ROOT ) );
2327
2328         if (!grab_win) return;
2329         wine_tsx11_lock();
2330         XFlush( gdi_display );
2331         XGrabPointer( thread_data->display, grab_win, False,
2332                       PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
2333                       GrabModeAsync, GrabModeAsync, None, None, CurrentTime );
2334         wine_tsx11_unlock();
2335         thread_data->grab_window = grab_win;
2336     }
2337     else  /* release capture */
2338     {
2339         wine_tsx11_lock();
2340         XFlush( gdi_display );
2341         XUngrabPointer( thread_data->display, CurrentTime );
2342         XFlush( thread_data->display );
2343         wine_tsx11_unlock();
2344         thread_data->grab_window = None;
2345     }
2346 }
2347
2348
2349 /*****************************************************************
2350  *              SetParent   (X11DRV.@)
2351  */
2352 void CDECL X11DRV_SetParent( HWND hwnd, HWND parent, HWND old_parent )
2353 {
2354     Display *display = thread_display();
2355     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2356
2357     if (!data) return;
2358     if (parent == old_parent) return;
2359     if (data->embedded) return;
2360
2361     if (parent != GetDesktopWindow()) /* a child window */
2362     {
2363         if (old_parent == GetDesktopWindow())
2364         {
2365             /* destroy the old X windows */
2366             destroy_whole_window( display, data, FALSE );
2367             destroy_icon_window( display, data );
2368             if (data->managed)
2369             {
2370                 data->managed = FALSE;
2371                 RemovePropA( data->hwnd, managed_prop );
2372             }
2373         }
2374     }
2375     else  /* new top level window */
2376     {
2377         /* FIXME: we ignore errors since we can't really recover anyway */
2378         create_whole_window( display, data );
2379     }
2380 }
2381
2382
2383 /*****************************************************************
2384  *              SetFocus   (X11DRV.@)
2385  *
2386  * Set the X focus.
2387  */
2388 void CDECL X11DRV_SetFocus( HWND hwnd )
2389 {
2390     Display *display = thread_display();
2391     struct x11drv_win_data *data;
2392     XWindowChanges changes;
2393     DWORD timestamp;
2394
2395     if (!(hwnd = GetAncestor( hwnd, GA_ROOT ))) return;
2396     if (!(data = X11DRV_get_win_data( hwnd ))) return;
2397     if (data->managed || !data->whole_window) return;
2398
2399     if (EVENT_x11_time_to_win32_time(0))
2400         /* ICCCM says don't use CurrentTime, so try to use last message time if possible */
2401         /* FIXME: this is not entirely correct */
2402         timestamp = GetMessageTime() - EVENT_x11_time_to_win32_time(0);
2403     else
2404         timestamp = CurrentTime;
2405
2406     /* Set X focus and install colormap */
2407     wine_tsx11_lock();
2408     changes.stack_mode = Above;
2409     XConfigureWindow( display, data->whole_window, CWStackMode, &changes );
2410     XSetInputFocus( display, data->whole_window, RevertToParent, timestamp );
2411     wine_tsx11_unlock();
2412 }
2413
2414
2415 /***********************************************************************
2416  *              WindowPosChanging   (X11DRV.@)
2417  */
2418 void CDECL X11DRV_WindowPosChanging( HWND hwnd, HWND insert_after, UINT swp_flags,
2419                                      const RECT *window_rect, const RECT *client_rect, RECT *visible_rect )
2420 {
2421     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2422     DWORD style = GetWindowLongW( hwnd, GWL_STYLE );
2423
2424     if (!data)
2425     {
2426         /* create the win data if the window is being made visible */
2427         if (!(style & WS_VISIBLE) && !(swp_flags & SWP_SHOWWINDOW)) return;
2428         if (!(data = X11DRV_create_win_data( hwnd ))) return;
2429     }
2430
2431     /* check if we need to switch the window to managed */
2432     if (!data->managed && data->whole_window && is_window_managed( hwnd, swp_flags, window_rect ))
2433     {
2434         TRACE( "making win %p/%lx managed\n", hwnd, data->whole_window );
2435         if (data->mapped) unmap_window( thread_display(), data );
2436         data->managed = TRUE;
2437         SetPropA( hwnd, managed_prop, (HANDLE)1 );
2438     }
2439
2440     *visible_rect = *window_rect;
2441     X11DRV_window_to_X_rect( data, visible_rect );
2442 }
2443
2444
2445 /***********************************************************************
2446  *              WindowPosChanged   (X11DRV.@)
2447  */
2448 void CDECL X11DRV_WindowPosChanged( HWND hwnd, HWND insert_after, UINT swp_flags,
2449                                     const RECT *rectWindow, const RECT *rectClient,
2450                                     const RECT *visible_rect, const RECT *valid_rects )
2451 {
2452     struct x11drv_thread_data *thread_data;
2453     Display *display;
2454     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2455     DWORD new_style = GetWindowLongW( hwnd, GWL_STYLE );
2456     RECT old_window_rect, old_whole_rect, old_client_rect;
2457     int event_type;
2458
2459     if (!data) return;
2460
2461     thread_data = x11drv_thread_data();
2462     display = thread_data->display;
2463
2464     old_window_rect = data->window_rect;
2465     old_whole_rect  = data->whole_rect;
2466     old_client_rect = data->client_rect;
2467     data->window_rect = *rectWindow;
2468     data->whole_rect  = *visible_rect;
2469     data->client_rect = *rectClient;
2470
2471     TRACE( "win %p window %s client %s style %08x flags %08x\n",
2472            hwnd, wine_dbgstr_rect(rectWindow), wine_dbgstr_rect(rectClient), new_style, swp_flags );
2473
2474     if (!IsRectEmpty( &valid_rects[0] ))
2475     {
2476         int x_offset = old_whole_rect.left - data->whole_rect.left;
2477         int y_offset = old_whole_rect.top - data->whole_rect.top;
2478
2479         /* if all that happened is that the whole window moved, copy everything */
2480         if (!(swp_flags & SWP_FRAMECHANGED) &&
2481             old_whole_rect.right   - data->whole_rect.right   == x_offset &&
2482             old_whole_rect.bottom  - data->whole_rect.bottom  == y_offset &&
2483             old_client_rect.left   - data->client_rect.left   == x_offset &&
2484             old_client_rect.right  - data->client_rect.right  == x_offset &&
2485             old_client_rect.top    - data->client_rect.top    == y_offset &&
2486             old_client_rect.bottom - data->client_rect.bottom == y_offset &&
2487             !memcmp( &valid_rects[0], &data->client_rect, sizeof(RECT) ))
2488         {
2489             /* if we have an X window the bits will be moved by the X server */
2490             if (!data->whole_window && (x_offset != 0 || y_offset != 0))
2491                 move_window_bits( data, &old_whole_rect, &data->whole_rect, &old_client_rect );
2492         }
2493         else
2494             move_window_bits( data, &valid_rects[1], &valid_rects[0], &old_client_rect );
2495     }
2496
2497     wine_tsx11_lock();
2498     XFlush( gdi_display );  /* make sure painting is done before we move the window */
2499     wine_tsx11_unlock();
2500
2501     sync_client_position( display, data, swp_flags, &old_client_rect, &old_whole_rect );
2502
2503     if (!data->whole_window) return;
2504
2505     /* check if we are currently processing an event relevant to this window */
2506     event_type = 0;
2507     if (thread_data->current_event && thread_data->current_event->xany.window == data->whole_window)
2508         event_type = thread_data->current_event->type;
2509
2510     if (event_type != ConfigureNotify && event_type != PropertyNotify &&
2511         event_type != GravityNotify && event_type != ReparentNotify)
2512         event_type = 0;  /* ignore other events */
2513
2514     if (data->mapped && event_type != ReparentNotify)
2515     {
2516         if (((swp_flags & SWP_HIDEWINDOW) && !(new_style & WS_VISIBLE)) ||
2517             (!event_type &&
2518              !is_window_rect_mapped( rectWindow ) && is_window_rect_mapped( &old_window_rect )))
2519             unmap_window( display, data );
2520     }
2521
2522     /* don't change position if we are about to minimize or maximize a managed window */
2523     if (!event_type &&
2524         !(data->managed && (swp_flags & SWP_STATECHANGED) && (new_style & (WS_MINIMIZE|WS_MAXIMIZE))))
2525         sync_window_position( display, data, swp_flags,
2526                               &old_window_rect, &old_whole_rect, &old_client_rect );
2527
2528     if ((new_style & WS_VISIBLE) &&
2529         ((new_style & WS_MINIMIZE) || is_window_rect_mapped( rectWindow )))
2530     {
2531         if (!data->mapped || (swp_flags & (SWP_FRAMECHANGED|SWP_STATECHANGED)))
2532             set_wm_hints( display, data );
2533
2534         if (!data->mapped)
2535         {
2536             map_window( display, data, new_style );
2537         }
2538         else if ((swp_flags & SWP_STATECHANGED) && (!data->iconic != !(new_style & WS_MINIMIZE)))
2539         {
2540             data->iconic = (new_style & WS_MINIMIZE) != 0;
2541             TRACE( "changing win %p iconic state to %u\n", data->hwnd, data->iconic );
2542             wine_tsx11_lock();
2543             if (data->iconic)
2544                 XIconifyWindow( display, data->whole_window, DefaultScreen(display) );
2545             else if (is_window_rect_mapped( rectWindow ))
2546                 XMapWindow( display, data->whole_window );
2547             wine_tsx11_unlock();
2548             update_net_wm_states( display, data );
2549         }
2550         else if (!event_type)
2551         {
2552             update_net_wm_states( display, data );
2553         }
2554     }
2555
2556     wine_tsx11_lock();
2557     XFlush( display );  /* make sure changes are done before we start painting again */
2558     wine_tsx11_unlock();
2559 }
2560
2561
2562 /***********************************************************************
2563  *           ShowWindow   (X11DRV.@)
2564  */
2565 UINT CDECL X11DRV_ShowWindow( HWND hwnd, INT cmd, RECT *rect, UINT swp )
2566 {
2567     int x, y;
2568     unsigned int width, height, border, depth;
2569     Window root, top;
2570     DWORD style = GetWindowLongW( hwnd, GWL_STYLE );
2571     struct x11drv_thread_data *thread_data = x11drv_thread_data();
2572     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2573
2574     if (!data || !data->whole_window || !data->managed || !data->mapped || data->iconic) return swp;
2575     if (style & WS_MINIMIZE) return swp;
2576     if (IsRectEmpty( rect )) return swp;
2577
2578     /* only fetch the new rectangle if the ShowWindow was a result of a window manager event */
2579
2580     if (!thread_data->current_event || thread_data->current_event->xany.window != data->whole_window)
2581         return swp;
2582
2583     if (thread_data->current_event->type != ConfigureNotify &&
2584         thread_data->current_event->type != PropertyNotify)
2585         return swp;
2586
2587     TRACE( "win %p/%lx cmd %d at %s flags %08x\n",
2588            hwnd, data->whole_window, cmd, wine_dbgstr_rect(rect), swp );
2589
2590     wine_tsx11_lock();
2591     XGetGeometry( thread_data->display, data->whole_window,
2592                   &root, &x, &y, &width, &height, &border, &depth );
2593     XTranslateCoordinates( thread_data->display, data->whole_window, root, 0, 0, &x, &y, &top );
2594     wine_tsx11_unlock();
2595     rect->left   = x;
2596     rect->top    = y;
2597     rect->right  = x + width;
2598     rect->bottom = y + height;
2599     OffsetRect( rect, virtual_screen_rect.left, virtual_screen_rect.top );
2600     X11DRV_X_to_window_rect( data, rect );
2601     return swp & ~(SWP_NOMOVE | SWP_NOCLIENTMOVE | SWP_NOSIZE | SWP_NOCLIENTSIZE);
2602 }
2603
2604
2605 /**********************************************************************
2606  *              SetWindowIcon (X11DRV.@)
2607  *
2608  * hIcon or hIconSm has changed (or is being initialised for the
2609  * first time). Complete the X11 driver-specific initialisation
2610  * and set the window hints.
2611  *
2612  * This is not entirely correct, may need to create
2613  * an icon window and set the pixmap as a background
2614  */
2615 void CDECL X11DRV_SetWindowIcon( HWND hwnd, UINT type, HICON icon )
2616 {
2617     Display *display = thread_display();
2618     struct x11drv_win_data *data;
2619
2620
2621     if (!(data = X11DRV_get_win_data( hwnd ))) return;
2622     if (!data->whole_window) return;
2623     if (!data->managed) return;
2624
2625     if (data->wm_hints)
2626     {
2627         if (type == ICON_BIG) set_icon_hints( display, data, icon, 0 );
2628         else set_icon_hints( display, data, 0, icon );
2629         wine_tsx11_lock();
2630         XSetWMHints( display, data->whole_window, data->wm_hints );
2631         wine_tsx11_unlock();
2632     }
2633 }
2634
2635
2636 /***********************************************************************
2637  *              SetWindowRgn  (X11DRV.@)
2638  *
2639  * Assign specified region to window (for non-rectangular windows)
2640  */
2641 int CDECL X11DRV_SetWindowRgn( HWND hwnd, HRGN hrgn, BOOL redraw )
2642 {
2643     struct x11drv_win_data *data;
2644
2645     if ((data = X11DRV_get_win_data( hwnd )))
2646     {
2647         sync_window_region( thread_display(), data, hrgn );
2648     }
2649     else if (X11DRV_get_whole_window( hwnd ))
2650     {
2651         SendMessageW( hwnd, WM_X11DRV_SET_WIN_REGION, 0, 0 );
2652     }
2653     return TRUE;
2654 }
2655
2656
2657 /***********************************************************************
2658  *              SetLayeredWindowAttributes  (X11DRV.@)
2659  *
2660  * Set transparency attributes for a layered window.
2661  */
2662 void CDECL X11DRV_SetLayeredWindowAttributes( HWND hwnd, COLORREF key, BYTE alpha, DWORD flags )
2663 {
2664     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
2665
2666     if (data)
2667     {
2668         if (data->whole_window)
2669             sync_window_opacity( thread_display(), data->whole_window, key, alpha, flags );
2670     }
2671     else
2672     {
2673         Window win = X11DRV_get_whole_window( hwnd );
2674         if (win) sync_window_opacity( gdi_display, win, key, alpha, flags );
2675     }
2676 }
2677
2678
2679 /**********************************************************************
2680  *           X11DRV_WindowMessage   (X11DRV.@)
2681  */
2682 LRESULT CDECL X11DRV_WindowMessage( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
2683 {
2684     struct x11drv_win_data *data;
2685
2686     switch(msg)
2687     {
2688     case WM_X11DRV_ACQUIRE_SELECTION:
2689         return X11DRV_AcquireClipboard( hwnd );
2690     case WM_X11DRV_SET_WIN_FORMAT:
2691         return set_win_format( hwnd, (XID)wp );
2692     case WM_X11DRV_SET_WIN_REGION:
2693         if ((data = X11DRV_get_win_data( hwnd ))) sync_window_region( thread_display(), data, (HRGN)1 );
2694         return 0;
2695     case WM_X11DRV_RESIZE_DESKTOP:
2696         X11DRV_resize_desktop( LOWORD(lp), HIWORD(lp) );
2697         return 0;
2698     case WM_X11DRV_SET_CURSOR:
2699         if ((data = X11DRV_get_win_data( hwnd )) && data->whole_window)
2700             set_window_cursor( data->whole_window, (HCURSOR)lp );
2701         return 0;
2702     case WM_X11DRV_CLIP_CURSOR:
2703         return clip_cursor_notify( hwnd, (HWND)lp );
2704     default:
2705         FIXME( "got window msg %x hwnd %p wp %lx lp %lx\n", msg, hwnd, wp, lp );
2706         return 0;
2707     }
2708 }
2709
2710
2711 /***********************************************************************
2712  *              is_netwm_supported
2713  */
2714 static BOOL is_netwm_supported( Display *display, Atom atom )
2715 {
2716     static Atom *net_supported;
2717     static int net_supported_count = -1;
2718     int i;
2719
2720     wine_tsx11_lock();
2721     if (net_supported_count == -1)
2722     {
2723         Atom type;
2724         int format;
2725         unsigned long count, remaining;
2726
2727         if (!XGetWindowProperty( display, DefaultRootWindow(display), x11drv_atom(_NET_SUPPORTED), 0,
2728                                  ~0UL, False, XA_ATOM, &type, &format, &count,
2729                                  &remaining, (unsigned char **)&net_supported ))
2730             net_supported_count = get_property_size( format, count ) / sizeof(Atom);
2731         else
2732             net_supported_count = 0;
2733     }
2734     wine_tsx11_unlock();
2735
2736     for (i = 0; i < net_supported_count; i++)
2737         if (net_supported[i] == atom) return TRUE;
2738     return FALSE;
2739 }
2740
2741
2742 /***********************************************************************
2743  *           SysCommand   (X11DRV.@)
2744  *
2745  * Perform WM_SYSCOMMAND handling.
2746  */
2747 LRESULT CDECL X11DRV_SysCommand( HWND hwnd, WPARAM wparam, LPARAM lparam )
2748 {
2749     WPARAM hittest = wparam & 0x0f;
2750     DWORD dwPoint;
2751     int x, y, dir;
2752     XEvent xev;
2753     Display *display = thread_display();
2754     struct x11drv_win_data *data;
2755
2756     if (!(data = X11DRV_get_win_data( hwnd ))) return -1;
2757     if (!data->whole_window || !data->managed || !data->mapped) return -1;
2758
2759     switch (wparam & 0xfff0)
2760     {
2761     case SC_MOVE:
2762         if (!hittest) dir = _NET_WM_MOVERESIZE_MOVE_KEYBOARD;
2763         else dir = _NET_WM_MOVERESIZE_MOVE;
2764         break;
2765     case SC_SIZE:
2766         /* windows without WS_THICKFRAME are not resizable through the window manager */
2767         if (!(GetWindowLongW( hwnd, GWL_STYLE ) & WS_THICKFRAME)) return -1;
2768
2769         switch (hittest)
2770         {
2771         case WMSZ_LEFT:        dir = _NET_WM_MOVERESIZE_SIZE_LEFT; break;
2772         case WMSZ_RIGHT:       dir = _NET_WM_MOVERESIZE_SIZE_RIGHT; break;
2773         case WMSZ_TOP:         dir = _NET_WM_MOVERESIZE_SIZE_TOP; break;
2774         case WMSZ_TOPLEFT:     dir = _NET_WM_MOVERESIZE_SIZE_TOPLEFT; break;
2775         case WMSZ_TOPRIGHT:    dir = _NET_WM_MOVERESIZE_SIZE_TOPRIGHT; break;
2776         case WMSZ_BOTTOM:      dir = _NET_WM_MOVERESIZE_SIZE_BOTTOM; break;
2777         case WMSZ_BOTTOMLEFT:  dir = _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT; break;
2778         case WMSZ_BOTTOMRIGHT: dir = _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT; break;
2779         default:               dir = _NET_WM_MOVERESIZE_SIZE_KEYBOARD; break;
2780         }
2781         break;
2782
2783     case SC_KEYMENU:
2784         /* prevent a simple ALT press+release from activating the system menu,
2785          * as that can get confusing on managed windows */
2786         if ((WCHAR)lparam) return -1;  /* got an explicit char */
2787         if (GetMenu( hwnd )) return -1;  /* window has a real menu */
2788         if (!(GetWindowLongW( hwnd, GWL_STYLE ) & WS_SYSMENU)) return -1;  /* no system menu */
2789         TRACE( "ignoring SC_KEYMENU wp %lx lp %lx\n", wparam, lparam );
2790         return 0;
2791
2792     default:
2793         return -1;
2794     }
2795
2796     if (IsZoomed(hwnd)) return -1;
2797
2798     if (!is_netwm_supported( display, x11drv_atom(_NET_WM_MOVERESIZE) ))
2799     {
2800         TRACE( "_NET_WM_MOVERESIZE not supported\n" );
2801         return -1;
2802     }
2803
2804     dwPoint = GetMessagePos();
2805     x = (short)LOWORD(dwPoint);
2806     y = (short)HIWORD(dwPoint);
2807
2808     TRACE("hwnd %p, x %d, y %d, dir %d\n", hwnd, x, y, dir);
2809
2810     xev.xclient.type = ClientMessage;
2811     xev.xclient.window = X11DRV_get_whole_window(hwnd);
2812     xev.xclient.message_type = x11drv_atom(_NET_WM_MOVERESIZE);
2813     xev.xclient.serial = 0;
2814     xev.xclient.display = display;
2815     xev.xclient.send_event = True;
2816     xev.xclient.format = 32;
2817     xev.xclient.data.l[0] = x - virtual_screen_rect.left; /* x coord */
2818     xev.xclient.data.l[1] = y - virtual_screen_rect.top;  /* y coord */
2819     xev.xclient.data.l[2] = dir; /* direction */
2820     xev.xclient.data.l[3] = 1; /* button */
2821     xev.xclient.data.l[4] = 0; /* unused */
2822
2823     /* need to ungrab the pointer that may have been automatically grabbed
2824      * with a ButtonPress event */
2825     wine_tsx11_lock();
2826     XUngrabPointer( display, CurrentTime );
2827     XSendEvent(display, root_window, False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
2828     wine_tsx11_unlock();
2829     return 0;
2830 }