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