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