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