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