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