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