winex11: Avoid erasing the window when changing the pixel format.
[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 static const char whole_window_prop[] = "__wine_x11_whole_window";
78 static const char client_window_prop[]= "__wine_x11_client_window";
79 static const char icon_window_prop[]  = "__wine_x11_icon_window";
80 static const char fbconfig_id_prop[]  = "__wine_x11_fbconfig_id";
81 static const char gl_drawable_prop[]  = "__wine_x11_gl_drawable";
82 static const char pixmap_prop[]       = "__wine_x11_pixmap";
83 static const char managed_prop[]      = "__wine_x11_managed";
84
85 /***********************************************************************
86  *              is_window_managed
87  *
88  * Check if a given window should be managed
89  */
90 static BOOL is_window_managed( HWND hwnd, UINT swp_flags, const RECT *window_rect )
91 {
92     DWORD style, ex_style;
93
94     if (!managed_mode) return FALSE;
95
96     /* child windows are not managed */
97     style = GetWindowLongW( hwnd, GWL_STYLE );
98     if ((style & (WS_CHILD|WS_POPUP)) == WS_CHILD) return FALSE;
99     /* activated windows are managed */
100     if (!(swp_flags & (SWP_NOACTIVATE|SWP_HIDEWINDOW))) return TRUE;
101     if (hwnd == GetActiveWindow()) return TRUE;
102     /* windows with caption are managed */
103     if ((style & WS_CAPTION) == WS_CAPTION) return TRUE;
104     /* windows with thick frame are managed */
105     if (style & WS_THICKFRAME) return TRUE;
106     if (style & WS_POPUP)
107     {
108         /* popup with sysmenu == caption are managed */
109         if (style & WS_SYSMENU) return TRUE;
110         /* full-screen popup windows are managed */
111         if (window_rect->left <= 0 && window_rect->right >= screen_width &&
112             window_rect->top <= 0 && window_rect->bottom >= screen_height)
113             return TRUE;
114     }
115     /* application windows are managed */
116     ex_style = GetWindowLongW( hwnd, GWL_EXSTYLE );
117     if (ex_style & WS_EX_APPWINDOW) return TRUE;
118     /* default: not managed */
119     return FALSE;
120 }
121
122
123 /***********************************************************************
124  *              X11DRV_is_window_rect_mapped
125  *
126  * Check if the X whole window should be mapped based on its rectangle
127  */
128 static BOOL is_window_rect_mapped( const RECT *rect )
129 {
130     /* don't map if rect is empty */
131     if (IsRectEmpty( rect )) return FALSE;
132
133     /* don't map if rect is off-screen */
134     if (rect->left >= virtual_screen_rect.right ||
135         rect->top >= virtual_screen_rect.bottom ||
136         rect->right <= virtual_screen_rect.left ||
137         rect->bottom <= virtual_screen_rect.top)
138         return FALSE;
139
140     return TRUE;
141 }
142
143
144 /***********************************************************************
145  *              is_window_resizable
146  *
147  * Check if window should be made resizable by the window manager
148  */
149 static inline BOOL is_window_resizable( struct x11drv_win_data *data, DWORD style )
150 {
151     if (style & WS_THICKFRAME) return TRUE;
152     /* Metacity needs the window to be resizable to make it fullscreen */
153     return (data->whole_rect.left <= 0 && data->whole_rect.right >= screen_width &&
154             data->whole_rect.top <= 0 && data->whole_rect.bottom >= screen_height);
155 }
156
157
158 /***********************************************************************
159  *              get_window_owner
160  */
161 static HWND get_window_owner( HWND hwnd )
162 {
163     RECT rect;
164     HWND owner = GetWindow( hwnd, GW_OWNER );
165     /* ignore the zero-size owners used by Delphi apps */
166     if (owner && GetWindowRect( owner, &rect ) && IsRectEmpty( &rect )) owner = 0;
167     return owner;
168 }
169
170
171 /***********************************************************************
172  *              get_mwm_decorations
173  */
174 static unsigned long get_mwm_decorations( struct x11drv_win_data *data,
175                                           DWORD style, DWORD ex_style )
176 {
177     unsigned long ret = 0;
178
179     if (!decorated_mode) return 0;
180
181     if (IsRectEmpty( &data->window_rect )) return 0;
182     if (data->shaped) return 0;
183
184     if (ex_style & WS_EX_TOOLWINDOW) return 0;
185
186     if ((style & WS_CAPTION) == WS_CAPTION)
187     {
188         ret |= MWM_DECOR_TITLE | MWM_DECOR_BORDER;
189         if (style & WS_SYSMENU) ret |= MWM_DECOR_MENU;
190         if (style & WS_MINIMIZEBOX) ret |= MWM_DECOR_MINIMIZE;
191         if (style & WS_MAXIMIZEBOX) ret |= MWM_DECOR_MAXIMIZE;
192     }
193     if (ex_style & WS_EX_DLGMODALFRAME) ret |= MWM_DECOR_BORDER;
194     else if (style & WS_THICKFRAME) ret |= MWM_DECOR_BORDER | MWM_DECOR_RESIZEH;
195     else if ((style & (WS_DLGFRAME|WS_BORDER)) == WS_DLGFRAME) ret |= MWM_DECOR_BORDER;
196     return ret;
197 }
198
199
200 /***********************************************************************
201  *              get_x11_rect_offset
202  *
203  * Helper for X11DRV_window_to_X_rect and X11DRV_X_to_window_rect.
204  */
205 static void get_x11_rect_offset( struct x11drv_win_data *data, RECT *rect )
206 {
207     DWORD style, ex_style, style_mask = 0, ex_style_mask = 0;
208     unsigned long decor;
209
210     rect->top = rect->bottom = rect->left = rect->right = 0;
211
212     style = GetWindowLongW( data->hwnd, GWL_STYLE );
213     ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
214     decor = get_mwm_decorations( data, style, ex_style );
215
216     if (decor & MWM_DECOR_TITLE) style_mask |= WS_CAPTION;
217     if (decor & MWM_DECOR_BORDER)
218     {
219         style_mask |= WS_DLGFRAME | WS_THICKFRAME;
220         ex_style_mask |= WS_EX_DLGMODALFRAME;
221     }
222
223     AdjustWindowRectEx( rect, style & style_mask, FALSE, ex_style & ex_style_mask );
224 }
225
226
227 /***********************************************************************
228  *              get_window_attributes
229  *
230  * Fill the window attributes structure for an X window.
231  */
232 static int get_window_attributes( Display *display, struct x11drv_win_data *data,
233                                   XSetWindowAttributes *attr )
234 {
235     attr->override_redirect = !data->managed;
236     attr->colormap          = X11DRV_PALETTE_PaletteXColormap;
237     attr->save_under        = ((GetClassLongW( data->hwnd, GCL_STYLE ) & CS_SAVEBITS) != 0);
238     attr->cursor            = x11drv_thread_data()->cursor;
239     attr->bit_gravity       = NorthWestGravity;
240     attr->win_gravity       = StaticGravity;
241     attr->backing_store     = NotUseful;
242     attr->event_mask        = (ExposureMask | PointerMotionMask |
243                                ButtonPressMask | ButtonReleaseMask | EnterWindowMask |
244                                KeyPressMask | KeyReleaseMask | FocusChangeMask | KeymapStateMask);
245     if (data->managed) attr->event_mask |= StructureNotifyMask | PropertyChangeMask;
246
247     return (CWOverrideRedirect | CWSaveUnder | CWColormap | CWCursor |
248             CWEventMask | CWBitGravity | CWBackingStore);
249 }
250
251
252 /***********************************************************************
253  *              create_client_window
254  */
255 static Window create_client_window( Display *display, struct x11drv_win_data *data, XVisualInfo *vis )
256 {
257     int cx, cy, mask;
258     XSetWindowAttributes attr;
259     Window client;
260     Visual *client_visual = vis ? vis->visual : visual;
261
262     attr.bit_gravity = NorthWestGravity;
263     attr.win_gravity = NorthWestGravity;
264     attr.backing_store = NotUseful;
265     attr.event_mask = (ExposureMask | PointerMotionMask |
266                        ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
267     mask = CWEventMask | CWBitGravity | CWWinGravity | CWBackingStore;
268
269     if ((cx = data->client_rect.right - data->client_rect.left) <= 0) cx = 1;
270     if ((cy = data->client_rect.bottom - data->client_rect.top) <= 0) cy = 1;
271
272     wine_tsx11_lock();
273
274     if (vis)
275     {
276         attr.colormap = XCreateColormap( display, root_window, vis->visual,
277                                          (vis->class == PseudoColor || vis->class == GrayScale ||
278                                           vis->class == DirectColor) ? AllocAll : AllocNone );
279         mask |= CWColormap;
280     }
281
282     client = XCreateWindow( display, data->whole_window,
283                             data->client_rect.left - data->whole_rect.left,
284                             data->client_rect.top - data->whole_rect.top,
285                             cx, cy, 0, screen_depth, InputOutput,
286                             client_visual, mask, &attr );
287     if (!client)
288     {
289         wine_tsx11_unlock();
290         return 0;
291     }
292
293     if (data->client_window)
294     {
295         struct x11drv_thread_data *thread_data = x11drv_thread_data();
296         if (thread_data->cursor_window == data->client_window) thread_data->cursor_window = None;
297         XDeleteContext( display, data->client_window, winContext );
298         XDestroyWindow( display, data->client_window );
299     }
300     data->client_window = client;
301     data->visualid = XVisualIDFromVisual( client_visual );
302
303     if (data->colormap) XFreeColormap( display, data->colormap );
304     data->colormap = vis ? attr.colormap : 0;
305
306     XMapWindow( display, data->client_window );
307     XSaveContext( display, data->client_window, winContext, (char *)data->hwnd );
308     wine_tsx11_unlock();
309
310     SetPropA( data->hwnd, client_window_prop, (HANDLE)data->client_window );
311     return data->client_window;
312 }
313
314
315 /***********************************************************************
316  *              sync_window_style
317  *
318  * Change the X window attributes when the window style has changed.
319  */
320 static void sync_window_style( Display *display, struct x11drv_win_data *data )
321 {
322     if (data->whole_window != root_window)
323     {
324         XSetWindowAttributes attr;
325         int mask = get_window_attributes( display, data, &attr );
326
327         wine_tsx11_lock();
328         XChangeWindowAttributes( display, data->whole_window, mask, &attr );
329         wine_tsx11_unlock();
330     }
331 }
332
333
334 /***********************************************************************
335  *              sync_window_region
336  *
337  * Update the X11 window region.
338  */
339 static void sync_window_region( Display *display, struct x11drv_win_data *data, HRGN hrgn )
340 {
341 #ifdef HAVE_LIBXSHAPE
342     if (!data->whole_window) return;
343     data->shaped = FALSE;
344
345     if (!hrgn)
346     {
347         wine_tsx11_lock();
348         XShapeCombineMask( display, data->whole_window, ShapeBounding, 0, 0, None, ShapeSet );
349         wine_tsx11_unlock();
350     }
351     else
352     {
353         RGNDATA *pRegionData = X11DRV_GetRegionData( hrgn, 0 );
354         if (pRegionData)
355         {
356             wine_tsx11_lock();
357             XShapeCombineRectangles( display, data->whole_window, ShapeBounding,
358                                      data->window_rect.left - data->whole_rect.left,
359                                      data->window_rect.top - data->whole_rect.top,
360                                      (XRectangle *)pRegionData->Buffer,
361                                      pRegionData->rdh.nCount, ShapeSet, YXBanded );
362             wine_tsx11_unlock();
363             HeapFree(GetProcessHeap(), 0, pRegionData);
364             data->shaped = TRUE;
365         }
366     }
367 #endif  /* HAVE_LIBXSHAPE */
368 }
369
370
371 /***********************************************************************
372  *              sync_window_text
373  */
374 static void sync_window_text( Display *display, Window win, const WCHAR *text )
375 {
376     UINT count;
377     char *buffer, *utf8_buffer;
378     XTextProperty prop;
379
380     /* allocate new buffer for window text */
381     count = WideCharToMultiByte(CP_UNIXCP, 0, text, -1, NULL, 0, NULL, NULL);
382     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, count ))) return;
383     WideCharToMultiByte(CP_UNIXCP, 0, text, -1, buffer, count, NULL, NULL);
384
385     count = WideCharToMultiByte(CP_UTF8, 0, text, strlenW(text), NULL, 0, NULL, NULL);
386     if (!(utf8_buffer = HeapAlloc( GetProcessHeap(), 0, count )))
387     {
388         HeapFree( GetProcessHeap(), 0, buffer );
389         return;
390     }
391     WideCharToMultiByte(CP_UTF8, 0, text, strlenW(text), utf8_buffer, count, NULL, NULL);
392
393     wine_tsx11_lock();
394     if (XmbTextListToTextProperty( display, &buffer, 1, XStdICCTextStyle, &prop ) == Success)
395     {
396         XSetWMName( display, win, &prop );
397         XSetWMIconName( display, win, &prop );
398         XFree( prop.value );
399     }
400     /*
401       Implements a NET_WM UTF-8 title. It should be without a trailing \0,
402       according to the standard
403       ( http://www.pps.jussieu.fr/~jch/software/UTF8_STRING/UTF8_STRING.text ).
404     */
405     XChangeProperty( display, win, x11drv_atom(_NET_WM_NAME), x11drv_atom(UTF8_STRING),
406                      8, PropModeReplace, (unsigned char *) utf8_buffer, count);
407     wine_tsx11_unlock();
408
409     HeapFree( GetProcessHeap(), 0, utf8_buffer );
410     HeapFree( GetProcessHeap(), 0, buffer );
411 }
412
413
414 /***********************************************************************
415  *              X11DRV_set_win_format
416  */
417 BOOL X11DRV_set_win_format( HWND hwnd, XID fbconfig_id )
418 {
419     struct x11drv_win_data *data;
420     XVisualInfo *vis;
421     int w, h;
422
423     if (!(data = X11DRV_get_win_data(hwnd)) &&
424         !(data = X11DRV_create_win_data(hwnd))) return FALSE;
425
426     if (!(vis = visual_from_fbconfig_id(fbconfig_id))) return FALSE;
427
428     if (data->whole_window)
429     {
430         Display *display = thread_display();
431         Window client = data->client_window;
432
433         if (vis->visualid != data->visualid)
434         {
435             client = create_client_window( display, data, vis );
436             TRACE( "re-created client window %lx for %p fbconfig %lx\n", client, data->hwnd, fbconfig_id );
437         }
438         wine_tsx11_lock();
439         XFree(vis);
440         XFlush( display );
441         wine_tsx11_unlock();
442         if (client) goto done;
443         return FALSE;
444     }
445
446     w = data->client_rect.right - data->client_rect.left;
447     h = data->client_rect.bottom - data->client_rect.top;
448
449     if(w <= 0) w = 1;
450     if(h <= 0) h = 1;
451
452 #ifdef SONAME_LIBXCOMPOSITE
453     if(usexcomposite)
454     {
455         XSetWindowAttributes attrib;
456         static Window dummy_parent;
457
458         wine_tsx11_lock();
459         attrib.override_redirect = True;
460         if (!dummy_parent)
461         {
462             dummy_parent = XCreateWindow( gdi_display, root_window, -1, -1, 1, 1, 0, screen_depth,
463                                          InputOutput, visual, CWOverrideRedirect, &attrib );
464             XMapWindow( gdi_display, dummy_parent );
465         }
466         data->colormap = XCreateColormap(gdi_display, dummy_parent, vis->visual,
467                                          (vis->class == PseudoColor ||
468                                           vis->class == GrayScale ||
469                                           vis->class == DirectColor) ?
470                                          AllocAll : AllocNone);
471         attrib.colormap = data->colormap;
472         XInstallColormap(gdi_display, attrib.colormap);
473
474         if(data->gl_drawable) XDestroyWindow(gdi_display, data->gl_drawable);
475         data->gl_drawable = XCreateWindow(gdi_display, dummy_parent, -w, 0, w, h, 0,
476                                           vis->depth, InputOutput, vis->visual,
477                                           CWColormap | CWOverrideRedirect,
478                                           &attrib);
479         if(data->gl_drawable)
480         {
481             pXCompositeRedirectWindow(gdi_display, data->gl_drawable,
482                                       CompositeRedirectManual);
483             XMapWindow(gdi_display, data->gl_drawable);
484         }
485         XFree(vis);
486         XFlush( gdi_display );
487         wine_tsx11_unlock();
488     }
489     else
490 #endif
491     {
492         WARN("XComposite is not available, using GLXPixmap hack\n");
493
494         wine_tsx11_lock();
495
496         if(data->pixmap) XFreePixmap(gdi_display, data->pixmap);
497         data->pixmap = XCreatePixmap(gdi_display, root_window, w, h, vis->depth);
498         if(!data->pixmap)
499         {
500             XFree(vis);
501             wine_tsx11_unlock();
502             return FALSE;
503         }
504
505         if(data->gl_drawable) destroy_glxpixmap(gdi_display, data->gl_drawable);
506         data->gl_drawable = create_glxpixmap(gdi_display, vis, data->pixmap);
507         if(!data->gl_drawable)
508         {
509             XFreePixmap(gdi_display, data->pixmap);
510             data->pixmap = 0;
511         }
512         XFree(vis);
513         XFlush( gdi_display );
514         wine_tsx11_unlock();
515         if (data->pixmap) SetPropA(hwnd, pixmap_prop, (HANDLE)data->pixmap);
516     }
517
518     if (!data->gl_drawable) return FALSE;
519
520     TRACE("Created GL drawable 0x%lx, using FBConfigID 0x%lx\n",
521           data->gl_drawable, fbconfig_id);
522     SetPropA(hwnd, gl_drawable_prop, (HANDLE)data->gl_drawable);
523
524 done:
525     data->fbconfig_id = fbconfig_id;
526     SetPropA(hwnd, fbconfig_id_prop, (HANDLE)data->fbconfig_id);
527     /* force DCE invalidation */
528     SetWindowPos( hwnd, 0, 0, 0, 0, 0,
529                   SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE |
530                   SWP_NOREDRAW | SWP_DEFERERASE | SWP_NOSENDCHANGING | SWP_STATECHANGED);
531     return TRUE;
532 }
533
534 /***********************************************************************
535  *              sync_gl_drawable
536  */
537 static void sync_gl_drawable(struct x11drv_win_data *data)
538 {
539     int w = data->client_rect.right - data->client_rect.left;
540     int h = data->client_rect.bottom - data->client_rect.top;
541     XVisualInfo *vis;
542     Drawable glxp;
543     Pixmap pix;
544
545     if (w <= 0) w = 1;
546     if (h <= 0) h = 1;
547
548     TRACE("Resizing GL drawable 0x%lx to %dx%d\n", data->gl_drawable, w, h);
549 #ifdef SONAME_LIBXCOMPOSITE
550     if(usexcomposite)
551     {
552         wine_tsx11_lock();
553         XMoveResizeWindow(gdi_display, data->gl_drawable, -w, 0, w, h);
554         wine_tsx11_unlock();
555         return;
556     }
557 #endif
558
559     if (!(vis = visual_from_fbconfig_id(data->fbconfig_id))) return;
560
561     wine_tsx11_lock();
562     pix = XCreatePixmap(gdi_display, root_window, w, h, vis->depth);
563     if(!pix)
564     {
565         ERR("Failed to create pixmap for offscreen rendering\n");
566         XFree(vis);
567         wine_tsx11_unlock();
568         return;
569     }
570
571     glxp = create_glxpixmap(gdi_display, vis, pix);
572     if(!glxp)
573     {
574         ERR("Failed to create drawable for offscreen rendering\n");
575         XFreePixmap(gdi_display, pix);
576         XFree(vis);
577         wine_tsx11_unlock();
578         return;
579     }
580
581     XFree(vis);
582
583     mark_drawable_dirty(data->gl_drawable, glxp);
584
585     XFreePixmap(gdi_display, data->pixmap);
586     destroy_glxpixmap(gdi_display, data->gl_drawable);
587     TRACE( "Recreated GL drawable %lx to replace %lx\n", glxp, data->gl_drawable );
588
589     data->pixmap = pix;
590     data->gl_drawable = glxp;
591
592     XFlush( gdi_display );
593     wine_tsx11_unlock();
594
595     SetPropA(data->hwnd, gl_drawable_prop, (HANDLE)data->gl_drawable);
596     SetPropA(data->hwnd, pixmap_prop, (HANDLE)data->pixmap);
597 }
598
599
600 /***********************************************************************
601  *              get_window_changes
602  *
603  * fill the window changes structure
604  */
605 static int get_window_changes( XWindowChanges *changes, const RECT *old, const RECT *new )
606 {
607     int mask = 0;
608
609     if (old->right - old->left != new->right - new->left )
610     {
611         if ((changes->width = new->right - new->left) <= 0) changes->width = 1;
612         mask |= CWWidth;
613     }
614     if (old->bottom - old->top != new->bottom - new->top)
615     {
616         if ((changes->height = new->bottom - new->top) <= 0) changes->height = 1;
617         mask |= CWHeight;
618     }
619     if (old->left != new->left)
620     {
621         changes->x = new->left;
622         mask |= CWX;
623     }
624     if (old->top != new->top)
625     {
626         changes->y = new->top;
627         mask |= CWY;
628     }
629     return mask;
630 }
631
632
633 /***********************************************************************
634  *              create_icon_window
635  */
636 static Window create_icon_window( Display *display, struct x11drv_win_data *data )
637 {
638     XSetWindowAttributes attr;
639
640     attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
641                        ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
642     attr.bit_gravity = NorthWestGravity;
643     attr.backing_store = NotUseful/*WhenMapped*/;
644     attr.colormap      = X11DRV_PALETTE_PaletteXColormap; /* Needed due to our visual */
645
646     wine_tsx11_lock();
647     data->icon_window = XCreateWindow( display, root_window, 0, 0,
648                                        GetSystemMetrics( SM_CXICON ),
649                                        GetSystemMetrics( SM_CYICON ),
650                                        0, screen_depth,
651                                        InputOutput, visual,
652                                        CWEventMask | CWBitGravity | CWBackingStore | CWColormap, &attr );
653     XSaveContext( display, data->icon_window, winContext, (char *)data->hwnd );
654     XFlush( display );  /* make sure the window exists before we start painting to it */
655     wine_tsx11_unlock();
656
657     TRACE( "created %lx\n", data->icon_window );
658     SetPropA( data->hwnd, icon_window_prop, (HANDLE)data->icon_window );
659     return data->icon_window;
660 }
661
662
663
664 /***********************************************************************
665  *              destroy_icon_window
666  */
667 static void destroy_icon_window( Display *display, struct x11drv_win_data *data )
668 {
669     if (!data->icon_window) return;
670     if (x11drv_thread_data()->cursor_window == data->icon_window)
671         x11drv_thread_data()->cursor_window = None;
672     wine_tsx11_lock();
673     XDeleteContext( display, data->icon_window, winContext );
674     XDestroyWindow( display, data->icon_window );
675     data->icon_window = 0;
676     wine_tsx11_unlock();
677     RemovePropA( data->hwnd, icon_window_prop );
678 }
679
680
681 /***********************************************************************
682  *              set_icon_hints
683  *
684  * Set the icon wm hints
685  */
686 static void set_icon_hints( Display *display, struct x11drv_win_data *data, HICON hIcon )
687 {
688     XWMHints *hints = data->wm_hints;
689
690     if (data->hWMIconBitmap) DeleteObject( data->hWMIconBitmap );
691     if (data->hWMIconMask) DeleteObject( data->hWMIconMask);
692     data->hWMIconBitmap = 0;
693     data->hWMIconMask = 0;
694
695     if (!hIcon)
696     {
697         if (!data->icon_window) create_icon_window( display, data );
698         hints->icon_window = data->icon_window;
699         hints->flags = (hints->flags & ~(IconPixmapHint | IconMaskHint)) | IconWindowHint;
700     }
701     else
702     {
703         HBITMAP hbmOrig;
704         RECT rcMask;
705         BITMAP bmMask;
706         ICONINFO ii;
707         HDC hDC;
708
709         GetIconInfo(hIcon, &ii);
710
711         GetObjectA(ii.hbmMask, sizeof(bmMask), &bmMask);
712         rcMask.top    = 0;
713         rcMask.left   = 0;
714         rcMask.right  = bmMask.bmWidth;
715         rcMask.bottom = bmMask.bmHeight;
716
717         hDC = CreateCompatibleDC(0);
718         hbmOrig = SelectObject(hDC, ii.hbmMask);
719         InvertRect(hDC, &rcMask);
720         SelectObject(hDC, ii.hbmColor);  /* force the color bitmap to x11drv mode too */
721         SelectObject(hDC, hbmOrig);
722         DeleteDC(hDC);
723
724         data->hWMIconBitmap = ii.hbmColor;
725         data->hWMIconMask = ii.hbmMask;
726
727         hints->icon_pixmap = X11DRV_get_pixmap(data->hWMIconBitmap);
728         hints->icon_mask = X11DRV_get_pixmap(data->hWMIconMask);
729         destroy_icon_window( display, data );
730         hints->flags = (hints->flags & ~IconWindowHint) | IconPixmapHint | IconMaskHint;
731     }
732 }
733
734
735 /***********************************************************************
736  *              set_size_hints
737  *
738  * set the window size hints
739  */
740 static void set_size_hints( Display *display, struct x11drv_win_data *data, DWORD style )
741 {
742     XSizeHints* size_hints;
743
744     if (!(size_hints = XAllocSizeHints())) return;
745
746     size_hints->win_gravity = StaticGravity;
747     size_hints->flags |= PWinGravity;
748
749     /* don't update size hints if window is not in normal state */
750     if (!(style & (WS_MINIMIZE | WS_MAXIMIZE)))
751     {
752         if (data->hwnd != GetDesktopWindow())  /* don't force position of desktop */
753         {
754             size_hints->x = data->whole_rect.left;
755             size_hints->y = data->whole_rect.top;
756             size_hints->flags |= PPosition;
757         }
758
759         if (!is_window_resizable( data, style ))
760         {
761             size_hints->max_width = data->whole_rect.right - data->whole_rect.left;
762             size_hints->max_height = data->whole_rect.bottom - data->whole_rect.top;
763             size_hints->min_width = size_hints->max_width;
764             size_hints->min_height = size_hints->max_height;
765             size_hints->flags |= PMinSize | PMaxSize;
766         }
767     }
768     XSetWMNormalHints( display, data->whole_window, size_hints );
769     XFree( size_hints );
770 }
771
772
773 /***********************************************************************
774  *              get_process_name
775  *
776  * get the name of the current process for setting class hints
777  */
778 static char *get_process_name(void)
779 {
780     static char *name;
781
782     if (!name)
783     {
784         WCHAR module[MAX_PATH];
785         DWORD len = GetModuleFileNameW( 0, module, MAX_PATH );
786         if (len && len < MAX_PATH)
787         {
788             char *ptr;
789             WCHAR *p, *appname = module;
790
791             if ((p = strrchrW( appname, '/' ))) appname = p + 1;
792             if ((p = strrchrW( appname, '\\' ))) appname = p + 1;
793             len = WideCharToMultiByte( CP_UNIXCP, 0, appname, -1, NULL, 0, NULL, NULL );
794             if ((ptr = HeapAlloc( GetProcessHeap(), 0, len )))
795             {
796                 WideCharToMultiByte( CP_UNIXCP, 0, appname, -1, ptr, len, NULL, NULL );
797                 name = ptr;
798             }
799         }
800     }
801     return name;
802 }
803
804
805 /***********************************************************************
806  *              set_initial_wm_hints
807  *
808  * Set the window manager hints that don't change over the lifetime of a window.
809  */
810 static void set_initial_wm_hints( Display *display, struct x11drv_win_data *data )
811 {
812     long i;
813     Atom protocols[3];
814     Atom dndVersion = 4;
815     XClassHint *class_hints;
816     char *process_name = get_process_name();
817
818     wine_tsx11_lock();
819
820     /* wm protocols */
821     i = 0;
822     protocols[i++] = x11drv_atom(WM_DELETE_WINDOW);
823     protocols[i++] = x11drv_atom(_NET_WM_PING);
824     if (use_take_focus) protocols[i++] = x11drv_atom(WM_TAKE_FOCUS);
825     XChangeProperty( display, data->whole_window, x11drv_atom(WM_PROTOCOLS),
826                      XA_ATOM, 32, PropModeReplace, (unsigned char *)protocols, i );
827
828     /* class hints */
829     if ((class_hints = XAllocClassHint()))
830     {
831         static char wine[] = "Wine";
832
833         class_hints->res_name = process_name;
834         class_hints->res_class = wine;
835         XSetClassHint( display, data->whole_window, class_hints );
836         XFree( class_hints );
837     }
838
839     /* set the WM_CLIENT_MACHINE and WM_LOCALE_NAME properties */
840     XSetWMProperties(display, data->whole_window, NULL, NULL, NULL, 0, NULL, NULL, NULL);
841     /* set the pid. together, these properties are needed so the window manager can kill us if we freeze */
842     i = getpid();
843     XChangeProperty(display, data->whole_window, x11drv_atom(_NET_WM_PID),
844                     XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&i, 1);
845
846     XChangeProperty( display, data->whole_window, x11drv_atom(XdndAware),
847                      XA_ATOM, 32, PropModeReplace, (unsigned char*)&dndVersion, 1 );
848
849     data->wm_hints = XAllocWMHints();
850     wine_tsx11_unlock();
851
852     if (data->wm_hints)
853     {
854         HICON icon = (HICON)SendMessageW( data->hwnd, WM_GETICON, ICON_BIG, 0 );
855         if (!icon) icon = (HICON)GetClassLongPtrW( data->hwnd, GCLP_HICON );
856         data->wm_hints->flags = 0;
857         set_icon_hints( display, data, icon );
858     }
859 }
860
861
862 /***********************************************************************
863  *              set_wm_hints
864  *
865  * Set the window manager hints for a newly-created window
866  */
867 static void set_wm_hints( Display *display, struct x11drv_win_data *data )
868 {
869     Window group_leader;
870     Atom window_type;
871     MwmHints mwm_hints;
872     DWORD style, ex_style;
873     HWND owner;
874
875     if (data->hwnd == GetDesktopWindow())
876     {
877         /* force some styles for the desktop to get the correct decorations */
878         style = WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
879         ex_style = WS_EX_APPWINDOW;
880         owner = 0;
881     }
882     else
883     {
884         style = GetWindowLongW( data->hwnd, GWL_STYLE );
885         ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
886         owner = get_window_owner( data->hwnd );
887     }
888
889     /* transient for hint */
890     if (owner)
891     {
892         Window owner_win = X11DRV_get_whole_window( owner );
893         wine_tsx11_lock();
894         XSetTransientForHint( display, data->whole_window, owner_win );
895         wine_tsx11_unlock();
896         group_leader = owner_win;
897     }
898     else group_leader = data->whole_window;
899
900     wine_tsx11_lock();
901
902     /* size hints */
903     set_size_hints( display, data, style );
904
905     /* set the WM_WINDOW_TYPE */
906     if (style & WS_THICKFRAME) window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_NORMAL);
907     else if (ex_style & WS_EX_APPWINDOW) window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_NORMAL);
908     else if (style & WS_DLGFRAME) window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_DIALOG);
909     else if (ex_style & WS_EX_DLGMODALFRAME) window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_DIALOG);
910     else if ((style & WS_POPUP) && owner) window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_DIALOG);
911 #if 0  /* many window managers don't handle utility windows very well */
912     else if (ex_style & WS_EX_TOOLWINDOW) window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_UTILITY);
913 #endif
914     else window_type = x11drv_atom(_NET_WM_WINDOW_TYPE_NORMAL);
915
916     XChangeProperty(display, data->whole_window, x11drv_atom(_NET_WM_WINDOW_TYPE),
917                     XA_ATOM, 32, PropModeReplace, (unsigned char*)&window_type, 1);
918
919     mwm_hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
920     mwm_hints.decorations = get_mwm_decorations( data, style, ex_style );
921     mwm_hints.functions = MWM_FUNC_MOVE;
922     if (is_window_resizable( data, style )) mwm_hints.functions |= MWM_FUNC_RESIZE;
923     if (style & WS_MINIMIZEBOX) mwm_hints.functions |= MWM_FUNC_MINIMIZE;
924     if (style & WS_MAXIMIZEBOX) mwm_hints.functions |= MWM_FUNC_MAXIMIZE;
925     if (style & WS_SYSMENU)     mwm_hints.functions |= MWM_FUNC_CLOSE;
926
927     XChangeProperty( display, data->whole_window, x11drv_atom(_MOTIF_WM_HINTS),
928                      x11drv_atom(_MOTIF_WM_HINTS), 32, PropModeReplace,
929                      (unsigned char*)&mwm_hints, sizeof(mwm_hints)/sizeof(long) );
930
931     /* wm hints */
932     if (data->wm_hints)
933     {
934         data->wm_hints->flags |= InputHint | StateHint | WindowGroupHint;
935         data->wm_hints->input = !(style & WS_DISABLED);
936         data->wm_hints->initial_state = (style & WS_MINIMIZE) ? IconicState : NormalState;
937         data->wm_hints->window_group = group_leader;
938         XSetWMHints( display, data->whole_window, data->wm_hints );
939     }
940
941     wine_tsx11_unlock();
942 }
943
944
945 /***********************************************************************
946  *     update_net_wm_states
947  */
948 void update_net_wm_states( Display *display, struct x11drv_win_data *data )
949 {
950     static const unsigned int state_atoms[NB_NET_WM_STATES] =
951     {
952         XATOM__NET_WM_STATE_FULLSCREEN,
953         XATOM__NET_WM_STATE_ABOVE,
954         XATOM__NET_WM_STATE_MAXIMIZED_VERT,
955         XATOM__NET_WM_STATE_SKIP_PAGER,
956         XATOM__NET_WM_STATE_SKIP_TASKBAR
957     };
958
959     DWORD i, style, ex_style, new_state = 0;
960
961     if (!data->managed) return;
962     if (data->whole_window == root_window) return;
963
964     style = GetWindowLongW( data->hwnd, GWL_STYLE );
965     if (data->whole_rect.left <= 0 && data->whole_rect.right >= screen_width &&
966         data->whole_rect.top <= 0 && data->whole_rect.bottom >= screen_height)
967     {
968         if ((style & WS_MAXIMIZE) && (style & WS_CAPTION) == WS_CAPTION)
969             new_state |= (1 << NET_WM_STATE_MAXIMIZED);
970         else if (!(style & WS_MINIMIZE))
971             new_state |= (1 << NET_WM_STATE_FULLSCREEN);
972     }
973     else if (style & WS_MAXIMIZE)
974         new_state |= (1 << NET_WM_STATE_MAXIMIZED);
975
976     ex_style = GetWindowLongW( data->hwnd, GWL_EXSTYLE );
977     if (ex_style & WS_EX_TOPMOST)
978         new_state |= (1 << NET_WM_STATE_ABOVE);
979     if (ex_style & WS_EX_TOOLWINDOW)
980         new_state |= (1 << NET_WM_STATE_SKIP_TASKBAR) | (1 << NET_WM_STATE_SKIP_PAGER);
981     if (!(ex_style & WS_EX_APPWINDOW) && get_window_owner( data->hwnd ))
982         new_state |= (1 << NET_WM_STATE_SKIP_TASKBAR);
983
984     if (!data->mapped)  /* set the _NET_WM_STATE atom directly */
985     {
986         Atom atoms[NB_NET_WM_STATES+1];
987         DWORD count;
988
989         for (i = count = 0; i < NB_NET_WM_STATES; i++)
990         {
991             if (!(new_state & (1 << i))) continue;
992             TRACE( "setting wm state %u for unmapped window %p/%lx\n",
993                    i, data->hwnd, data->whole_window );
994             atoms[count++] = X11DRV_Atoms[state_atoms[i] - FIRST_XATOM];
995             if (state_atoms[i] == XATOM__NET_WM_STATE_MAXIMIZED_VERT)
996                 atoms[count++] = x11drv_atom(_NET_WM_STATE_MAXIMIZED_HORZ);
997         }
998         wine_tsx11_lock();
999         XChangeProperty( display, data->whole_window, x11drv_atom(_NET_WM_STATE), XA_ATOM,
1000                          32, PropModeReplace, (unsigned char *)atoms, count );
1001         wine_tsx11_unlock();
1002     }
1003     else  /* ask the window manager to do it for us */
1004     {
1005         XEvent xev;
1006
1007         xev.xclient.type = ClientMessage;
1008         xev.xclient.window = data->whole_window;
1009         xev.xclient.message_type = x11drv_atom(_NET_WM_STATE);
1010         xev.xclient.serial = 0;
1011         xev.xclient.display = display;
1012         xev.xclient.send_event = True;
1013         xev.xclient.format = 32;
1014         xev.xclient.data.l[3] = 1;
1015
1016         for (i = 0; i < NB_NET_WM_STATES; i++)
1017         {
1018             if (!((data->net_wm_state ^ new_state) & (1 << i))) continue;  /* unchanged */
1019
1020             TRACE( "setting wm state %u for window %p/%lx to %u prev %u\n",
1021                    i, data->hwnd, data->whole_window,
1022                    (new_state & (1 << i)) != 0, (data->net_wm_state & (1 << i)) != 0 );
1023
1024             xev.xclient.data.l[0] = (new_state & (1 << i)) ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
1025             xev.xclient.data.l[1] = X11DRV_Atoms[state_atoms[i] - FIRST_XATOM];
1026             xev.xclient.data.l[2] = ((state_atoms[i] == XATOM__NET_WM_STATE_MAXIMIZED_VERT) ?
1027                                      x11drv_atom(_NET_WM_STATE_MAXIMIZED_HORZ) : 0);
1028             wine_tsx11_lock();
1029             XSendEvent( display, root_window, False,
1030                         SubstructureRedirectMask | SubstructureNotifyMask, &xev );
1031             wine_tsx11_unlock();
1032         }
1033     }
1034     data->net_wm_state = new_state;
1035 }
1036
1037
1038 /***********************************************************************
1039  *     set_xembed_flags
1040  */
1041 static void set_xembed_flags( Display *display, struct x11drv_win_data *data, unsigned long flags )
1042 {
1043     unsigned long info[2];
1044
1045     info[0] = 0; /* protocol version */
1046     info[1] = flags;
1047     wine_tsx11_lock();
1048     XChangeProperty( display, data->whole_window, x11drv_atom(_XEMBED_INFO),
1049                      x11drv_atom(_XEMBED_INFO), 32, PropModeReplace, (unsigned char*)info, 2 );
1050     wine_tsx11_unlock();
1051 }
1052
1053
1054 /***********************************************************************
1055  *     map_window
1056  */
1057 static void map_window( Display *display, struct x11drv_win_data *data, DWORD new_style )
1058 {
1059     TRACE( "win %p/%lx\n", data->hwnd, data->whole_window );
1060
1061     wait_for_withdrawn_state( display, data, TRUE );
1062
1063     if (!data->embedded)
1064     {
1065         update_net_wm_states( display, data );
1066         sync_window_style( display, data );
1067         wine_tsx11_lock();
1068         XMapWindow( display, data->whole_window );
1069         wine_tsx11_unlock();
1070     }
1071     else set_xembed_flags( display, data, XEMBED_MAPPED );
1072
1073     data->mapped = TRUE;
1074     data->iconic = (new_style & WS_MINIMIZE) != 0;
1075 }
1076
1077
1078 /***********************************************************************
1079  *     unmap_window
1080  */
1081 static void unmap_window( Display *display, struct x11drv_win_data *data )
1082 {
1083     TRACE( "win %p/%lx\n", data->hwnd, data->whole_window );
1084
1085     if (!data->embedded)
1086     {
1087         wait_for_withdrawn_state( display, data, FALSE );
1088         wine_tsx11_lock();
1089         if (data->managed) XWithdrawWindow( display, data->whole_window, DefaultScreen(display) );
1090         else XUnmapWindow( display, data->whole_window );
1091         wine_tsx11_unlock();
1092     }
1093     else set_xembed_flags( display, data, 0 );
1094
1095     data->mapped = FALSE;
1096     data->net_wm_state = 0;
1097 }
1098
1099
1100 /***********************************************************************
1101  *     make_window_embedded
1102  */
1103 void make_window_embedded( Display *display, struct x11drv_win_data *data )
1104 {
1105     if (data->mapped)
1106     {
1107         /* the window cannot be mapped before being embedded */
1108         unmap_window( display, data );
1109         data->embedded = TRUE;
1110         map_window( display, data, 0 );
1111     }
1112     else
1113     {
1114         data->embedded = TRUE;
1115         set_xembed_flags( display, data, 0 );
1116     }
1117 }
1118
1119
1120 /***********************************************************************
1121  *              X11DRV_window_to_X_rect
1122  *
1123  * Convert a rect from client to X window coordinates
1124  */
1125 void X11DRV_window_to_X_rect( struct x11drv_win_data *data, RECT *rect )
1126 {
1127     RECT rc;
1128
1129     if (!data->managed) return;
1130     if (IsRectEmpty( rect )) return;
1131
1132     get_x11_rect_offset( data, &rc );
1133
1134     rect->left   -= rc.left;
1135     rect->right  -= rc.right;
1136     rect->top    -= rc.top;
1137     rect->bottom -= rc.bottom;
1138     if (rect->top >= rect->bottom) rect->bottom = rect->top + 1;
1139     if (rect->left >= rect->right) rect->right = rect->left + 1;
1140 }
1141
1142
1143 /***********************************************************************
1144  *              X11DRV_X_to_window_rect
1145  *
1146  * Opposite of X11DRV_window_to_X_rect
1147  */
1148 void X11DRV_X_to_window_rect( struct x11drv_win_data *data, RECT *rect )
1149 {
1150     RECT rc;
1151
1152     if (!data->managed) return;
1153     if (IsRectEmpty( rect )) return;
1154
1155     get_x11_rect_offset( data, &rc );
1156
1157     rect->left   += rc.left;
1158     rect->right  += rc.right;
1159     rect->top    += rc.top;
1160     rect->bottom += rc.bottom;
1161     if (rect->top >= rect->bottom) rect->bottom = rect->top + 1;
1162     if (rect->left >= rect->right) rect->right = rect->left + 1;
1163 }
1164
1165
1166 /***********************************************************************
1167  *              sync_window_position
1168  *
1169  * Synchronize the X window position with the Windows one
1170  */
1171 static void sync_window_position( Display *display, struct x11drv_win_data *data,
1172                                   UINT swp_flags, const RECT *old_client_rect,
1173                                   const RECT *old_whole_rect )
1174 {
1175     DWORD style = GetWindowLongW( data->hwnd, GWL_STYLE );
1176     XWindowChanges changes;
1177     unsigned int mask = 0;
1178
1179     if (data->managed && data->iconic) return;
1180
1181     /* resizing a managed maximized window is not allowed */
1182     if (!(style & WS_MAXIMIZE) || !data->managed)
1183     {
1184         if ((changes.width = data->whole_rect.right - data->whole_rect.left) <= 0) changes.width = 1;
1185         if ((changes.height = data->whole_rect.bottom - data->whole_rect.top) <= 0) changes.height = 1;
1186         mask |= CWWidth | CWHeight;
1187     }
1188
1189     /* only the size is allowed to change for the desktop window */
1190     if (data->whole_window != root_window)
1191     {
1192         changes.x = data->whole_rect.left - virtual_screen_rect.left;
1193         changes.y = data->whole_rect.top - virtual_screen_rect.top;
1194         mask |= CWX | CWY;
1195     }
1196
1197     if (!(swp_flags & SWP_NOZORDER))
1198     {
1199         /* find window that this one must be after */
1200         HWND prev = GetWindow( data->hwnd, GW_HWNDPREV );
1201         while (prev && !(GetWindowLongW( prev, GWL_STYLE ) & WS_VISIBLE))
1202             prev = GetWindow( prev, GW_HWNDPREV );
1203         if (!prev)  /* top child */
1204         {
1205             changes.stack_mode = Above;
1206             mask |= CWStackMode;
1207         }
1208         /* should use stack_mode Below but most window managers don't get it right */
1209         /* and Above with a sibling doesn't work so well either, so we ignore it */
1210     }
1211
1212     TRACE( "setting win %p/%lx pos %d,%d,%dx%d after %lx changes=%x\n",
1213            data->hwnd, data->whole_window, data->whole_rect.left, data->whole_rect.top,
1214            data->whole_rect.right - data->whole_rect.left,
1215            data->whole_rect.bottom - data->whole_rect.top, changes.sibling, mask );
1216
1217     wine_tsx11_lock();
1218     set_size_hints( display, data, style );
1219     XReconfigureWMWindow( display, data->whole_window,
1220                           DefaultScreen(display), mask, &changes );
1221     wine_tsx11_unlock();
1222 }
1223
1224
1225 /***********************************************************************
1226  *              sync_client_position
1227  *
1228  * Synchronize the X client window position with the Windows one
1229  */
1230 static void sync_client_position( Display *display, struct x11drv_win_data *data,
1231                                   UINT swp_flags, const RECT *old_client_rect,
1232                                   const RECT *old_whole_rect )
1233 {
1234     int mask;
1235     XWindowChanges changes;
1236     RECT old = *old_client_rect;
1237     RECT new = data->client_rect;
1238
1239     OffsetRect( &old, -old_whole_rect->left, -old_whole_rect->top );
1240     OffsetRect( &new, -data->whole_rect.left, -data->whole_rect.top );
1241     if (!(mask = get_window_changes( &changes, &old, &new ))) return;
1242
1243     if (data->client_window)
1244     {
1245         TRACE( "setting client win %lx pos %d,%d,%dx%d changes=%x\n",
1246                data->client_window, new.left, new.top,
1247                new.right - new.left, new.bottom - new.top, mask );
1248         wine_tsx11_lock();
1249         XConfigureWindow( display, data->client_window, mask, &changes );
1250         wine_tsx11_unlock();
1251     }
1252
1253     if (data->gl_drawable && (mask & (CWWidth|CWHeight))) sync_gl_drawable( data );
1254 }
1255
1256
1257 /***********************************************************************
1258  *              move_window_bits
1259  *
1260  * Move the window bits when a window is moved.
1261  */
1262 static void move_window_bits( struct x11drv_win_data *data, const RECT *old_rect, const RECT *new_rect,
1263                               const RECT *old_client_rect )
1264 {
1265     RECT src_rect = *old_rect;
1266     RECT dst_rect = *new_rect;
1267     HDC hdc_src, hdc_dst;
1268     INT code;
1269     HRGN rgn = 0;
1270     HWND parent = 0;
1271
1272     if (!data->whole_window)
1273     {
1274         OffsetRect( &dst_rect, -data->window_rect.left, -data->window_rect.top );
1275         parent = GetAncestor( data->hwnd, GA_PARENT );
1276         hdc_src = GetDCEx( parent, 0, DCX_CACHE );
1277         hdc_dst = GetDCEx( data->hwnd, 0, DCX_CACHE | DCX_WINDOW );
1278     }
1279     else
1280     {
1281         OffsetRect( &dst_rect, -data->client_rect.left, -data->client_rect.top );
1282         /* make src rect relative to the old position of the window */
1283         OffsetRect( &src_rect, -old_client_rect->left, -old_client_rect->top );
1284         if (dst_rect.left == src_rect.left && dst_rect.top == src_rect.top) return;
1285         hdc_src = hdc_dst = GetDCEx( data->hwnd, 0, DCX_CACHE );
1286     }
1287
1288     code = X11DRV_START_EXPOSURES;
1289     ExtEscape( hdc_dst, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
1290
1291     TRACE( "copying bits for win %p/%lx/%lx %s -> %s\n",
1292            data->hwnd, data->whole_window, data->client_window,
1293            wine_dbgstr_rect(&src_rect), wine_dbgstr_rect(&dst_rect) );
1294     BitBlt( hdc_dst, dst_rect.left, dst_rect.top,
1295             dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top,
1296             hdc_src, src_rect.left, src_rect.top, SRCCOPY );
1297
1298     code = X11DRV_END_EXPOSURES;
1299     ExtEscape( hdc_dst, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, sizeof(rgn), (LPSTR)&rgn );
1300
1301     ReleaseDC( data->hwnd, hdc_dst );
1302     if (hdc_src != hdc_dst) ReleaseDC( parent, hdc_src );
1303
1304     if (rgn)
1305     {
1306         if (!data->whole_window)
1307         {
1308             /* map region to client rect since we are using DCX_WINDOW */
1309             OffsetRgn( rgn, data->window_rect.left - data->client_rect.left,
1310                        data->window_rect.top - data->client_rect.top );
1311             RedrawWindow( data->hwnd, NULL, rgn,
1312                           RDW_INVALIDATE | RDW_FRAME | RDW_ERASE | RDW_ALLCHILDREN );
1313         }
1314         else RedrawWindow( data->hwnd, NULL, rgn, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN );
1315         DeleteObject( rgn );
1316     }
1317 }
1318
1319
1320 /**********************************************************************
1321  *              create_whole_window
1322  *
1323  * Create the whole X window for a given window
1324  */
1325 static Window create_whole_window( Display *display, struct x11drv_win_data *data )
1326 {
1327     int cx, cy, mask;
1328     XSetWindowAttributes attr;
1329     WCHAR text[1024];
1330     HRGN hrgn;
1331
1332     if (!(cx = data->window_rect.right - data->window_rect.left)) cx = 1;
1333     if (!(cy = data->window_rect.bottom - data->window_rect.top)) cy = 1;
1334
1335     if (!data->managed && is_window_managed( data->hwnd, SWP_NOACTIVATE, &data->window_rect ))
1336     {
1337         TRACE( "making win %p/%lx managed\n", data->hwnd, data->whole_window );
1338         data->managed = TRUE;
1339         SetPropA( data->hwnd, managed_prop, (HANDLE)1 );
1340     }
1341
1342     mask = get_window_attributes( display, data, &attr );
1343
1344     wine_tsx11_lock();
1345
1346     data->whole_rect = data->window_rect;
1347     data->whole_window = XCreateWindow( display, root_window,
1348                                         data->window_rect.left - virtual_screen_rect.left,
1349                                         data->window_rect.top - virtual_screen_rect.top,
1350                                         cx, cy, 0, screen_depth, InputOutput,
1351                                         visual, mask, &attr );
1352
1353     if (data->whole_window) XSaveContext( display, data->whole_window, winContext, (char *)data->hwnd );
1354     wine_tsx11_unlock();
1355
1356     if (!data->whole_window) return 0;
1357
1358     if (!create_client_window( display, data, NULL ))
1359     {
1360         wine_tsx11_lock();
1361         XDeleteContext( display, data->whole_window, winContext );
1362         XDestroyWindow( display, data->whole_window );
1363         data->whole_window = 0;
1364         wine_tsx11_unlock();
1365         return 0;
1366     }
1367
1368     set_initial_wm_hints( display, data );
1369     set_wm_hints( display, data );
1370
1371     SetPropA( data->hwnd, whole_window_prop, (HANDLE)data->whole_window );
1372
1373     /* set the window text */
1374     if (!InternalGetWindowText( data->hwnd, text, sizeof(text)/sizeof(WCHAR) )) text[0] = 0;
1375     sync_window_text( display, data->whole_window, text );
1376
1377     /* set the window region */
1378     if ((hrgn = CreateRectRgn( 0, 0, 0, 0 )))
1379     {
1380         if (GetWindowRgn( data->hwnd, hrgn ) != ERROR) sync_window_region( display, data, hrgn );
1381         DeleteObject( hrgn );
1382     }
1383     wine_tsx11_lock();
1384     XFlush( display );  /* make sure the window exists before we start painting to it */
1385     wine_tsx11_unlock();
1386     return data->whole_window;
1387 }
1388
1389
1390 /**********************************************************************
1391  *              destroy_whole_window
1392  *
1393  * Destroy the whole X window for a given window.
1394  */
1395 static void destroy_whole_window( Display *display, struct x11drv_win_data *data, BOOL already_destroyed )
1396 {
1397     struct x11drv_thread_data *thread_data = x11drv_thread_data();
1398
1399     if (!data->whole_window) return;
1400
1401     TRACE( "win %p xwin %lx/%lx\n", data->hwnd, data->whole_window, data->client_window );
1402     if (thread_data->cursor_window == data->whole_window ||
1403         thread_data->cursor_window == data->client_window)
1404         thread_data->cursor_window = None;
1405     wine_tsx11_lock();
1406     XDeleteContext( display, data->whole_window, winContext );
1407     XDeleteContext( display, data->client_window, winContext );
1408     if (!already_destroyed) XDestroyWindow( display, data->whole_window );
1409     data->whole_window = data->client_window = 0;
1410     data->wm_state = WithdrawnState;
1411     data->net_wm_state = 0;
1412     data->mapped = FALSE;
1413     if (data->xic)
1414     {
1415         XUnsetICFocus( data->xic );
1416         XDestroyIC( data->xic );
1417         data->xic = 0;
1418     }
1419     /* Outlook stops processing messages after destroying a dialog, so we need an explicit flush */
1420     XFlush( display );
1421     XFree( data->wm_hints );
1422     data->wm_hints = NULL;
1423     wine_tsx11_unlock();
1424     RemovePropA( data->hwnd, whole_window_prop );
1425     RemovePropA( data->hwnd, client_window_prop );
1426 }
1427
1428
1429 /*****************************************************************
1430  *              SetWindowText   (X11DRV.@)
1431  */
1432 void X11DRV_SetWindowText( HWND hwnd, LPCWSTR text )
1433 {
1434     Display *display = thread_display();
1435     Window win;
1436
1437     if ((win = X11DRV_get_whole_window( hwnd )) && win != DefaultRootWindow(display))
1438         sync_window_text( display, win, text );
1439 }
1440
1441
1442 /***********************************************************************
1443  *              SetWindowStyle   (X11DRV.@)
1444  *
1445  * Update the X state of a window to reflect a style change
1446  */
1447 void X11DRV_SetWindowStyle( HWND hwnd, DWORD old_style )
1448 {
1449     Display *display = thread_display();
1450     struct x11drv_win_data *data;
1451     DWORD new_style, changed;
1452
1453     if (hwnd == GetDesktopWindow()) return;
1454     new_style = GetWindowLongW( hwnd, GWL_STYLE );
1455     changed = new_style ^ old_style;
1456
1457     if ((changed & WS_VISIBLE) && (new_style & WS_VISIBLE))
1458     {
1459         /* we don't unmap windows, that causes trouble with the window manager */
1460         if (!(data = X11DRV_get_win_data( hwnd )) &&
1461             !(data = X11DRV_create_win_data( hwnd ))) return;
1462
1463         if (data->whole_window && is_window_rect_mapped( &data->window_rect ))
1464         {
1465             set_wm_hints( display, data );
1466             if (!data->mapped) map_window( display, data, new_style );
1467         }
1468     }
1469
1470     if (changed & WS_DISABLED)
1471     {
1472         data = X11DRV_get_win_data( hwnd );
1473         if (data && data->wm_hints)
1474         {
1475             wine_tsx11_lock();
1476             data->wm_hints->input = !(new_style & WS_DISABLED);
1477             XSetWMHints( display, data->whole_window, data->wm_hints );
1478             wine_tsx11_unlock();
1479         }
1480     }
1481 }
1482
1483
1484 /***********************************************************************
1485  *              DestroyWindow   (X11DRV.@)
1486  */
1487 void X11DRV_DestroyWindow( HWND hwnd )
1488 {
1489     struct x11drv_thread_data *thread_data = x11drv_thread_data();
1490     Display *display = thread_data->display;
1491     struct x11drv_win_data *data;
1492
1493     if (!(data = X11DRV_get_win_data( hwnd ))) return;
1494
1495     if (data->pixmap)
1496     {
1497         wine_tsx11_lock();
1498         destroy_glxpixmap(gdi_display, data->gl_drawable);
1499         XFreePixmap(gdi_display, data->pixmap);
1500         wine_tsx11_unlock();
1501     }
1502     else if (data->gl_drawable)
1503     {
1504         wine_tsx11_lock();
1505         XDestroyWindow(gdi_display, data->gl_drawable);
1506         wine_tsx11_unlock();
1507     }
1508
1509     destroy_whole_window( display, data, FALSE );
1510     destroy_icon_window( display, data );
1511
1512     if (data->colormap)
1513     {
1514         wine_tsx11_lock();
1515         XFreeColormap( display, data->colormap );
1516         wine_tsx11_unlock();
1517     }
1518
1519     if (thread_data->last_focus == hwnd) thread_data->last_focus = 0;
1520     if (data->hWMIconBitmap) DeleteObject( data->hWMIconBitmap );
1521     if (data->hWMIconMask) DeleteObject( data->hWMIconMask);
1522     wine_tsx11_lock();
1523     XDeleteContext( display, (XID)hwnd, win_data_context );
1524     wine_tsx11_unlock();
1525     HeapFree( GetProcessHeap(), 0, data );
1526 }
1527
1528
1529 /***********************************************************************
1530  *              X11DRV_DestroyNotify
1531  */
1532 void X11DRV_DestroyNotify( HWND hwnd, XEvent *event )
1533 {
1534     Display *display = event->xdestroywindow.display;
1535     struct x11drv_win_data *data;
1536
1537     if (!(data = X11DRV_get_win_data( hwnd ))) return;
1538
1539     FIXME( "window %p/%lx destroyed from the outside\n", hwnd, data->whole_window );
1540     destroy_whole_window( display, data, TRUE );
1541 }
1542
1543
1544 static struct x11drv_win_data *alloc_win_data( Display *display, HWND hwnd )
1545 {
1546     struct x11drv_win_data *data;
1547
1548     if ((data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data))))
1549     {
1550         data->hwnd = hwnd;
1551         wine_tsx11_lock();
1552         if (!winContext) winContext = XUniqueContext();
1553         if (!win_data_context) win_data_context = XUniqueContext();
1554         XSaveContext( display, (XID)hwnd, win_data_context, (char *)data );
1555         wine_tsx11_unlock();
1556     }
1557     return data;
1558 }
1559
1560
1561 /* initialize the desktop window id in the desktop manager process */
1562 static struct x11drv_win_data *create_desktop_win_data( Display *display, HWND hwnd )
1563 {
1564     struct x11drv_win_data *data;
1565
1566     if (!(data = alloc_win_data( display, hwnd ))) return NULL;
1567     data->whole_window = data->client_window = root_window;
1568     data->managed = TRUE;
1569     SetPropA( data->hwnd, managed_prop, (HANDLE)1 );
1570     SetPropA( data->hwnd, whole_window_prop, (HANDLE)root_window );
1571     SetPropA( data->hwnd, client_window_prop, (HANDLE)root_window );
1572     set_initial_wm_hints( display, data );
1573     return data;
1574 }
1575
1576 /**********************************************************************
1577  *              CreateDesktopWindow   (X11DRV.@)
1578  */
1579 BOOL X11DRV_CreateDesktopWindow( HWND hwnd )
1580 {
1581     unsigned int width, height;
1582
1583     /* retrieve the real size of the desktop */
1584     SERVER_START_REQ( get_window_rectangles )
1585     {
1586         req->handle = hwnd;
1587         wine_server_call( req );
1588         width  = reply->window.right - reply->window.left;
1589         height = reply->window.bottom - reply->window.top;
1590     }
1591     SERVER_END_REQ;
1592
1593     if (!width && !height)  /* not initialized yet */
1594     {
1595         SERVER_START_REQ( set_window_pos )
1596         {
1597             req->handle        = hwnd;
1598             req->previous      = 0;
1599             req->flags         = SWP_NOZORDER;
1600             req->window.left   = virtual_screen_rect.left;
1601             req->window.top    = virtual_screen_rect.top;
1602             req->window.right  = virtual_screen_rect.right;
1603             req->window.bottom = virtual_screen_rect.bottom;
1604             req->client        = req->window;
1605             wine_server_call( req );
1606         }
1607         SERVER_END_REQ;
1608     }
1609     else
1610     {
1611         Window win = (Window)GetPropA( hwnd, whole_window_prop );
1612         if (win && win != root_window) X11DRV_init_desktop( win, width, height );
1613     }
1614     return TRUE;
1615 }
1616
1617
1618 /**********************************************************************
1619  *              CreateWindow   (X11DRV.@)
1620  */
1621 BOOL X11DRV_CreateWindow( HWND hwnd )
1622 {
1623     Display *display = thread_display();
1624
1625     if (hwnd == GetDesktopWindow() && root_window != DefaultRootWindow( display ))
1626     {
1627         /* the desktop win data can't be created lazily */
1628         if (!create_desktop_win_data( display, hwnd )) return FALSE;
1629     }
1630     return TRUE;
1631 }
1632
1633
1634 /***********************************************************************
1635  *              X11DRV_get_win_data
1636  *
1637  * Return the X11 data structure associated with a window.
1638  */
1639 struct x11drv_win_data *X11DRV_get_win_data( HWND hwnd )
1640 {
1641     char *data;
1642
1643     if (!hwnd || XFindContext( thread_display(), (XID)hwnd, win_data_context, &data )) data = NULL;
1644     return (struct x11drv_win_data *)data;
1645 }
1646
1647
1648 /***********************************************************************
1649  *              X11DRV_create_win_data
1650  *
1651  * Create an X11 data window structure for an existing window.
1652  */
1653 struct x11drv_win_data *X11DRV_create_win_data( HWND hwnd )
1654 {
1655     Display *display = thread_display();
1656     struct x11drv_win_data *data;
1657     HWND parent;
1658
1659     if (!(parent = GetAncestor( hwnd, GA_PARENT ))) return NULL;  /* desktop */
1660     if (!(data = alloc_win_data( display, hwnd ))) return NULL;
1661
1662     GetWindowRect( hwnd, &data->window_rect );
1663     MapWindowPoints( 0, parent, (POINT *)&data->window_rect, 2 );
1664     data->whole_rect = data->window_rect;
1665     GetClientRect( hwnd, &data->client_rect );
1666     MapWindowPoints( hwnd, parent, (POINT *)&data->client_rect, 2 );
1667
1668     if (parent == GetDesktopWindow())
1669     {
1670         if (!create_whole_window( display, data ))
1671         {
1672             HeapFree( GetProcessHeap(), 0, data );
1673             return NULL;
1674         }
1675         TRACE( "win %p/%lx/%lx window %s whole %s client %s\n",
1676                hwnd, data->whole_window, data->client_window, wine_dbgstr_rect( &data->window_rect ),
1677                wine_dbgstr_rect( &data->whole_rect ), wine_dbgstr_rect( &data->client_rect ));
1678     }
1679     return data;
1680 }
1681
1682
1683 /***********************************************************************
1684  *              X11DRV_get_whole_window
1685  *
1686  * Return the X window associated with the full area of a window
1687  */
1688 Window X11DRV_get_whole_window( HWND hwnd )
1689 {
1690     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
1691
1692     if (!data)
1693     {
1694         if (hwnd == GetDesktopWindow()) return root_window;
1695         return (Window)GetPropA( hwnd, whole_window_prop );
1696     }
1697     return data->whole_window;
1698 }
1699
1700
1701 /***********************************************************************
1702  *              X11DRV_get_client_window
1703  *
1704  * Return the X window associated with the client area of a window
1705  */
1706 Window X11DRV_get_client_window( HWND hwnd )
1707 {
1708     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
1709
1710     if (!data)
1711     {
1712         if (hwnd == GetDesktopWindow()) return root_window;
1713         return (Window)GetPropA( hwnd, client_window_prop );
1714     }
1715     return data->client_window;
1716 }
1717
1718
1719 /***********************************************************************
1720  *              X11DRV_get_ic
1721  *
1722  * Return the X input context associated with a window
1723  */
1724 XIC X11DRV_get_ic( HWND hwnd )
1725 {
1726     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
1727     XIM xim;
1728
1729     if (!data) return 0;
1730     if (data->xic) return data->xic;
1731     if (!(xim = x11drv_thread_data()->xim)) return 0;
1732     return X11DRV_CreateIC( xim, data );
1733 }
1734
1735
1736 /***********************************************************************
1737  *              X11DRV_GetDC   (X11DRV.@)
1738  */
1739 void X11DRV_GetDC( HDC hdc, HWND hwnd, HWND top, const RECT *win_rect,
1740                    const RECT *top_rect, DWORD flags )
1741 {
1742     struct x11drv_escape_set_drawable escape;
1743     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
1744
1745     escape.code        = X11DRV_SET_DRAWABLE;
1746     escape.mode        = IncludeInferiors;
1747     escape.fbconfig_id = 0;
1748     escape.gl_drawable = 0;
1749     escape.pixmap      = 0;
1750     escape.gl_copy     = FALSE;
1751
1752     if (top == hwnd && data && IsIconic( hwnd ) && data->icon_window)
1753     {
1754         escape.drawable = data->icon_window;
1755     }
1756     else if (top == hwnd)
1757     {
1758         escape.fbconfig_id = data ? data->fbconfig_id : (XID)GetPropA( hwnd, fbconfig_id_prop );
1759         /* GL draws to the client area even for window DCs */
1760         escape.gl_drawable = data ? data->client_window : X11DRV_get_client_window( hwnd );
1761         if (flags & DCX_WINDOW)
1762             escape.drawable = data ? data->whole_window : X11DRV_get_whole_window( hwnd );
1763         else
1764             escape.drawable = escape.gl_drawable;
1765     }
1766     else
1767     {
1768         escape.drawable    = X11DRV_get_client_window( top );
1769         escape.fbconfig_id = data ? data->fbconfig_id : (XID)GetPropA( hwnd, fbconfig_id_prop );
1770         escape.gl_drawable = data ? data->gl_drawable : (Drawable)GetPropA( hwnd, gl_drawable_prop );
1771         escape.pixmap      = data ? data->pixmap : (Pixmap)GetPropA( hwnd, pixmap_prop );
1772         escape.gl_copy     = (escape.gl_drawable != 0);
1773         if (flags & DCX_CLIPCHILDREN) escape.mode = ClipByChildren;
1774     }
1775
1776     escape.dc_rect.left         = win_rect->left - top_rect->left;
1777     escape.dc_rect.top          = win_rect->top - top_rect->top;
1778     escape.dc_rect.right        = win_rect->right - top_rect->left;
1779     escape.dc_rect.bottom       = win_rect->bottom - top_rect->top;
1780     escape.drawable_rect.left   = top_rect->left;
1781     escape.drawable_rect.top    = top_rect->top;
1782     escape.drawable_rect.right  = top_rect->right;
1783     escape.drawable_rect.bottom = top_rect->bottom;
1784
1785     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
1786 }
1787
1788
1789 /***********************************************************************
1790  *              X11DRV_ReleaseDC  (X11DRV.@)
1791  */
1792 void X11DRV_ReleaseDC( HWND hwnd, HDC hdc )
1793 {
1794     struct x11drv_escape_set_drawable escape;
1795
1796     escape.code = X11DRV_SET_DRAWABLE;
1797     escape.drawable = root_window;
1798     escape.mode = IncludeInferiors;
1799     escape.drawable_rect = virtual_screen_rect;
1800     SetRect( &escape.dc_rect, 0, 0, virtual_screen_rect.right - virtual_screen_rect.left,
1801              virtual_screen_rect.bottom - virtual_screen_rect.top );
1802     escape.fbconfig_id = 0;
1803     escape.gl_drawable = 0;
1804     escape.pixmap = 0;
1805     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
1806 }
1807
1808
1809 /***********************************************************************
1810  *              SetCapture  (X11DRV.@)
1811  */
1812 void X11DRV_SetCapture( HWND hwnd, UINT flags )
1813 {
1814     struct x11drv_thread_data *thread_data = x11drv_thread_data();
1815
1816     if (!(flags & (GUI_INMOVESIZE | GUI_INMENUMODE))) return;
1817
1818     if (hwnd)
1819     {
1820         Window grab_win = X11DRV_get_client_window( GetAncestor( hwnd, GA_ROOT ) );
1821
1822         if (!grab_win) return;
1823         wine_tsx11_lock();
1824         XFlush( gdi_display );
1825         XGrabPointer( thread_data->display, grab_win, False,
1826                       PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
1827                       GrabModeAsync, GrabModeAsync, None, None, CurrentTime );
1828         wine_tsx11_unlock();
1829         thread_data->grab_window = grab_win;
1830     }
1831     else  /* release capture */
1832     {
1833         wine_tsx11_lock();
1834         XFlush( gdi_display );
1835         XUngrabPointer( thread_data->display, CurrentTime );
1836         wine_tsx11_unlock();
1837         thread_data->grab_window = None;
1838     }
1839 }
1840
1841
1842 /*****************************************************************
1843  *              SetParent   (X11DRV.@)
1844  */
1845 void X11DRV_SetParent( HWND hwnd, HWND parent, HWND old_parent )
1846 {
1847     Display *display = thread_display();
1848     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
1849
1850     if (!data) return;
1851     if (parent == old_parent) return;
1852
1853     if (parent != GetDesktopWindow()) /* a child window */
1854     {
1855         if (old_parent == GetDesktopWindow())
1856         {
1857             /* destroy the old X windows */
1858             destroy_whole_window( display, data, FALSE );
1859             destroy_icon_window( display, data );
1860             if (data->managed)
1861             {
1862                 data->managed = FALSE;
1863                 RemovePropA( data->hwnd, managed_prop );
1864             }
1865         }
1866     }
1867     else  /* new top level window */
1868     {
1869         /* FIXME: we ignore errors since we can't really recover anyway */
1870         create_whole_window( display, data );
1871     }
1872 }
1873
1874
1875 /*****************************************************************
1876  *              SetFocus   (X11DRV.@)
1877  *
1878  * Set the X focus.
1879  * Explicit colormap management seems to work only with OLVWM.
1880  */
1881 void X11DRV_SetFocus( HWND hwnd )
1882 {
1883     Display *display = thread_display();
1884     struct x11drv_win_data *data;
1885     XWindowChanges changes;
1886
1887     /* If setting the focus to 0, uninstall the colormap */
1888     if (!hwnd && root_window == DefaultRootWindow(display))
1889     {
1890         wine_tsx11_lock();
1891         if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
1892             XUninstallColormap( display, X11DRV_PALETTE_PaletteXColormap );
1893         wine_tsx11_unlock();
1894         return;
1895     }
1896
1897     hwnd = GetAncestor( hwnd, GA_ROOT );
1898
1899     if (!(data = X11DRV_get_win_data( hwnd ))) return;
1900     if (data->managed || !data->whole_window) return;
1901
1902     /* Set X focus and install colormap */
1903     wine_tsx11_lock();
1904     changes.stack_mode = Above;
1905     XConfigureWindow( display, data->whole_window, CWStackMode, &changes );
1906     if (root_window == DefaultRootWindow(display))
1907     {
1908         /* we must not use CurrentTime (ICCCM), so try to use last message time instead */
1909         /* FIXME: this is not entirely correct */
1910         XSetInputFocus( display, data->whole_window, RevertToParent,
1911                         /* CurrentTime */
1912                         GetMessageTime() - EVENT_x11_time_to_win32_time(0));
1913         if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
1914             XInstallColormap( display, X11DRV_PALETTE_PaletteXColormap );
1915     }
1916     wine_tsx11_unlock();
1917 }
1918
1919
1920 /***********************************************************************
1921  *              SetWindowPos   (X11DRV.@)
1922  */
1923 void X11DRV_SetWindowPos( HWND hwnd, HWND insert_after, UINT swp_flags,
1924                           const RECT *rectWindow, const RECT *rectClient,
1925                           const RECT *visible_rect, const RECT *valid_rects )
1926 {
1927     struct x11drv_thread_data *thread_data = x11drv_thread_data();
1928     Display *display = thread_data->display;
1929     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
1930     DWORD new_style = GetWindowLongW( hwnd, GWL_STYLE );
1931     RECT old_whole_rect, old_client_rect;
1932     int event_type;
1933
1934     if (!data)
1935     {
1936         /* create the win data if the window is being made visible */
1937         if (!(new_style & WS_VISIBLE)) return;
1938         if (!(data = X11DRV_create_win_data( hwnd ))) return;
1939     }
1940
1941     /* check if we need to switch the window to managed */
1942     if (!data->managed && data->whole_window && is_window_managed( hwnd, swp_flags, rectWindow ))
1943     {
1944         TRACE( "making win %p/%lx managed\n", hwnd, data->whole_window );
1945         if (data->mapped) unmap_window( display, data );
1946         data->managed = TRUE;
1947         SetPropA( hwnd, managed_prop, (HANDLE)1 );
1948     }
1949
1950     old_whole_rect  = data->whole_rect;
1951     old_client_rect = data->client_rect;
1952     data->window_rect = *rectWindow;
1953     data->whole_rect  = *rectWindow;
1954     data->client_rect = *rectClient;
1955     X11DRV_window_to_X_rect( data, &data->whole_rect );
1956     if (memcmp( visible_rect, &data->whole_rect, sizeof(RECT) ))
1957     {
1958         TRACE( "%p: need to update visible rect %s -> %s\n", hwnd,
1959                wine_dbgstr_rect(visible_rect), wine_dbgstr_rect(&data->whole_rect) );
1960         SERVER_START_REQ( set_window_visible_rect )
1961         {
1962             req->handle         = hwnd;
1963             req->flags          = swp_flags;
1964             req->visible.left   = data->whole_rect.left;
1965             req->visible.top    = data->whole_rect.top;
1966             req->visible.right  = data->whole_rect.right;
1967             req->visible.bottom = data->whole_rect.bottom;
1968             wine_server_call( req );
1969         }
1970         SERVER_END_REQ;
1971     }
1972
1973     TRACE( "win %p window %s client %s style %08x flags %08x\n",
1974            hwnd, wine_dbgstr_rect(rectWindow), wine_dbgstr_rect(rectClient), new_style, swp_flags );
1975
1976     if (!IsRectEmpty( &valid_rects[0] ))
1977     {
1978         int x_offset = old_whole_rect.left - data->whole_rect.left;
1979         int y_offset = old_whole_rect.top - data->whole_rect.top;
1980
1981         /* if all that happened is that the whole window moved, copy everything */
1982         if (!(swp_flags & SWP_FRAMECHANGED) &&
1983             old_whole_rect.right   - data->whole_rect.right   == x_offset &&
1984             old_whole_rect.bottom  - data->whole_rect.bottom  == y_offset &&
1985             old_client_rect.left   - data->client_rect.left   == x_offset &&
1986             old_client_rect.right  - data->client_rect.right  == x_offset &&
1987             old_client_rect.top    - data->client_rect.top    == y_offset &&
1988             old_client_rect.bottom - data->client_rect.bottom == y_offset &&
1989             !memcmp( &valid_rects[0], &data->client_rect, sizeof(RECT) ))
1990         {
1991             /* if we have an X window the bits will be moved by the X server */
1992             if (!data->whole_window)
1993                 move_window_bits( data, &old_whole_rect, &data->whole_rect, &old_client_rect );
1994         }
1995         else
1996             move_window_bits( data, &valid_rects[1], &valid_rects[0], &old_client_rect );
1997     }
1998
1999     wine_tsx11_lock();
2000     XFlush( gdi_display );  /* make sure painting is done before we move the window */
2001     wine_tsx11_unlock();
2002
2003     sync_client_position( display, data, swp_flags, &old_client_rect, &old_whole_rect );
2004
2005     if (!data->whole_window) return;
2006
2007     /* check if we are currently processing an event relevant to this window */
2008     event_type = 0;
2009     if (thread_data->current_event && thread_data->current_event->xany.window == data->whole_window)
2010         event_type = thread_data->current_event->type;
2011
2012     if (event_type != ConfigureNotify && event_type != PropertyNotify)
2013         event_type = 0;  /* ignore other events */
2014
2015     if (data->mapped)
2016     {
2017         if (((swp_flags & SWP_HIDEWINDOW) && !(new_style & WS_VISIBLE)) ||
2018             (!event_type && !is_window_rect_mapped( rectWindow )))
2019             unmap_window( display, data );
2020     }
2021
2022     /* don't change position if we are about to minimize or maximize a managed window */
2023     if (!event_type &&
2024         !(data->managed && (swp_flags & SWP_STATECHANGED) && (new_style & (WS_MINIMIZE|WS_MAXIMIZE))))
2025         sync_window_position( display, data, swp_flags, &old_client_rect, &old_whole_rect );
2026
2027     if ((new_style & WS_VISIBLE) &&
2028         ((new_style & WS_MINIMIZE) || is_window_rect_mapped( rectWindow )))
2029     {
2030         if (!data->mapped || (swp_flags & (SWP_FRAMECHANGED|SWP_STATECHANGED)))
2031             set_wm_hints( display, data );
2032
2033         if (!data->mapped)
2034         {
2035             map_window( display, data, new_style );
2036         }
2037         else if ((swp_flags & SWP_STATECHANGED) && (!data->iconic != !(new_style & WS_MINIMIZE)))
2038         {
2039             data->iconic = (new_style & WS_MINIMIZE) != 0;
2040             TRACE( "changing win %p iconic state to %u\n", data->hwnd, data->iconic );
2041             wine_tsx11_lock();
2042             if (data->iconic)
2043                 XIconifyWindow( display, data->whole_window, DefaultScreen(display) );
2044             else if (is_window_rect_mapped( rectWindow ))
2045                 XMapWindow( display, data->whole_window );
2046             wine_tsx11_unlock();
2047             update_net_wm_states( display, data );
2048         }
2049         else if (!event_type)
2050         {
2051             update_net_wm_states( display, data );
2052         }
2053     }
2054
2055     wine_tsx11_lock();
2056     XFlush( display );  /* make sure changes are done before we start painting again */
2057     wine_tsx11_unlock();
2058 }
2059
2060
2061 /**********************************************************************
2062  *              SetWindowIcon (X11DRV.@)
2063  *
2064  * hIcon or hIconSm has changed (or is being initialised for the
2065  * first time). Complete the X11 driver-specific initialisation
2066  * and set the window hints.
2067  *
2068  * This is not entirely correct, may need to create
2069  * an icon window and set the pixmap as a background
2070  */
2071 void X11DRV_SetWindowIcon( HWND hwnd, UINT type, HICON icon )
2072 {
2073     Display *display = thread_display();
2074     struct x11drv_win_data *data;
2075
2076     if (type != ICON_BIG) return;  /* nothing to do here */
2077
2078     if (!(data = X11DRV_get_win_data( hwnd ))) return;
2079     if (!data->whole_window) return;
2080     if (!data->managed) return;
2081
2082     if (data->wm_hints)
2083     {
2084         set_icon_hints( display, data, icon );
2085         wine_tsx11_lock();
2086         XSetWMHints( display, data->whole_window, data->wm_hints );
2087         wine_tsx11_unlock();
2088     }
2089 }
2090
2091
2092 /***********************************************************************
2093  *              SetWindowRgn  (X11DRV.@)
2094  *
2095  * Assign specified region to window (for non-rectangular windows)
2096  */
2097 int X11DRV_SetWindowRgn( HWND hwnd, HRGN hrgn, BOOL redraw )
2098 {
2099     struct x11drv_win_data *data;
2100
2101     if ((data = X11DRV_get_win_data( hwnd )))
2102     {
2103         sync_window_region( thread_display(), data, hrgn );
2104     }
2105     else if (GetWindowThreadProcessId( hwnd, NULL ) != GetCurrentThreadId())
2106     {
2107         FIXME( "not supported on other thread window %p\n", hwnd );
2108         SetLastError( ERROR_INVALID_WINDOW_HANDLE );
2109         return FALSE;
2110     }
2111
2112     return TRUE;
2113 }
2114
2115
2116 /***********************************************************************
2117  *              is_netwm_supported
2118  */
2119 static BOOL is_netwm_supported( Display *display, Atom atom )
2120 {
2121     static Atom *net_supported;
2122     static int net_supported_count = -1;
2123     int i;
2124
2125     wine_tsx11_lock();
2126     if (net_supported_count == -1)
2127     {
2128         Atom type;
2129         int format;
2130         unsigned long count, remaining;
2131
2132         if (!XGetWindowProperty( display, DefaultRootWindow(display), x11drv_atom(_NET_SUPPORTED), 0,
2133                                  ~0UL, False, XA_ATOM, &type, &format, &count,
2134                                  &remaining, (unsigned char **)&net_supported ))
2135             net_supported_count = get_property_size( format, count ) / sizeof(Atom);
2136         else
2137             net_supported_count = 0;
2138     }
2139     wine_tsx11_unlock();
2140
2141     for (i = 0; i < net_supported_count; i++)
2142         if (net_supported[i] == atom) return TRUE;
2143     return FALSE;
2144 }
2145
2146
2147 /***********************************************************************
2148  *           SysCommand   (X11DRV.@)
2149  *
2150  * Perform WM_SYSCOMMAND handling.
2151  */
2152 LRESULT X11DRV_SysCommand( HWND hwnd, WPARAM wparam, LPARAM lparam )
2153 {
2154     WPARAM hittest = wparam & 0x0f;
2155     DWORD dwPoint;
2156     int x, y, dir;
2157     XEvent xev;
2158     Display *display = thread_display();
2159     struct x11drv_win_data *data;
2160
2161     if (!(data = X11DRV_get_win_data( hwnd ))) return -1;
2162     if (!data->whole_window || !data->managed || !data->mapped) return -1;
2163
2164     switch (wparam & 0xfff0)
2165     {
2166     case SC_MOVE:
2167         if (!hittest) dir = _NET_WM_MOVERESIZE_MOVE_KEYBOARD;
2168         else dir = _NET_WM_MOVERESIZE_MOVE;
2169         break;
2170     case SC_SIZE:
2171         /* windows without WS_THICKFRAME are not resizable through the window manager */
2172         if (!(GetWindowLongW( hwnd, GWL_STYLE ) & WS_THICKFRAME)) return -1;
2173
2174         switch (hittest)
2175         {
2176         case WMSZ_LEFT:        dir = _NET_WM_MOVERESIZE_SIZE_LEFT; break;
2177         case WMSZ_RIGHT:       dir = _NET_WM_MOVERESIZE_SIZE_RIGHT; break;
2178         case WMSZ_TOP:         dir = _NET_WM_MOVERESIZE_SIZE_TOP; break;
2179         case WMSZ_TOPLEFT:     dir = _NET_WM_MOVERESIZE_SIZE_TOPLEFT; break;
2180         case WMSZ_TOPRIGHT:    dir = _NET_WM_MOVERESIZE_SIZE_TOPRIGHT; break;
2181         case WMSZ_BOTTOM:      dir = _NET_WM_MOVERESIZE_SIZE_BOTTOM; break;
2182         case WMSZ_BOTTOMLEFT:  dir = _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT; break;
2183         case WMSZ_BOTTOMRIGHT: dir = _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT; break;
2184         default:               dir = _NET_WM_MOVERESIZE_SIZE_KEYBOARD; break;
2185         }
2186         break;
2187
2188     case SC_KEYMENU:
2189         /* prevent a simple ALT press+release from activating the system menu,
2190          * as that can get confusing on managed windows */
2191         if ((WCHAR)lparam) return -1;  /* got an explicit char */
2192         if (GetMenu( hwnd )) return -1;  /* window has a real menu */
2193         if (!(GetWindowLongW( hwnd, GWL_STYLE ) & WS_SYSMENU)) return -1;  /* no system menu */
2194         TRACE( "ignoring SC_KEYMENU wp %lx lp %lx\n", wparam, lparam );
2195         return 0;
2196
2197     default:
2198         return -1;
2199     }
2200
2201     if (IsZoomed(hwnd)) return -1;
2202
2203     if (!is_netwm_supported( display, x11drv_atom(_NET_WM_MOVERESIZE) ))
2204     {
2205         TRACE( "_NET_WM_MOVERESIZE not supported\n" );
2206         return -1;
2207     }
2208
2209     dwPoint = GetMessagePos();
2210     x = (short)LOWORD(dwPoint);
2211     y = (short)HIWORD(dwPoint);
2212
2213     TRACE("hwnd %p, x %d, y %d, dir %d\n", hwnd, x, y, dir);
2214
2215     xev.xclient.type = ClientMessage;
2216     xev.xclient.window = X11DRV_get_whole_window(hwnd);
2217     xev.xclient.message_type = x11drv_atom(_NET_WM_MOVERESIZE);
2218     xev.xclient.serial = 0;
2219     xev.xclient.display = display;
2220     xev.xclient.send_event = True;
2221     xev.xclient.format = 32;
2222     xev.xclient.data.l[0] = x; /* x coord */
2223     xev.xclient.data.l[1] = y; /* y coord */
2224     xev.xclient.data.l[2] = dir; /* direction */
2225     xev.xclient.data.l[3] = 1; /* button */
2226     xev.xclient.data.l[4] = 0; /* unused */
2227
2228     /* need to ungrab the pointer that may have been automatically grabbed
2229      * with a ButtonPress event */
2230     wine_tsx11_lock();
2231     XUngrabPointer( display, CurrentTime );
2232     XSendEvent(display, root_window, False, SubstructureNotifyMask, &xev);
2233     wine_tsx11_unlock();
2234     return 0;
2235 }