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