Avoid holding x11drv lock while calling function that grabs gdi
[wine] / dlls / x11drv / winpos.c
1 /*
2  * Window position related functions.
3  *
4  * Copyright 1993, 1994, 1995, 2001 Alexandre Julliard
5  * Copyright 1995, 1996, 1999 Alex Korobka
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23
24 #include <X11/Xlib.h>
25 #ifdef HAVE_LIBXSHAPE
26 #include <X11/IntrinsicP.h>
27 #include <X11/extensions/shape.h>
28 #endif /* HAVE_LIBXSHAPE */
29 #include <stdarg.h>
30
31 #include "windef.h"
32 #include "winbase.h"
33 #include "wingdi.h"
34 #include "winuser.h"
35 #include "winerror.h"
36 #include "wownt32.h"
37 #include "wine/wingdi16.h"
38
39 #include "x11drv.h"
40 #include "win.h"
41 #include "winpos.h"
42 #include "dce.h"
43 #include "cursoricon.h"
44 #include "nonclient.h"
45
46 #include "wine/server.h"
47 #include "wine/debug.h"
48
49 WINE_DEFAULT_DEBUG_CHANNEL(x11drv);
50
51 #define SWP_AGG_NOGEOMETRYCHANGE \
52     (SWP_NOSIZE | SWP_NOMOVE | SWP_NOCLIENTSIZE | SWP_NOCLIENTMOVE)
53 #define SWP_AGG_NOPOSCHANGE \
54     (SWP_AGG_NOGEOMETRYCHANGE | SWP_NOZORDER)
55 #define SWP_AGG_STATUSFLAGS \
56     (SWP_AGG_NOPOSCHANGE | SWP_FRAMECHANGED | SWP_HIDEWINDOW | SWP_SHOWWINDOW)
57
58 #define SWP_EX_NOCOPY       0x0001
59 #define SWP_EX_PAINTSELF    0x0002
60 #define SWP_EX_NONCLIENT    0x0004
61
62 #define HAS_THICKFRAME(style,exStyle) \
63     (((style) & WS_THICKFRAME) && \
64      !(((style) & (WS_DLGFRAME|WS_BORDER)) == WS_DLGFRAME))
65
66 #define ON_LEFT_BORDER(hit) \
67  (((hit) == HTLEFT) || ((hit) == HTTOPLEFT) || ((hit) == HTBOTTOMLEFT))
68 #define ON_RIGHT_BORDER(hit) \
69  (((hit) == HTRIGHT) || ((hit) == HTTOPRIGHT) || ((hit) == HTBOTTOMRIGHT))
70 #define ON_TOP_BORDER(hit) \
71  (((hit) == HTTOP) || ((hit) == HTTOPLEFT) || ((hit) == HTTOPRIGHT))
72 #define ON_BOTTOM_BORDER(hit) \
73  (((hit) == HTBOTTOM) || ((hit) == HTBOTTOMLEFT) || ((hit) == HTBOTTOMRIGHT))
74
75
76 /***********************************************************************
77  *              clip_children
78  *
79  * Clip all children of a given window out of the visible region
80  */
81 static int clip_children( HWND parent, HWND last, HRGN hrgn, int whole_window )
82 {
83     HWND *list;
84     WND *ptr;
85     HRGN rectRgn;
86     int i, x, y, ret = SIMPLEREGION;
87
88     /* first check if we have anything to do */
89     if (!(list = WIN_ListChildren( parent ))) return ret;
90
91     if (whole_window)
92     {
93         WND *win = WIN_FindWndPtr( parent );
94         x = win->rectWindow.left - win->rectClient.left;
95         y = win->rectWindow.top - win->rectClient.top;
96         WIN_ReleaseWndPtr( win );
97     }
98     else x = y = 0;
99
100     rectRgn = CreateRectRgn( 0, 0, 0, 0 );
101
102     for (i = 0; list[i] && list[i] != last; i++)
103     {
104         if (!(ptr = WIN_FindWndPtr( list[i] ))) continue;
105         if ((ptr->dwStyle & WS_VISIBLE) && !(ptr->dwExStyle & WS_EX_TRANSPARENT))
106         {
107             SetRectRgn( rectRgn, ptr->rectWindow.left + x, ptr->rectWindow.top + y,
108                         ptr->rectWindow.right + x, ptr->rectWindow.bottom + y );
109             if ((ret = CombineRgn( hrgn, hrgn, rectRgn, RGN_DIFF )) == NULLREGION)
110             {
111                 WIN_ReleaseWndPtr( ptr );
112                 break;  /* no need to go on, region is empty */
113             }
114         }
115         WIN_ReleaseWndPtr( ptr );
116     }
117     DeleteObject( rectRgn );
118     HeapFree( GetProcessHeap(), 0, list );
119     return ret;
120 }
121
122
123 /***********************************************************************
124  *              get_server_visible_region
125  */
126 static HRGN get_server_visible_region( HWND hwnd, HWND top, UINT flags )
127 {
128     RGNDATA *data;
129     HRGN ret = 0;
130     size_t size = 256;
131     BOOL retry = FALSE;
132
133     do
134     {
135         if (!(data = HeapAlloc( GetProcessHeap(), 0, sizeof(*data) + size - 1 ))) return 0;
136         SERVER_START_REQ( get_visible_region )
137         {
138             req->window  = hwnd;
139             req->top_win = top;
140             req->flags   = flags;
141             wine_server_set_reply( req, data->Buffer, size );
142             if (!wine_server_call_err( req ))
143             {
144                 if (reply->total_size <= size)
145                 {
146                     size_t reply_size = wine_server_reply_size( reply );
147                     data->rdh.dwSize   = sizeof(data->rdh);
148                     data->rdh.iType    = RDH_RECTANGLES;
149                     data->rdh.nCount   = reply_size / sizeof(RECT);
150                     data->rdh.nRgnSize = reply_size;
151                     ret = ExtCreateRegion( NULL, size, data );
152                     retry = FALSE;
153                 }
154                 else
155                 {
156                     size = reply->total_size;
157                     retry = TRUE;
158                 }
159             }
160         }
161         SERVER_END_REQ;
162         HeapFree( GetProcessHeap(), 0, data );
163     } while (retry);
164     return ret;
165 }
166
167
168 /***********************************************************************
169  *              get_covered_region
170  *
171  * Compute the portion of 'rgn' that is covered by non-clipped siblings.
172  * This is the area that is covered from X point of view, but may still need
173  * to be exposed.
174  * 'rgn' must be relative to the client area of the parent of 'win'.
175  */
176 static int get_covered_region( WND *win, HRGN rgn )
177 {
178     HRGN tmp;
179     int ret;
180     WND *parent, *ptr = WIN_FindWndPtr( win->hwndSelf );
181     int xoffset = 0, yoffset = 0;
182
183     tmp = CreateRectRgn( 0, 0, 0, 0 );
184     CombineRgn( tmp, rgn, 0, RGN_COPY );
185
186     /* to make things easier we actually build the uncovered
187      * area by removing all siblings and then we subtract that
188      * from the total region to get the covered area */
189     for (;;)
190     {
191         if (!(ptr->dwStyle & WS_CLIPSIBLINGS))
192         {
193             if (clip_children( ptr->parent, ptr->hwndSelf, tmp, FALSE ) == NULLREGION) break;
194         }
195         if (!(parent = WIN_FindWndPtr( ptr->parent ))) break;
196         WIN_ReleaseWndPtr( ptr );
197         ptr = parent;
198         OffsetRgn( tmp, ptr->rectClient.left, ptr->rectClient.top );
199         xoffset += ptr->rectClient.left;
200         yoffset += ptr->rectClient.top;
201     }
202     WIN_ReleaseWndPtr( ptr );
203     /* make it relative to the target window again */
204     OffsetRgn( tmp, -xoffset, -yoffset );
205
206     /* now subtract the computed region from the original one */
207     ret = CombineRgn( rgn, rgn, tmp, RGN_DIFF );
208     DeleteObject( tmp );
209     return ret;
210 }
211
212
213 /***********************************************************************
214  *              expose_window
215  *
216  * Expose a region of a given window.
217  */
218 static void expose_window( HWND hwnd, RECT *rect, HRGN rgn, int flags )
219 {
220     POINT offset;
221     HWND top = 0;
222     HWND *list;
223     int i;
224
225     /* find the top most parent that doesn't clip children or siblings and
226      * invalidate the area on its parent, including all children */
227     if ((list = WIN_ListParents( hwnd )))
228     {
229         HWND current = hwnd;
230         LONG style = GetWindowLongW( hwnd, GWL_STYLE );
231         for (i = 0; list[i] && list[i] != GetDesktopWindow(); i++)
232         {
233             if (!(style & WS_CLIPSIBLINGS)) top = current;
234             style = GetWindowLongW( list[i], GWL_STYLE );
235             if (!(style & WS_CLIPCHILDREN)) top = current;
236             current = list[i];
237         }
238
239         if (top)
240         {
241             /* find the parent of the top window, reusing the parent list */
242             if (top == hwnd) i = 0;
243             else
244             {
245                 for (i = 0; list[i]; i++) if (list[i] == top) break;
246                 if (list[i] && list[i+1]) i++;
247             }
248             if (list[i] != GetDesktopWindow()) top = list[i];
249             flags &= ~RDW_FRAME;  /* parent will invalidate children frame anyway */
250             flags |= RDW_ALLCHILDREN;
251         }
252         HeapFree( GetProcessHeap(), 0, list );
253     }
254
255     if (!top) top = hwnd;
256
257     /* make coords relative to top */
258     offset.x = offset.y = 0;
259     MapWindowPoints( hwnd, top, &offset, 1 );
260
261     if (rect)
262     {
263         OffsetRect( rect, offset.x, offset.y );
264         RedrawWindow( top, rect, 0, flags );
265     }
266     else
267     {
268         OffsetRgn( rgn, offset.x, offset.y );
269         RedrawWindow( top, NULL, rgn, flags );
270     }
271 }
272
273
274 /***********************************************************************
275  *              expose_covered_parent_area
276  *
277  * Expose the parent area that has been uncovered by moving/hiding a
278  * given window, but that is still covered by other siblings (the area
279  * not covered by siblings will be exposed automatically by X).
280  */
281 static void expose_covered_parent_area( WND *win, const RECT *old_rect )
282 {
283     int ret = SIMPLEREGION;
284     HRGN hrgn = CreateRectRgnIndirect( old_rect );
285
286     if (win->dwStyle & WS_VISIBLE)
287     {
288         HRGN tmp = CreateRectRgnIndirect( &win->rectWindow );
289         ret = CombineRgn( hrgn, hrgn, tmp, RGN_DIFF );
290         DeleteObject( tmp );
291     }
292
293     if (ret != NULLREGION)
294     {
295         if (get_covered_region( win, hrgn ) != NULLREGION)
296             expose_window( win->parent, NULL, hrgn, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN );
297     }
298     DeleteObject( hrgn );
299 }
300
301
302 /***********************************************************************
303  *              expose_covered_window_area
304  *
305  * Expose the area of a window that is covered by other siblings.
306  */
307 static void expose_covered_window_area( WND *win, const RECT *old_client_rect, BOOL frame )
308 {
309     HRGN hrgn;
310     int ret = SIMPLEREGION;
311
312     if (frame)
313         hrgn = CreateRectRgn( win->rectWindow.left - win->rectClient.left,
314                               win->rectWindow.top - win->rectClient.top,
315                               win->rectWindow.right - win->rectWindow.left,
316                               win->rectWindow.bottom - win->rectWindow.top );
317     else
318         hrgn = CreateRectRgn( 0, 0,
319                               win->rectClient.right - win->rectClient.left,
320                               win->rectClient.bottom - win->rectClient.top );
321
322     /* if the client rect didn't move we don't need to repaint it all */
323     if (old_client_rect->left == win->rectClient.left &&
324         old_client_rect->top == win->rectClient.top)
325     {
326         RECT rc;
327
328         if (IntersectRect( &rc, old_client_rect, &win->rectClient ))
329         {
330             HRGN tmp;
331             /* subtract the unchanged client area from the region to expose */
332             OffsetRect( &rc, -win->rectClient.left, -win->rectClient.top );
333             if ((tmp = CreateRectRgnIndirect( &rc )))
334             {
335                 ret = CombineRgn( hrgn, hrgn, tmp, RGN_DIFF );
336                 DeleteObject( tmp );
337             }
338         }
339     }
340
341     if (ret != NULLREGION)
342     {
343         if (get_covered_region( win, hrgn ) != NULLREGION)
344             expose_window( win->hwndSelf, NULL, hrgn,
345                            RDW_INVALIDATE | RDW_ERASE | RDW_FRAME | RDW_ALLCHILDREN );
346     }
347
348     DeleteObject( hrgn );
349 }
350
351
352 /***********************************************************************
353  *           X11DRV_Expose
354  */
355 void X11DRV_Expose( HWND hwnd, XExposeEvent *event )
356 {
357     RECT rect;
358     struct x11drv_win_data *data;
359     int flags = RDW_INVALIDATE | RDW_ERASE;
360     WND *win;
361
362     TRACE( "win %p (%lx) %d,%d %dx%d\n",
363            hwnd, event->window, event->x, event->y, event->width, event->height );
364
365     rect.left   = event->x;
366     rect.top    = event->y;
367     rect.right  = rect.left + event->width;
368     rect.bottom = rect.top + event->height;
369
370     if (!(win = WIN_GetPtr( hwnd ))) return;
371     data = win->pDriverData;
372
373     if (event->window != data->client_window)  /* whole window or icon window */
374     {
375         flags |= RDW_FRAME;
376         /* make position relative to client area instead of window */
377         OffsetRect( &rect, -data->client_rect.left, -data->client_rect.top );
378     }
379     WIN_ReleasePtr( win );
380
381     expose_window( hwnd, &rect, 0, flags );
382 }
383
384
385 /***********************************************************************
386  *              GetDC (X11DRV.@)
387  *
388  * Set the drawable, origin and dimensions for the DC associated to
389  * a given window.
390  */
391 BOOL X11DRV_GetDC( HWND hwnd, HDC hdc, HRGN hrgn, DWORD flags )
392 {
393     WND *win = WIN_GetPtr( hwnd );
394     HWND top = 0;
395     X11DRV_WND_DATA *data = win->pDriverData;
396     struct x11drv_escape_set_drawable escape;
397
398     escape.mode = IncludeInferiors;
399     /* don't clip siblings if using parent clip region */
400     if (flags & DCX_PARENTCLIP) flags &= ~DCX_CLIPSIBLINGS;
401
402     top = GetAncestor( hwnd, GA_ROOT );
403     if (!top) top = GetDesktopWindow();
404
405     if (top != hwnd)
406     {
407         escape.org.x = escape.org.y = 0;
408         if (flags & DCX_WINDOW)
409         {
410             escape.org.x = win->rectWindow.left - win->rectClient.left;
411             escape.org.y = win->rectWindow.top - win->rectClient.top;
412         }
413         MapWindowPoints( hwnd, top, &escape.org, 1 );
414         escape.drawable_org.x = escape.drawable_org.y = 0;
415         MapWindowPoints( top, 0, &escape.drawable_org, 1 );
416         escape.drawable = X11DRV_get_client_window( top );
417     }
418     else
419     {
420         if (IsIconic( hwnd ))
421         {
422             escape.drawable = data->icon_window ? data->icon_window : data->whole_window;
423             escape.org.x = 0;
424             escape.org.y = 0;
425             escape.drawable_org = escape.org;
426         }
427         else if (flags & DCX_WINDOW)
428         {
429             escape.drawable = data->whole_window;
430             escape.drawable_org.x = data->whole_rect.left;
431             escape.drawable_org.y = data->whole_rect.top;
432             escape.org.x = win->rectWindow.left - data->whole_rect.left;
433             escape.org.y = win->rectWindow.top - data->whole_rect.top;
434         }
435         else
436         {
437             escape.drawable = data->client_window;
438             escape.drawable_org.x = win->rectClient.left;
439             escape.drawable_org.y = win->rectClient.top;
440             escape.org.x = 0;
441             escape.org.y = 0;
442         }
443     }
444
445     escape.code = X11DRV_SET_DRAWABLE;
446     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
447
448     if (flags & (DCX_EXCLUDERGN | DCX_INTERSECTRGN) ||
449         SetHookFlags16( HDC_16(hdc), DCHF_VALIDATEVISRGN ))  /* DC was dirty */
450     {
451         /* need to recompute the visible region */
452         HRGN visRgn = get_server_visible_region( hwnd, top, flags );
453
454         if (flags & (DCX_EXCLUDERGN | DCX_INTERSECTRGN))
455             CombineRgn( visRgn, visRgn, hrgn, (flags & DCX_INTERSECTRGN) ? RGN_AND : RGN_DIFF );
456
457         SelectVisRgn16( HDC_16(hdc), HRGN_16(visRgn) );
458         DeleteObject( visRgn );
459     }
460
461     WIN_ReleasePtr( win );
462     return TRUE;
463 }
464
465
466 /***********************************************************************
467  *              ReleaseDC (X11DRV.@)
468  */
469 void X11DRV_ReleaseDC( HWND hwnd, HDC hdc )
470 {
471     struct x11drv_escape_set_drawable escape;
472
473     escape.code = X11DRV_SET_DRAWABLE;
474     escape.drawable = root_window;
475     escape.mode = IncludeInferiors;
476     escape.org.x = escape.org.y = 0;
477     escape.drawable_org.x = escape.drawable_org.y = 0;
478
479     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
480 }
481
482
483 /***********************************************************************
484  *           SWP_DoWinPosChanging
485  */
486 static BOOL SWP_DoWinPosChanging( WINDOWPOS* pWinpos, RECT* pNewWindowRect, RECT* pNewClientRect )
487 {
488     WND *wndPtr;
489
490     /* Send WM_WINDOWPOSCHANGING message */
491
492     if (!(pWinpos->flags & SWP_NOSENDCHANGING))
493         SendMessageW( pWinpos->hwnd, WM_WINDOWPOSCHANGING, 0, (LPARAM)pWinpos );
494
495     if (!(wndPtr = WIN_GetPtr( pWinpos->hwnd )) || wndPtr == WND_OTHER_PROCESS) return FALSE;
496
497     /* Calculate new position and size */
498
499     *pNewWindowRect = wndPtr->rectWindow;
500     *pNewClientRect = (wndPtr->dwStyle & WS_MINIMIZE) ? wndPtr->rectWindow
501                                                     : wndPtr->rectClient;
502
503     if (!(pWinpos->flags & SWP_NOSIZE))
504     {
505         pNewWindowRect->right  = pNewWindowRect->left + pWinpos->cx;
506         pNewWindowRect->bottom = pNewWindowRect->top + pWinpos->cy;
507     }
508     if (!(pWinpos->flags & SWP_NOMOVE))
509     {
510         pNewWindowRect->left    = pWinpos->x;
511         pNewWindowRect->top     = pWinpos->y;
512         pNewWindowRect->right  += pWinpos->x - wndPtr->rectWindow.left;
513         pNewWindowRect->bottom += pWinpos->y - wndPtr->rectWindow.top;
514
515         OffsetRect( pNewClientRect, pWinpos->x - wndPtr->rectWindow.left,
516                                     pWinpos->y - wndPtr->rectWindow.top );
517     }
518     pWinpos->flags |= SWP_NOCLIENTMOVE | SWP_NOCLIENTSIZE;
519     WIN_ReleasePtr( wndPtr );
520     return TRUE;
521 }
522
523 /***********************************************************************
524  *           SWP_DoNCCalcSize
525  */
526 static UINT SWP_DoNCCalcSize( WINDOWPOS* pWinpos, RECT* pNewWindowRect, RECT* pNewClientRect )
527 {
528     UINT wvrFlags = 0;
529     WND *wndPtr;
530
531     if (!(wndPtr = WIN_GetPtr( pWinpos->hwnd )) || wndPtr == WND_OTHER_PROCESS) return 0;
532
533       /* Send WM_NCCALCSIZE message to get new client area */
534     if( (pWinpos->flags & (SWP_FRAMECHANGED | SWP_NOSIZE)) != SWP_NOSIZE )
535     {
536         NCCALCSIZE_PARAMS params;
537         WINDOWPOS winposCopy;
538
539         params.rgrc[0] = *pNewWindowRect;
540         params.rgrc[1] = wndPtr->rectWindow;
541         params.rgrc[2] = wndPtr->rectClient;
542         params.lppos = &winposCopy;
543         winposCopy = *pWinpos;
544         WIN_ReleasePtr( wndPtr );
545
546         wvrFlags = SendMessageW( pWinpos->hwnd, WM_NCCALCSIZE, TRUE, (LPARAM)&params );
547
548         TRACE( "(%ld,%ld)-(%ld,%ld)\n", params.rgrc[0].left, params.rgrc[0].top,
549                params.rgrc[0].right, params.rgrc[0].bottom );
550
551         /* If the application send back garbage, ignore it */
552         if (params.rgrc[0].left <= params.rgrc[0].right &&
553             params.rgrc[0].top <= params.rgrc[0].bottom)
554             *pNewClientRect = params.rgrc[0];
555
556          /* FIXME: WVR_ALIGNxxx */
557
558         if (!(wndPtr = WIN_GetPtr( pWinpos->hwnd )) || wndPtr == WND_OTHER_PROCESS) return 0;
559
560         if( pNewClientRect->left != wndPtr->rectClient.left ||
561             pNewClientRect->top != wndPtr->rectClient.top )
562             pWinpos->flags &= ~SWP_NOCLIENTMOVE;
563
564         if( (pNewClientRect->right - pNewClientRect->left !=
565              wndPtr->rectClient.right - wndPtr->rectClient.left) ||
566             (pNewClientRect->bottom - pNewClientRect->top !=
567              wndPtr->rectClient.bottom - wndPtr->rectClient.top) )
568             pWinpos->flags &= ~SWP_NOCLIENTSIZE;
569     }
570     else
571     {
572         if (!(pWinpos->flags & SWP_NOMOVE) &&
573             (pNewClientRect->left != wndPtr->rectClient.left ||
574              pNewClientRect->top != wndPtr->rectClient.top))
575             pWinpos->flags &= ~SWP_NOCLIENTMOVE;
576     }
577     WIN_ReleasePtr( wndPtr );
578     return wvrFlags;
579 }
580
581
582 /***********************************************************************
583  *           SWP_DoOwnedPopups
584  *
585  * fix Z order taking into account owned popups -
586  * basically we need to maintain them above the window that owns them
587  *
588  * FIXME: hide/show owned popups when owner visibility changes.
589  */
590 static HWND SWP_DoOwnedPopups(HWND hwnd, HWND hwndInsertAfter)
591 {
592     HWND *list = NULL;
593     HWND owner = GetWindow( hwnd, GW_OWNER );
594     LONG style = GetWindowLongW( hwnd, GWL_STYLE );
595
596     WARN("(%p) hInsertAfter = %p\n", hwnd, hwndInsertAfter );
597
598     if ((style & WS_POPUP) && owner)
599     {
600         /* make sure this popup stays above the owner */
601
602         HWND hwndLocalPrev = HWND_TOP;
603
604         if( hwndInsertAfter != HWND_TOP )
605         {
606             if ((list = WIN_ListChildren( GetDesktopWindow() )))
607             {
608                 int i;
609                 for (i = 0; list[i]; i++)
610                 {
611                     if (list[i] == owner) break;
612                     if (list[i] != hwnd) hwndLocalPrev = list[i];
613                     if (hwndLocalPrev == hwndInsertAfter) break;
614                 }
615                 hwndInsertAfter = hwndLocalPrev;
616             }
617         }
618     }
619     else if (style & WS_CHILD) return hwndInsertAfter;
620
621     if (!list) list = WIN_ListChildren( GetDesktopWindow() );
622     if (list)
623     {
624         int i;
625         for (i = 0; list[i]; i++)
626         {
627             if (list[i] == hwnd) break;
628             if ((GetWindowLongW( list[i], GWL_STYLE ) & WS_POPUP) &&
629                 GetWindow( list[i], GW_OWNER ) == hwnd)
630             {
631                 SetWindowPos( list[i], hwndInsertAfter, 0, 0, 0, 0,
632                               SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE |
633                               SWP_NOSENDCHANGING | SWP_DEFERERASE );
634                 hwndInsertAfter = list[i];
635             }
636         }
637         HeapFree( GetProcessHeap(), 0, list );
638     }
639
640     return hwndInsertAfter;
641 }
642
643
644 /* fix redundant flags and values in the WINDOWPOS structure */
645 static BOOL fixup_flags( WINDOWPOS *winpos )
646 {
647     WND *wndPtr = WIN_GetPtr( winpos->hwnd );
648     BOOL ret = TRUE;
649
650     if (!wndPtr || wndPtr == WND_OTHER_PROCESS)
651     {
652         SetLastError( ERROR_INVALID_WINDOW_HANDLE );
653         return FALSE;
654     }
655     winpos->hwnd = wndPtr->hwndSelf;  /* make it a full handle */
656
657     /* Finally make sure that all coordinates are valid */
658     if (winpos->x < -32768) winpos->x = -32768;
659     else if (winpos->x > 32767) winpos->x = 32767;
660     if (winpos->y < -32768) winpos->y = -32768;
661     else if (winpos->y > 32767) winpos->y = 32767;
662
663     if (winpos->cx < 0) winpos->cx = 0;
664     else if (winpos->cx > 32767) winpos->cx = 32767;
665     if (winpos->cy < 0) winpos->cy = 0;
666     else if (winpos->cy > 32767) winpos->cy = 32767;
667
668     if (wndPtr->dwStyle & WS_VISIBLE) winpos->flags &= ~SWP_SHOWWINDOW;
669     else
670     {
671         winpos->flags &= ~SWP_HIDEWINDOW;
672         if (!(winpos->flags & SWP_SHOWWINDOW)) winpos->flags |= SWP_NOREDRAW;
673     }
674
675     if ((wndPtr->rectWindow.right - wndPtr->rectWindow.left == winpos->cx) &&
676         (wndPtr->rectWindow.bottom - wndPtr->rectWindow.top == winpos->cy))
677         winpos->flags |= SWP_NOSIZE;    /* Already the right size */
678
679     if ((wndPtr->rectWindow.left == winpos->x) && (wndPtr->rectWindow.top == winpos->y))
680         winpos->flags |= SWP_NOMOVE;    /* Already the right position */
681
682     if (winpos->hwnd == GetActiveWindow())
683         winpos->flags |= SWP_NOACTIVATE;   /* Already active */
684     else if ((wndPtr->dwStyle & (WS_POPUP | WS_CHILD)) != WS_CHILD)
685     {
686         if (!(winpos->flags & SWP_NOACTIVATE)) /* Bring to the top when activating */
687         {
688             winpos->flags &= ~SWP_NOZORDER;
689             winpos->hwndInsertAfter = HWND_TOP;
690         }
691     }
692
693     /* Check hwndInsertAfter */
694     if (winpos->flags & SWP_NOZORDER) goto done;
695
696     /* fix sign extension */
697     if (winpos->hwndInsertAfter == (HWND)0xffff) winpos->hwndInsertAfter = HWND_TOPMOST;
698     else if (winpos->hwndInsertAfter == (HWND)0xfffe) winpos->hwndInsertAfter = HWND_NOTOPMOST;
699
700       /* FIXME: TOPMOST not supported yet */
701     if ((winpos->hwndInsertAfter == HWND_TOPMOST) ||
702         (winpos->hwndInsertAfter == HWND_NOTOPMOST)) winpos->hwndInsertAfter = HWND_TOP;
703
704     /* hwndInsertAfter must be a sibling of the window */
705     if (winpos->hwndInsertAfter == HWND_TOP)
706     {
707         if (GetWindow(winpos->hwnd, GW_HWNDFIRST) == winpos->hwnd)
708             winpos->flags |= SWP_NOZORDER;
709     }
710     else if (winpos->hwndInsertAfter == HWND_BOTTOM)
711     {
712         if (GetWindow(winpos->hwnd, GW_HWNDLAST) == winpos->hwnd)
713             winpos->flags |= SWP_NOZORDER;
714     }
715     else
716     {
717         if (GetAncestor( winpos->hwndInsertAfter, GA_PARENT ) != wndPtr->parent) ret = FALSE;
718         else
719         {
720             /* don't need to change the Zorder of hwnd if it's already inserted
721              * after hwndInsertAfter or when inserting hwnd after itself.
722              */
723             if ((winpos->hwnd == winpos->hwndInsertAfter) ||
724                 (winpos->hwnd == GetWindow( winpos->hwndInsertAfter, GW_HWNDNEXT )))
725                 winpos->flags |= SWP_NOZORDER;
726         }
727     }
728  done:
729     WIN_ReleasePtr( wndPtr );
730     return ret;
731 }
732
733
734 /***********************************************************************
735  *              set_visible_style
736  *
737  * Set/clear the WS_VISIBLE style of a window and map/unmap the X window.
738  */
739 static void set_visible_style( HWND hwnd, BOOL set )
740 {
741     WND *win;
742
743     if (!(win = WIN_GetPtr( hwnd ))) return;
744     if (win == WND_OTHER_PROCESS) return;
745
746     TRACE( "hwnd %p (%lx) set %d visible %d empty %d\n",
747            hwnd, get_whole_window(win),
748            set, (win->dwStyle & WS_VISIBLE) != 0, IsRectEmpty(&win->rectWindow) );
749
750     if (set)
751     {
752         if (win->dwStyle & WS_VISIBLE) goto done;
753         WIN_SetStyle( hwnd, win->dwStyle | WS_VISIBLE );
754         if (X11DRV_is_window_rect_mapped( &win->rectWindow ) &&
755             get_whole_window(win) && is_window_top_level(win))
756         {
757             Display *display = thread_display();
758             X11DRV_sync_window_style( display, win );
759             X11DRV_set_wm_hints( display, win );
760             TRACE( "mapping win %p\n", hwnd );
761             wine_tsx11_lock();
762             XMapWindow( display, get_whole_window(win) );
763             wine_tsx11_unlock();
764         }
765     }
766     else
767     {
768         if (!(win->dwStyle & WS_VISIBLE)) goto done;
769         WIN_SetStyle( hwnd, win->dwStyle & ~WS_VISIBLE );
770         if (X11DRV_is_window_rect_mapped( &win->rectWindow ) &&
771             get_whole_window(win) && is_window_top_level(win))
772         {
773             TRACE( "unmapping win %p\n", hwnd );
774             wine_tsx11_lock();
775             XUnmapWindow( thread_display(), get_whole_window(win) );
776             wine_tsx11_unlock();
777         }
778     }
779  done:
780     WIN_ReleasePtr( win );
781 }
782
783
784 /***********************************************************************
785  *              SetWindowStyle   (X11DRV.@)
786  *
787  * Update the X state of a window to reflect a style change
788  */
789 void X11DRV_SetWindowStyle( HWND hwnd, LONG oldStyle )
790 {
791     Display *display = thread_display();
792     WND *wndPtr;
793     LONG changed;
794
795     if (hwnd == GetDesktopWindow()) return;
796     if (!(wndPtr = WIN_GetPtr( hwnd ))) return;
797     if (wndPtr == WND_OTHER_PROCESS) return;
798
799     changed = wndPtr->dwStyle ^ oldStyle;
800
801     if (changed & WS_VISIBLE)
802     {
803         if (X11DRV_is_window_rect_mapped( &wndPtr->rectWindow ))
804         {
805             if (wndPtr->dwStyle & WS_VISIBLE)
806             {
807                 TRACE( "mapping win %p\n", hwnd );
808                 if (is_window_top_level(wndPtr))
809                 {
810                     X11DRV_sync_window_style( display, wndPtr );
811                     X11DRV_set_wm_hints( display, wndPtr );
812                 }
813                 wine_tsx11_lock();
814                 XMapWindow( display, get_whole_window(wndPtr) );
815                 wine_tsx11_unlock();
816             }
817             else if (!is_window_top_level(wndPtr))  /* don't unmap managed windows */
818             {
819                 TRACE( "unmapping win %p\n", hwnd );
820                 wine_tsx11_lock();
821                 XUnmapWindow( display, get_whole_window(wndPtr) );
822                 wine_tsx11_unlock();
823             }
824         }
825     }
826
827     if (changed & WS_DISABLED)
828     {
829         if (wndPtr->dwExStyle & WS_EX_MANAGED)
830         {
831             XWMHints *wm_hints;
832             wine_tsx11_lock();
833             if (!(wm_hints = XGetWMHints( display, get_whole_window(wndPtr) )))
834                 wm_hints = XAllocWMHints();
835             if (wm_hints)
836             {
837                 wm_hints->flags |= InputHint;
838                 wm_hints->input = !(wndPtr->dwStyle & WS_DISABLED);
839                 XSetWMHints( display, get_whole_window(wndPtr), wm_hints );
840                 XFree(wm_hints);
841             }
842             wine_tsx11_unlock();
843         }
844     }
845     WIN_ReleasePtr(wndPtr);
846 }
847
848
849 /***********************************************************************
850  *              SetWindowPos   (X11DRV.@)
851  */
852 BOOL X11DRV_SetWindowPos( WINDOWPOS *winpos )
853 {
854     WND *wndPtr;
855     RECT newWindowRect, newClientRect;
856     RECT oldWindowRect, oldClientRect;
857     UINT wvrFlags = 0;
858     BOOL bChangePos;
859
860     TRACE( "hwnd %p, after %p, swp %d,%d %dx%d flags %08x\n",
861            winpos->hwnd, winpos->hwndInsertAfter, winpos->x, winpos->y,
862            winpos->cx, winpos->cy, winpos->flags);
863
864     bChangePos = !(winpos->flags & SWP_WINE_NOHOSTMOVE);
865     winpos->flags &= ~SWP_WINE_NOHOSTMOVE;
866
867     /* Check window handle */
868     if (winpos->hwnd == GetDesktopWindow()) return FALSE;
869
870     /* First make sure that coordinates are valid for WM_WINDOWPOSCHANGING */
871     if (!(winpos->flags & SWP_NOMOVE))
872     {
873         if (winpos->x < -32768) winpos->x = -32768;
874         else if (winpos->x > 32767) winpos->x = 32767;
875         if (winpos->y < -32768) winpos->y = -32768;
876         else if (winpos->y > 32767) winpos->y = 32767;
877     }
878     if (!(winpos->flags & SWP_NOSIZE))
879     {
880         if (winpos->cx < 0) winpos->cx = 0;
881         else if (winpos->cx > 32767) winpos->cx = 32767;
882         if (winpos->cy < 0) winpos->cy = 0;
883         else if (winpos->cy > 32767) winpos->cy = 32767;
884     }
885
886     if (!SWP_DoWinPosChanging( winpos, &newWindowRect, &newClientRect )) return FALSE;
887
888     /* Fix redundant flags */
889     if (!fixup_flags( winpos )) return FALSE;
890
891     if (!(wndPtr = WIN_FindWndPtr( winpos->hwnd ))) return FALSE;
892
893     TRACE("\tcurrent (%ld,%ld)-(%ld,%ld), style %08x\n",
894           wndPtr->rectWindow.left, wndPtr->rectWindow.top,
895           wndPtr->rectWindow.right, wndPtr->rectWindow.bottom, (unsigned)wndPtr->dwStyle );
896
897     if((winpos->flags & (SWP_NOZORDER | SWP_HIDEWINDOW | SWP_SHOWWINDOW)) != SWP_NOZORDER)
898     {
899         if (GetAncestor( winpos->hwnd, GA_PARENT ) == GetDesktopWindow())
900             winpos->hwndInsertAfter = SWP_DoOwnedPopups( winpos->hwnd, winpos->hwndInsertAfter );
901     }
902
903     /* Common operations */
904
905     wvrFlags = SWP_DoNCCalcSize( winpos, &newWindowRect, &newClientRect );
906
907     if(!(winpos->flags & SWP_NOZORDER) && winpos->hwnd != winpos->hwndInsertAfter)
908     {
909         HWND parent = GetAncestor( winpos->hwnd, GA_PARENT );
910         if (parent) WIN_LinkWindow( winpos->hwnd, parent, winpos->hwndInsertAfter );
911     }
912
913     /* Reset active DCEs */
914
915     if( (((winpos->flags & SWP_AGG_NOPOSCHANGE) != SWP_AGG_NOPOSCHANGE) &&
916          wndPtr->dwStyle & WS_VISIBLE) ||
917         (winpos->flags & (SWP_HIDEWINDOW | SWP_SHOWWINDOW)) )
918     {
919         RECT rect;
920
921         UnionRect(&rect, &newWindowRect, &wndPtr->rectWindow);
922         DCE_InvalidateDCE(wndPtr->hwndSelf, &rect);
923     }
924
925     oldWindowRect = wndPtr->rectWindow;
926     oldClientRect = wndPtr->rectClient;
927
928     /* Find out if we have to redraw the whole client rect */
929
930     if( oldClientRect.bottom - oldClientRect.top ==
931         newClientRect.bottom - newClientRect.top ) wvrFlags &= ~WVR_VREDRAW;
932
933     if( oldClientRect.right - oldClientRect.left ==
934         newClientRect.right - newClientRect.left ) wvrFlags &= ~WVR_HREDRAW;
935
936     /* FIXME: actually do something with WVR_VALIDRECTS */
937
938     WIN_SetRectangles( winpos->hwnd, &newWindowRect, &newClientRect );
939
940     if (get_whole_window(wndPtr))  /* don't do anything if X window not created yet */
941     {
942         Display *display = thread_display();
943
944         if (!(winpos->flags & SWP_SHOWWINDOW) && (winpos->flags & SWP_HIDEWINDOW))
945         {
946             /* clear the update region */
947             RedrawWindow( winpos->hwnd, NULL, 0, RDW_VALIDATE | RDW_NOFRAME |
948                           RDW_NOERASE | RDW_NOINTERNALPAINT | RDW_ALLCHILDREN );
949             set_visible_style( winpos->hwnd, FALSE );
950         }
951         else if ((wndPtr->dwStyle & WS_VISIBLE) && bChangePos &&
952                  X11DRV_is_window_rect_mapped( &oldWindowRect ) &&
953                  !X11DRV_is_window_rect_mapped( &newWindowRect ))
954         {
955             /* resizing to zero size or off screen -> unmap */
956             TRACE( "unmapping zero size or off-screen win %p\n", winpos->hwnd );
957             wine_tsx11_lock();
958             XUnmapWindow( display, get_whole_window(wndPtr) );
959             wine_tsx11_unlock();
960         }
961
962         if (bChangePos)
963             X11DRV_sync_whole_window_position( display, wndPtr, !(winpos->flags & SWP_NOZORDER) );
964         else
965         {
966             struct x11drv_win_data *data = wndPtr->pDriverData;
967             data->whole_rect = wndPtr->rectWindow;
968             X11DRV_window_to_X_rect( wndPtr, &data->whole_rect );
969         }
970
971         if (X11DRV_sync_client_window_position( display, wndPtr ) ||
972             (winpos->flags & SWP_FRAMECHANGED))
973         {
974             /* if we moved the client area, repaint the whole non-client window */
975             wine_tsx11_lock();
976             XClearArea( display, get_whole_window(wndPtr), 0, 0, 0, 0, True );
977             wine_tsx11_unlock();
978             winpos->flags |= SWP_FRAMECHANGED;
979         }
980         if (winpos->flags & SWP_SHOWWINDOW)
981         {
982             set_visible_style( winpos->hwnd, TRUE );
983         }
984         else if ((wndPtr->dwStyle & WS_VISIBLE) && bChangePos &&
985                  !X11DRV_is_window_rect_mapped( &oldWindowRect ) &&
986                  X11DRV_is_window_rect_mapped( &newWindowRect ))
987         {
988             /* resizing from zero size to non-zero -> map */
989             TRACE( "mapping non zero size or off-screen win %p\n", winpos->hwnd );
990             wine_tsx11_lock();
991             XMapWindow( display, get_whole_window(wndPtr) );
992             wine_tsx11_unlock();
993         }
994         wine_tsx11_lock();
995         XFlush( display );  /* FIXME: should not be necessary */
996         wine_tsx11_unlock();
997     }
998     else  /* no X window, simply toggle the window style */
999     {
1000         if (winpos->flags & SWP_SHOWWINDOW)
1001             set_visible_style( winpos->hwnd, TRUE );
1002         else if (winpos->flags & SWP_HIDEWINDOW)
1003             set_visible_style( winpos->hwnd, FALSE );
1004     }
1005
1006     /* manually expose the areas that X won't expose because they are still covered by something */
1007
1008     if (!(winpos->flags & SWP_SHOWWINDOW))
1009         expose_covered_parent_area( wndPtr, &oldWindowRect );
1010
1011     if (wndPtr->dwStyle & WS_VISIBLE)
1012         expose_covered_window_area( wndPtr, &oldClientRect, winpos->flags & SWP_FRAMECHANGED );
1013
1014     WIN_ReleaseWndPtr(wndPtr);
1015
1016     if (wvrFlags & WVR_REDRAW) RedrawWindow( winpos->hwnd, NULL, 0, RDW_INVALIDATE | RDW_ERASE );
1017
1018     if( winpos->flags & SWP_HIDEWINDOW )
1019         HideCaret(winpos->hwnd);
1020     else if (winpos->flags & SWP_SHOWWINDOW)
1021         ShowCaret(winpos->hwnd);
1022
1023     if (!(winpos->flags & SWP_NOACTIVATE))
1024     {
1025         /* child windows get WM_CHILDACTIVATE message */
1026         if ((GetWindowLongW( winpos->hwnd, GWL_STYLE ) & (WS_CHILD | WS_POPUP)) == WS_CHILD)
1027             SendMessageA( winpos->hwnd, WM_CHILDACTIVATE, 0, 0 );
1028         else
1029             SetForegroundWindow( winpos->hwnd );
1030     }
1031
1032       /* And last, send the WM_WINDOWPOSCHANGED message */
1033
1034     TRACE("\tstatus flags = %04x\n", winpos->flags & SWP_AGG_STATUSFLAGS);
1035
1036     if (((winpos->flags & SWP_AGG_STATUSFLAGS) != SWP_AGG_NOPOSCHANGE))
1037     {
1038         /* WM_WINDOWPOSCHANGED is sent even if SWP_NOSENDCHANGING is set
1039            and always contains final window position.
1040          */
1041         winpos->x = newWindowRect.left;
1042         winpos->y = newWindowRect.top;
1043         winpos->cx = newWindowRect.right - newWindowRect.left;
1044         winpos->cy = newWindowRect.bottom - newWindowRect.top;
1045         SendMessageW( winpos->hwnd, WM_WINDOWPOSCHANGED, 0, (LPARAM)winpos );
1046     }
1047
1048     return TRUE;
1049 }
1050
1051
1052 /***********************************************************************
1053  *           WINPOS_FindIconPos
1054  *
1055  * Find a suitable place for an iconic window.
1056  */
1057 static POINT WINPOS_FindIconPos( WND* wndPtr, POINT pt )
1058 {
1059     RECT rectParent;
1060     HWND *list;
1061     short x, y, xspacing, yspacing;
1062
1063     GetClientRect( wndPtr->parent, &rectParent );
1064     if ((pt.x >= rectParent.left) && (pt.x + GetSystemMetrics(SM_CXICON) < rectParent.right) &&
1065         (pt.y >= rectParent.top) && (pt.y + GetSystemMetrics(SM_CYICON) < rectParent.bottom))
1066         return pt;  /* The icon already has a suitable position */
1067
1068     xspacing = GetSystemMetrics(SM_CXICONSPACING);
1069     yspacing = GetSystemMetrics(SM_CYICONSPACING);
1070
1071     list = WIN_ListChildren( wndPtr->parent );
1072     y = rectParent.bottom;
1073     for (;;)
1074     {
1075         x = rectParent.left;
1076         do
1077         {
1078             /* Check if another icon already occupies this spot */
1079             /* FIXME: this is completely inefficient */
1080             if (list)
1081             {
1082                 int i;
1083                 WND *childPtr;
1084
1085                 for (i = 0; list[i]; i++)
1086                 {
1087                     if (list[i] == wndPtr->hwndSelf) continue;
1088                     if (!IsIconic( list[i] )) continue;
1089                     if (!(childPtr = WIN_FindWndPtr( list[i] ))) continue;
1090                     if ((childPtr->rectWindow.left < x + xspacing) &&
1091                         (childPtr->rectWindow.right >= x) &&
1092                         (childPtr->rectWindow.top <= y) &&
1093                         (childPtr->rectWindow.bottom > y - yspacing))
1094                     {
1095                         WIN_ReleaseWndPtr( childPtr );
1096                         break;  /* There's a window in there */
1097                     }
1098                     WIN_ReleaseWndPtr( childPtr );
1099                 }
1100                 if (list[i])
1101                 {
1102                     /* found something here, try next spot */
1103                     x += xspacing;
1104                     continue;
1105                 }
1106             }
1107
1108             /* No window was found, so it's OK for us */
1109             pt.x = x + (xspacing - GetSystemMetrics(SM_CXICON)) / 2;
1110             pt.y = y - (yspacing + GetSystemMetrics(SM_CYICON)) / 2;
1111             HeapFree( GetProcessHeap(), 0, list );
1112             return pt;
1113
1114         } while(x <= rectParent.right-xspacing);
1115         y -= yspacing;
1116     }
1117 }
1118
1119
1120
1121
1122
1123 UINT WINPOS_MinMaximize( HWND hwnd, UINT cmd, LPRECT rect )
1124 {
1125     WND *wndPtr;
1126     UINT swpFlags = 0;
1127     POINT size;
1128     LONG old_style;
1129     WINDOWPLACEMENT wpl;
1130
1131     TRACE("%p %u\n", hwnd, cmd );
1132
1133     wpl.length = sizeof(wpl);
1134     GetWindowPlacement( hwnd, &wpl );
1135
1136     if (HOOK_CallHooks( WH_CBT, HCBT_MINMAX, (WPARAM)hwnd, cmd, TRUE ))
1137         return SWP_NOSIZE | SWP_NOMOVE;
1138
1139     if (IsIconic( hwnd ))
1140     {
1141         if (cmd == SW_MINIMIZE) return SWP_NOSIZE | SWP_NOMOVE;
1142         if (!SendMessageA( hwnd, WM_QUERYOPEN, 0, 0 )) return SWP_NOSIZE | SWP_NOMOVE;
1143         swpFlags |= SWP_NOCOPYBITS;
1144     }
1145
1146     if (!(wndPtr = WIN_FindWndPtr( hwnd ))) return 0;
1147
1148     size.x = wndPtr->rectWindow.left;
1149     size.y = wndPtr->rectWindow.top;
1150
1151     switch( cmd )
1152     {
1153     case SW_MINIMIZE:
1154         if( wndPtr->dwStyle & WS_MAXIMIZE) wndPtr->flags |= WIN_RESTORE_MAX;
1155         else wndPtr->flags &= ~WIN_RESTORE_MAX;
1156
1157         WIN_SetStyle( hwnd, (wndPtr->dwStyle & ~WS_MAXIMIZE) | WS_MINIMIZE );
1158
1159         X11DRV_set_iconic_state( wndPtr );
1160
1161         wpl.ptMinPosition = WINPOS_FindIconPos( wndPtr, wpl.ptMinPosition );
1162
1163         SetRect( rect, wpl.ptMinPosition.x, wpl.ptMinPosition.y,
1164                  GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON) );
1165         swpFlags |= SWP_NOCOPYBITS;
1166         break;
1167
1168     case SW_MAXIMIZE:
1169         WINPOS_GetMinMaxInfo( hwnd, &size, &wpl.ptMaxPosition, NULL, NULL );
1170
1171         old_style = WIN_SetStyle( hwnd, (wndPtr->dwStyle & ~WS_MINIMIZE) | WS_MAXIMIZE );
1172         if (old_style & WS_MINIMIZE)
1173         {
1174             WINPOS_ShowIconTitle( hwnd, FALSE );
1175             X11DRV_set_iconic_state( wndPtr );
1176         }
1177         SetRect( rect, wpl.ptMaxPosition.x, wpl.ptMaxPosition.y, size.x, size.y );
1178         break;
1179
1180     case SW_RESTORE:
1181         old_style = WIN_SetStyle( hwnd, wndPtr->dwStyle & ~(WS_MINIMIZE|WS_MAXIMIZE) );
1182         if (old_style & WS_MINIMIZE)
1183         {
1184             WINPOS_ShowIconTitle( hwnd, FALSE );
1185             X11DRV_set_iconic_state( wndPtr );
1186
1187             if( wndPtr->flags & WIN_RESTORE_MAX)
1188             {
1189                 /* Restore to maximized position */
1190                 WINPOS_GetMinMaxInfo( hwnd, &size, &wpl.ptMaxPosition, NULL, NULL);
1191                 WIN_SetStyle( hwnd, wndPtr->dwStyle | WS_MAXIMIZE );
1192                 SetRect( rect, wpl.ptMaxPosition.x, wpl.ptMaxPosition.y, size.x, size.y );
1193                 break;
1194             }
1195         }
1196         else if (!(old_style & WS_MAXIMIZE)) break;
1197
1198         /* Restore to normal position */
1199
1200         *rect = wpl.rcNormalPosition;
1201         rect->right -= rect->left;
1202         rect->bottom -= rect->top;
1203
1204         break;
1205     }
1206
1207     WIN_ReleaseWndPtr( wndPtr );
1208     return swpFlags;
1209 }
1210
1211
1212 /***********************************************************************
1213  *              ShowWindow   (X11DRV.@)
1214  */
1215 BOOL X11DRV_ShowWindow( HWND hwnd, INT cmd )
1216 {
1217     WND*        wndPtr = WIN_FindWndPtr( hwnd );
1218     BOOL        wasVisible, showFlag;
1219     RECT        newPos = {0, 0, 0, 0};
1220     UINT        swp = 0;
1221
1222     if (!wndPtr) return FALSE;
1223     hwnd = wndPtr->hwndSelf;  /* make it a full handle */
1224
1225     wasVisible = (wndPtr->dwStyle & WS_VISIBLE) != 0;
1226
1227     TRACE("hwnd=%p, cmd=%d, wasVisible %d\n", hwnd, cmd, wasVisible);
1228
1229     switch(cmd)
1230     {
1231         case SW_HIDE:
1232             if (!wasVisible) goto END;
1233             swp |= SWP_HIDEWINDOW | SWP_NOSIZE | SWP_NOMOVE |
1234                         SWP_NOACTIVATE | SWP_NOZORDER;
1235             break;
1236
1237         case SW_SHOWMINNOACTIVE:
1238             swp |= SWP_NOACTIVATE | SWP_NOZORDER;
1239             /* fall through */
1240         case SW_SHOWMINIMIZED:
1241         case SW_FORCEMINIMIZE: /* FIXME: Does not work if thread is hung. */
1242             swp |= SWP_SHOWWINDOW;
1243             /* fall through */
1244         case SW_MINIMIZE:
1245             swp |= SWP_FRAMECHANGED;
1246             if( !(wndPtr->dwStyle & WS_MINIMIZE) )
1247                  swp |= WINPOS_MinMaximize( hwnd, SW_MINIMIZE, &newPos );
1248             else swp |= SWP_NOSIZE | SWP_NOMOVE;
1249             break;
1250
1251         case SW_SHOWMAXIMIZED: /* same as SW_MAXIMIZE */
1252             swp |= SWP_SHOWWINDOW | SWP_FRAMECHANGED;
1253             if( !(wndPtr->dwStyle & WS_MAXIMIZE) )
1254                  swp |= WINPOS_MinMaximize( hwnd, SW_MAXIMIZE, &newPos );
1255             else swp |= SWP_NOSIZE | SWP_NOMOVE;
1256             break;
1257
1258         case SW_SHOWNA:
1259             swp |= SWP_NOACTIVATE | SWP_NOZORDER;
1260             /* fall through */
1261         case SW_SHOW:
1262             if (wasVisible) goto END;
1263
1264             swp |= SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE;
1265             break;
1266
1267         case SW_SHOWNOACTIVATE:
1268             swp |= SWP_NOACTIVATE | SWP_NOZORDER;
1269             /* fall through */
1270         case SW_SHOWNORMAL:  /* same as SW_NORMAL: */
1271         case SW_SHOWDEFAULT: /* FIXME: should have its own handler */
1272         case SW_RESTORE:
1273             swp |= SWP_SHOWWINDOW | SWP_FRAMECHANGED;
1274
1275             if( wndPtr->dwStyle & (WS_MINIMIZE | WS_MAXIMIZE) )
1276                  swp |= WINPOS_MinMaximize( hwnd, SW_RESTORE, &newPos );
1277             else swp |= SWP_NOSIZE | SWP_NOMOVE;
1278             break;
1279     }
1280
1281     showFlag = (cmd != SW_HIDE);
1282     if (showFlag != wasVisible)
1283     {
1284         SendMessageW( hwnd, WM_SHOWWINDOW, showFlag, 0 );
1285         if (!IsWindow( hwnd )) goto END;
1286     }
1287
1288     /* We can't activate a child window */
1289     if ((wndPtr->dwStyle & WS_CHILD) &&
1290         !(wndPtr->dwExStyle & WS_EX_MDICHILD))
1291         swp |= SWP_NOACTIVATE | SWP_NOZORDER;
1292
1293     SetWindowPos( hwnd, HWND_TOP, newPos.left, newPos.top,
1294                   newPos.right, newPos.bottom, LOWORD(swp) );
1295     if (cmd == SW_HIDE)
1296     {
1297         HWND hFocus;
1298
1299         /* FIXME: This will cause the window to be activated irrespective
1300          * of whether it is owned by the same thread. Has to be done
1301          * asynchronously.
1302          */
1303
1304         if (hwnd == GetActiveWindow())
1305             WINPOS_ActivateOtherWindow(hwnd);
1306
1307         /* Revert focus to parent */
1308         hFocus = GetFocus();
1309         if (hwnd == hFocus || IsChild(hwnd, hFocus))
1310         {
1311             HWND parent = GetAncestor(hwnd, GA_PARENT);
1312             if (parent == GetDesktopWindow()) parent = 0;
1313             SetFocus(parent);
1314         }
1315     }
1316     if (!IsWindow( hwnd )) goto END;
1317     else if( wndPtr->dwStyle & WS_MINIMIZE ) WINPOS_ShowIconTitle( hwnd, TRUE );
1318
1319     if (wndPtr->flags & WIN_NEED_SIZE)
1320     {
1321         /* should happen only in CreateWindowEx() */
1322         int wParam = SIZE_RESTORED;
1323
1324         wndPtr->flags &= ~WIN_NEED_SIZE;
1325         if (wndPtr->dwStyle & WS_MAXIMIZE) wParam = SIZE_MAXIMIZED;
1326         else if (wndPtr->dwStyle & WS_MINIMIZE) wParam = SIZE_MINIMIZED;
1327         SendMessageA( hwnd, WM_SIZE, wParam,
1328                      MAKELONG(wndPtr->rectClient.right-wndPtr->rectClient.left,
1329                             wndPtr->rectClient.bottom-wndPtr->rectClient.top));
1330         SendMessageA( hwnd, WM_MOVE, 0,
1331                    MAKELONG(wndPtr->rectClient.left, wndPtr->rectClient.top) );
1332     }
1333
1334 END:
1335     WIN_ReleaseWndPtr(wndPtr);
1336     return wasVisible;
1337 }
1338
1339
1340 /**********************************************************************
1341  *              X11DRV_MapNotify
1342  */
1343 void X11DRV_MapNotify( HWND hwnd, XMapEvent *event )
1344 {
1345     HWND hwndFocus = GetFocus();
1346     WND *win;
1347
1348     if (!(win = WIN_GetPtr( hwnd ))) return;
1349
1350     if ((win->dwStyle & WS_VISIBLE) &&
1351         (win->dwStyle & WS_MINIMIZE) &&
1352         (win->dwExStyle & WS_EX_MANAGED))
1353     {
1354         int x, y;
1355         unsigned int width, height, border, depth;
1356         Window root, top;
1357         RECT rect;
1358         LONG style = (win->dwStyle & ~(WS_MINIMIZE|WS_MAXIMIZE)) | WS_VISIBLE;
1359
1360         /* FIXME: hack */
1361         wine_tsx11_lock();
1362         XGetGeometry( event->display, get_whole_window(win), &root, &x, &y, &width, &height,
1363                         &border, &depth );
1364         XTranslateCoordinates( event->display, get_whole_window(win), root, 0, 0, &x, &y, &top );
1365         wine_tsx11_unlock();
1366         rect.left   = x;
1367         rect.top    = y;
1368         rect.right  = x + width;
1369         rect.bottom = y + height;
1370         X11DRV_X_to_window_rect( win, &rect );
1371
1372         DCE_InvalidateDCE( hwnd, &win->rectWindow );
1373
1374         if (win->flags & WIN_RESTORE_MAX) style |= WS_MAXIMIZE;
1375         WIN_SetStyle( hwnd, style );
1376         WIN_ReleasePtr( win );
1377
1378         SendMessageA( hwnd, WM_SHOWWINDOW, SW_RESTORE, 0 );
1379         SetWindowPos( hwnd, 0, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top,
1380                       SWP_NOZORDER | SWP_WINE_NOHOSTMOVE );
1381     }
1382     else WIN_ReleasePtr( win );
1383     if (hwndFocus && IsChild( hwnd, hwndFocus )) X11DRV_SetFocus(hwndFocus);  /* FIXME */
1384 }
1385
1386
1387 /**********************************************************************
1388  *              X11DRV_UnmapNotify
1389  */
1390 void X11DRV_UnmapNotify( HWND hwnd, XUnmapEvent *event )
1391 {
1392     WND *win;
1393
1394     if (!(win = WIN_GetPtr( hwnd ))) return;
1395
1396     if ((win->dwStyle & WS_VISIBLE) && (win->dwExStyle & WS_EX_MANAGED) &&
1397         X11DRV_is_window_rect_mapped( &win->rectWindow ))
1398     {
1399         if (win->dwStyle & WS_MAXIMIZE)
1400             win->flags |= WIN_RESTORE_MAX;
1401         else
1402             win->flags &= ~WIN_RESTORE_MAX;
1403
1404         WIN_SetStyle( hwnd, (win->dwStyle & ~WS_MAXIMIZE) | WS_MINIMIZE );
1405         WIN_ReleasePtr( win );
1406
1407         EndMenu();
1408         SendMessageA( hwnd, WM_SHOWWINDOW, SW_MINIMIZE, 0 );
1409         SetWindowPos( hwnd, 0, 0, 0, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON),
1410                       SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_WINE_NOHOSTMOVE );
1411     }
1412     else WIN_ReleasePtr( win );
1413 }
1414
1415
1416 /***********************************************************************
1417  *           query_zorder
1418  *
1419  * Synchronize internal z-order with the window manager's.
1420  */
1421 static Window __get_common_ancestor( Display *display, Window A, Window B,
1422                                      Window** children, unsigned* total )
1423 {
1424     /* find the real root window */
1425
1426     Window      root, *childrenB;
1427     unsigned    totalB;
1428
1429     wine_tsx11_lock();
1430     while( A != B && A && B )
1431     {
1432       XQueryTree( display, A, &root, &A, children, total );
1433       XQueryTree( display, B, &root, &B, &childrenB, &totalB );
1434       if( childrenB ) XFree( childrenB );
1435       if( *children ) XFree( *children ), *children = NULL;
1436     }
1437
1438     if( A && B )
1439     {
1440         XQueryTree( display, A, &root, &B, children, total );
1441         wine_tsx11_unlock();
1442         return A;
1443     }
1444     wine_tsx11_unlock();
1445     return 0 ;
1446 }
1447
1448 static Window __get_top_decoration( Display *display, Window w, Window ancestor )
1449 {
1450     Window*     children, root, prev = w, parent = w;
1451     unsigned    total;
1452
1453     wine_tsx11_lock();
1454     do
1455     {
1456         w = parent;
1457         XQueryTree( display, w, &root, &parent, &children, &total );
1458         if( children ) XFree( children );
1459     } while( parent && parent != ancestor );
1460     wine_tsx11_unlock();
1461     TRACE("\t%08x -> %08x\n", (unsigned)prev, (unsigned)w );
1462     return ( parent ) ? w : 0 ;
1463 }
1464
1465 static unsigned __td_lookup( Window w, Window* list, unsigned max )
1466 {
1467     unsigned    i;
1468     for( i = max; i > 0; i-- ) if( list[i - 1] == w ) break;
1469     return i;
1470 }
1471
1472 static HWND query_zorder( Display *display, HWND hWndCheck)
1473 {
1474     HWND      hwndInsertAfter = HWND_TOP;
1475     Window      w, parent, *children = NULL;
1476     unsigned    total, check, pos, best;
1477     HWND *list = WIN_ListChildren( GetDesktopWindow() );
1478     HWND hwndA = 0, hwndB = 0;
1479     int i;
1480
1481     /* find at least two managed windows */
1482     if (!list) return 0;
1483     for (i = 0; list[i]; i++)
1484     {
1485         if (!(GetWindowLongW( list[i], GWL_EXSTYLE ) & WS_EX_MANAGED)) continue;
1486         if (!(GetWindowLongW( list[i], GWL_STYLE ) & WS_VISIBLE)) continue;
1487         if (!hwndA) hwndA = list[i];
1488         else
1489         {
1490             hwndB = list[i];
1491             break;
1492         }
1493     }
1494     if (!hwndA || !hwndB) goto done;
1495
1496     parent = __get_common_ancestor( display, X11DRV_get_whole_window(hwndA),
1497                                     X11DRV_get_whole_window(hwndB), &children, &total );
1498     if( parent && children )
1499     {
1500         /* w is the ancestor if hWndCheck that is a direct descendant of 'parent' */
1501
1502         w = __get_top_decoration( display, X11DRV_get_whole_window(hWndCheck), parent );
1503
1504         if( w != children[total-1] ) /* check if at the top */
1505         {
1506             /* X child at index 0 is at the bottom, at index total-1 is at the top */
1507             check = __td_lookup( w, children, total );
1508             best = total;
1509
1510             /* go through all windows in Wine z-order... */
1511             for (i = 0; list[i]; i++)
1512             {
1513                 if (list[i] == hWndCheck) continue;
1514                 if (!(GetWindowLongW( list[i], GWL_EXSTYLE ) & WS_EX_MANAGED)) continue;
1515                 if (!(w = __get_top_decoration( display, X11DRV_get_whole_window(list[i]),
1516                                                 parent ))) continue;
1517                 pos = __td_lookup( w, children, total );
1518                 if( pos < best && pos > check )
1519                 {
1520                     /* find a nearest Wine window precedes hWndCheck in the real z-order */
1521                     best = pos;
1522                     hwndInsertAfter = list[i];
1523                 }
1524                 if( best - check == 1 ) break;
1525             }
1526         }
1527     }
1528     wine_tsx11_lock();
1529     if( children ) XFree( children );
1530     wine_tsx11_unlock();
1531
1532  done:
1533     HeapFree( GetProcessHeap(), 0, list );
1534     return hwndInsertAfter;
1535 }
1536
1537
1538 /***********************************************************************
1539  *              X11DRV_handle_desktop_resize
1540  */
1541 void X11DRV_handle_desktop_resize( unsigned int width, unsigned int height )
1542 {
1543     RECT rect;
1544     HWND hwnd = GetDesktopWindow();
1545
1546     screen_width  = width;
1547     screen_height = height;
1548     TRACE("desktop %p change to (%dx%d)\n", hwnd, width, height);
1549     SetRect( &rect, 0, 0, width, height );
1550     WIN_SetRectangles( hwnd, &rect, &rect );
1551     SendMessageTimeoutW( HWND_BROADCAST, WM_DISPLAYCHANGE, screen_depth,
1552                          MAKELPARAM( width, height ), SMTO_ABORTIFHUNG, 2000, NULL );
1553 }
1554
1555
1556 /***********************************************************************
1557  *              X11DRV_ConfigureNotify
1558  */
1559 void X11DRV_ConfigureNotify( HWND hwnd, XConfigureEvent *event )
1560 {
1561     HWND oldInsertAfter;
1562     struct x11drv_win_data *data;
1563     WND *win;
1564     RECT rect;
1565     WINDOWPOS winpos;
1566     int x = event->x, y = event->y;
1567
1568     if (!(win = WIN_GetPtr( hwnd ))) return;
1569     data = win->pDriverData;
1570
1571     /* Get geometry */
1572
1573     if (!event->send_event)  /* normal event, need to map coordinates to the root */
1574     {
1575         Window child;
1576         wine_tsx11_lock();
1577         XTranslateCoordinates( event->display, data->whole_window, root_window,
1578                                0, 0, &x, &y, &child );
1579         wine_tsx11_unlock();
1580     }
1581     rect.left   = x;
1582     rect.top    = y;
1583     rect.right  = x + event->width;
1584     rect.bottom = y + event->height;
1585     TRACE( "win %p new X rect %ld,%ld,%ldx%ld (event %d,%d,%dx%d)\n",
1586            hwnd, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top,
1587            event->x, event->y, event->width, event->height );
1588     X11DRV_X_to_window_rect( win, &rect );
1589     WIN_ReleasePtr( win );
1590
1591     winpos.hwnd  = hwnd;
1592     winpos.x     = rect.left;
1593     winpos.y     = rect.top;
1594     winpos.cx    = rect.right - rect.left;
1595     winpos.cy    = rect.bottom - rect.top;
1596     winpos.flags = SWP_NOACTIVATE;
1597
1598     /* Get Z-order (FIXME) */
1599
1600     winpos.hwndInsertAfter = query_zorder( event->display, hwnd );
1601
1602     /* needs to find the first Visible Window above the current one */
1603     oldInsertAfter = hwnd;
1604     for (;;)
1605     {
1606         oldInsertAfter = GetWindow( oldInsertAfter, GW_HWNDPREV );
1607         if (!oldInsertAfter)
1608         {
1609             oldInsertAfter = HWND_TOP;
1610             break;
1611         }
1612         if (GetWindowLongA( oldInsertAfter, GWL_STYLE ) & WS_VISIBLE) break;
1613     }
1614
1615     /* Compare what has changed */
1616
1617     GetWindowRect( hwnd, &rect );
1618     if (rect.left == winpos.x && rect.top == winpos.y) winpos.flags |= SWP_NOMOVE;
1619     else
1620         TRACE( "%p moving from (%ld,%ld) to (%d,%d)\n",
1621                hwnd, rect.left, rect.top, winpos.x, winpos.y );
1622
1623     if ((rect.right - rect.left == winpos.cx && rect.bottom - rect.top == winpos.cy) ||
1624         IsIconic(hwnd) ||
1625         (IsRectEmpty( &rect ) && winpos.cx == 1 && winpos.cy == 1))
1626         winpos.flags |= SWP_NOSIZE;
1627     else
1628         TRACE( "%p resizing from (%ldx%ld) to (%dx%d)\n",
1629                hwnd, rect.right - rect.left, rect.bottom - rect.top,
1630                winpos.cx, winpos.cy );
1631
1632     if (winpos.hwndInsertAfter == oldInsertAfter) winpos.flags |= SWP_NOZORDER;
1633     else
1634         TRACE( "%p restacking from after %p to after %p\n",
1635                hwnd, oldInsertAfter, winpos.hwndInsertAfter );
1636
1637     /* if nothing changed, don't do anything */
1638     if (winpos.flags == (SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE)) return;
1639
1640     SetWindowPos( hwnd, winpos.hwndInsertAfter, winpos.x, winpos.y,
1641                   winpos.cx, winpos.cy, winpos.flags | SWP_WINE_NOHOSTMOVE );
1642 }
1643
1644
1645 /***********************************************************************
1646  *              SetWindowRgn  (X11DRV.@)
1647  *
1648  * Assign specified region to window (for non-rectangular windows)
1649  */
1650 int X11DRV_SetWindowRgn( HWND hwnd, HRGN hrgn, BOOL redraw )
1651 {
1652     WND *wndPtr;
1653
1654     if ((wndPtr = WIN_GetPtr( hwnd )) == WND_OTHER_PROCESS)
1655     {
1656         if (IsWindow( hwnd ))
1657             FIXME( "not supported on other process window %p\n", hwnd );
1658         wndPtr = NULL;
1659     }
1660     if (!wndPtr)
1661     {
1662         SetLastError( ERROR_INVALID_WINDOW_HANDLE );
1663         return FALSE;
1664     }
1665
1666 #ifdef HAVE_LIBXSHAPE
1667     {
1668         Display *display = thread_display();
1669         X11DRV_WND_DATA *data = wndPtr->pDriverData;
1670
1671         if (data->whole_window)
1672         {
1673             if (!hrgn)
1674             {
1675                 wine_tsx11_lock();
1676                 XShapeCombineMask( display, data->whole_window,
1677                                    ShapeBounding, 0, 0, None, ShapeSet );
1678                 wine_tsx11_unlock();
1679             }
1680             else
1681             {
1682                 RGNDATA *pRegionData = X11DRV_GetRegionData( hrgn, 0 );
1683                 if (pRegionData)
1684                 {
1685                     wine_tsx11_lock();
1686                     XShapeCombineRectangles( display, data->whole_window, ShapeBounding,
1687                                              wndPtr->rectWindow.left - data->whole_rect.left,
1688                                              wndPtr->rectWindow.top - data->whole_rect.top,
1689                                              (XRectangle *)pRegionData->Buffer,
1690                                              pRegionData->rdh.nCount,
1691                                              ShapeSet, YXBanded );
1692                     wine_tsx11_unlock();
1693                     HeapFree(GetProcessHeap(), 0, pRegionData);
1694                 }
1695             }
1696         }
1697     }
1698 #endif  /* HAVE_LIBXSHAPE */
1699
1700     WIN_ReleasePtr( wndPtr );
1701     return TRUE;
1702 }
1703
1704
1705 /***********************************************************************
1706  *           draw_moving_frame
1707  *
1708  * Draw the frame used when moving or resizing window.
1709  *
1710  * FIXME:  This causes problems in Win95 mode.  (why?)
1711  */
1712 static void draw_moving_frame( HDC hdc, RECT *rect, BOOL thickframe )
1713 {
1714     if (thickframe)
1715     {
1716         const int width = GetSystemMetrics(SM_CXFRAME);
1717         const int height = GetSystemMetrics(SM_CYFRAME);
1718
1719         HBRUSH hbrush = SelectObject( hdc, GetStockObject( GRAY_BRUSH ) );
1720         PatBlt( hdc, rect->left, rect->top,
1721                 rect->right - rect->left - width, height, PATINVERT );
1722         PatBlt( hdc, rect->left, rect->top + height, width,
1723                 rect->bottom - rect->top - height, PATINVERT );
1724         PatBlt( hdc, rect->left + width, rect->bottom - 1,
1725                 rect->right - rect->left - width, -height, PATINVERT );
1726         PatBlt( hdc, rect->right - 1, rect->top, -width,
1727                 rect->bottom - rect->top - height, PATINVERT );
1728         SelectObject( hdc, hbrush );
1729     }
1730     else DrawFocusRect( hdc, rect );
1731 }
1732
1733
1734 /***********************************************************************
1735  *           start_size_move
1736  *
1737  * Initialisation of a move or resize, when initiatied from a menu choice.
1738  * Return hit test code for caption or sizing border.
1739  */
1740 static LONG start_size_move( HWND hwnd, WPARAM wParam, POINT *capturePoint, LONG style )
1741 {
1742     LONG hittest = 0;
1743     POINT pt;
1744     MSG msg;
1745     RECT rectWindow;
1746
1747     GetWindowRect( hwnd, &rectWindow );
1748
1749     if ((wParam & 0xfff0) == SC_MOVE)
1750     {
1751         /* Move pointer at the center of the caption */
1752         RECT rect;
1753         NC_GetInsideRect( hwnd, &rect );
1754         if (style & WS_SYSMENU)
1755             rect.left += GetSystemMetrics(SM_CXSIZE) + 1;
1756         if (style & WS_MINIMIZEBOX)
1757             rect.right -= GetSystemMetrics(SM_CXSIZE) + 1;
1758         if (style & WS_MAXIMIZEBOX)
1759             rect.right -= GetSystemMetrics(SM_CXSIZE) + 1;
1760         pt.x = rectWindow.left + (rect.right - rect.left) / 2;
1761         pt.y = rectWindow.top + rect.top + GetSystemMetrics(SM_CYSIZE)/2;
1762         hittest = HTCAPTION;
1763         *capturePoint = pt;
1764     }
1765     else  /* SC_SIZE */
1766     {
1767         while(!hittest)
1768         {
1769             GetMessageW( &msg, 0, WM_KEYFIRST, WM_MOUSELAST );
1770             if (CallMsgFilterW( &msg, MSGF_SIZE )) continue;
1771
1772             switch(msg.message)
1773             {
1774             case WM_MOUSEMOVE:
1775                 hittest = NC_HandleNCHitTest( hwnd, msg.pt );
1776                 if ((hittest < HTLEFT) || (hittest > HTBOTTOMRIGHT))
1777                     hittest = 0;
1778                 break;
1779
1780             case WM_LBUTTONUP:
1781                 return 0;
1782
1783             case WM_KEYDOWN:
1784                 switch(msg.wParam)
1785                 {
1786                 case VK_UP:
1787                     hittest = HTTOP;
1788                     pt.x =(rectWindow.left+rectWindow.right)/2;
1789                     pt.y = rectWindow.top + GetSystemMetrics(SM_CYFRAME) / 2;
1790                     break;
1791                 case VK_DOWN:
1792                     hittest = HTBOTTOM;
1793                     pt.x =(rectWindow.left+rectWindow.right)/2;
1794                     pt.y = rectWindow.bottom - GetSystemMetrics(SM_CYFRAME) / 2;
1795                     break;
1796                 case VK_LEFT:
1797                     hittest = HTLEFT;
1798                     pt.x = rectWindow.left + GetSystemMetrics(SM_CXFRAME) / 2;
1799                     pt.y =(rectWindow.top+rectWindow.bottom)/2;
1800                     break;
1801                 case VK_RIGHT:
1802                     hittest = HTRIGHT;
1803                     pt.x = rectWindow.right - GetSystemMetrics(SM_CXFRAME) / 2;
1804                     pt.y =(rectWindow.top+rectWindow.bottom)/2;
1805                     break;
1806                 case VK_RETURN:
1807                 case VK_ESCAPE: return 0;
1808                 }
1809             }
1810         }
1811         *capturePoint = pt;
1812     }
1813     SetCursorPos( pt.x, pt.y );
1814     NC_HandleSetCursor( hwnd, (WPARAM)hwnd, MAKELONG( hittest, WM_MOUSEMOVE ));
1815     return hittest;
1816 }
1817
1818
1819 /***********************************************************************
1820  *           set_movesize_capture
1821  */
1822 static void set_movesize_capture( HWND hwnd )
1823 {
1824     HWND previous = 0;
1825
1826     SERVER_START_REQ( set_capture_window )
1827     {
1828         req->handle = hwnd;
1829         req->flags  = CAPTURE_MOVESIZE;
1830         if (!wine_server_call_err( req ))
1831         {
1832             previous = reply->previous;
1833             hwnd = reply->full_handle;
1834         }
1835     }
1836     SERVER_END_REQ;
1837     if (previous && previous != hwnd)
1838         SendMessageW( previous, WM_CAPTURECHANGED, 0, (LPARAM)hwnd );
1839 }
1840
1841
1842 /***********************************************************************
1843  *           SysCommandSizeMove   (X11DRV.@)
1844  *
1845  * Perform SC_MOVE and SC_SIZE commands.
1846  */
1847 void X11DRV_SysCommandSizeMove( HWND hwnd, WPARAM wParam )
1848 {
1849     MSG msg;
1850     RECT sizingRect, mouseRect, origRect;
1851     HDC hdc;
1852     HWND parent;
1853     LONG hittest = (LONG)(wParam & 0x0f);
1854     HCURSOR hDragCursor = 0, hOldCursor = 0;
1855     POINT minTrack, maxTrack;
1856     POINT capturePoint, pt;
1857     LONG style = GetWindowLongA( hwnd, GWL_STYLE );
1858     LONG exstyle = GetWindowLongA( hwnd, GWL_EXSTYLE );
1859     BOOL    thickframe = HAS_THICKFRAME( style, exstyle );
1860     BOOL    iconic = style & WS_MINIMIZE;
1861     BOOL    moved = FALSE;
1862     DWORD     dwPoint = GetMessagePos ();
1863     BOOL DragFullWindows = FALSE;
1864     BOOL grab;
1865     int iWndsLocks;
1866     Display *old_gdi_display = NULL;
1867     Display *display = thread_display();
1868
1869     SystemParametersInfoA(SPI_GETDRAGFULLWINDOWS, 0, &DragFullWindows, 0);
1870
1871     pt.x = (short)LOWORD(dwPoint);
1872     pt.y = (short)HIWORD(dwPoint);
1873     capturePoint = pt;
1874
1875     if (IsZoomed(hwnd) || !IsWindowVisible(hwnd) || (exstyle & WS_EX_MANAGED)) return;
1876
1877     if ((wParam & 0xfff0) == SC_MOVE)
1878     {
1879         if (!hittest) hittest = start_size_move( hwnd, wParam, &capturePoint, style );
1880         if (!hittest) return;
1881     }
1882     else  /* SC_SIZE */
1883     {
1884         if (!thickframe) return;
1885         if ( hittest && ((wParam & 0xfff0) != SC_MOUSEMENU) )
1886             hittest += (HTLEFT - WMSZ_LEFT);
1887         else
1888         {
1889             set_movesize_capture( hwnd );
1890             hittest = start_size_move( hwnd, wParam, &capturePoint, style );
1891             if (!hittest)
1892             {
1893                 set_movesize_capture(0);
1894                 return;
1895             }
1896         }
1897     }
1898
1899       /* Get min/max info */
1900
1901     WINPOS_GetMinMaxInfo( hwnd, NULL, NULL, &minTrack, &maxTrack );
1902     GetWindowRect( hwnd, &sizingRect );
1903     if (style & WS_CHILD)
1904     {
1905         parent = GetParent(hwnd);
1906         /* make sizing rect relative to parent */
1907         MapWindowPoints( 0, parent, (POINT*)&sizingRect, 2 );
1908         GetClientRect( parent, &mouseRect );
1909     }
1910     else
1911     {
1912         parent = 0;
1913         SetRect(&mouseRect, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
1914     }
1915     origRect = sizingRect;
1916
1917     if (ON_LEFT_BORDER(hittest))
1918     {
1919         mouseRect.left  = max( mouseRect.left, sizingRect.right-maxTrack.x );
1920         mouseRect.right = min( mouseRect.right, sizingRect.right-minTrack.x );
1921     }
1922     else if (ON_RIGHT_BORDER(hittest))
1923     {
1924         mouseRect.left  = max( mouseRect.left, sizingRect.left+minTrack.x );
1925         mouseRect.right = min( mouseRect.right, sizingRect.left+maxTrack.x );
1926     }
1927     if (ON_TOP_BORDER(hittest))
1928     {
1929         mouseRect.top    = max( mouseRect.top, sizingRect.bottom-maxTrack.y );
1930         mouseRect.bottom = min( mouseRect.bottom,sizingRect.bottom-minTrack.y);
1931     }
1932     else if (ON_BOTTOM_BORDER(hittest))
1933     {
1934         mouseRect.top    = max( mouseRect.top, sizingRect.top+minTrack.y );
1935         mouseRect.bottom = min( mouseRect.bottom, sizingRect.top+maxTrack.y );
1936     }
1937     if (parent) MapWindowPoints( parent, 0, (LPPOINT)&mouseRect, 2 );
1938
1939     /* Retrieve a default cache DC (without using the window style) */
1940     hdc = GetDCEx( parent, 0, DCX_CACHE );
1941
1942     if( iconic ) /* create a cursor for dragging */
1943     {
1944         hDragCursor = (HCURSOR)GetClassLongA( hwnd, GCL_HICON);
1945         if( !hDragCursor ) hDragCursor = (HCURSOR)SendMessageA( hwnd, WM_QUERYDRAGICON, 0, 0L);
1946         if( !hDragCursor ) iconic = FALSE;
1947     }
1948
1949     /* repaint the window before moving it around */
1950     RedrawWindow( hwnd, NULL, 0, RDW_UPDATENOW | RDW_ALLCHILDREN );
1951
1952     SendMessageA( hwnd, WM_ENTERSIZEMOVE, 0, 0 );
1953     set_movesize_capture( hwnd );
1954
1955     /* grab the server only when moving top-level windows without desktop */
1956     grab = (!DragFullWindows && !parent && (root_window == DefaultRootWindow(gdi_display)));
1957
1958     wine_tsx11_lock();
1959     if (grab)
1960     {
1961         XSync( gdi_display, False );
1962         XGrabServer( display );
1963         XSync( display, False );
1964         /* switch gdi display to the thread display, since the server is grabbed */
1965         old_gdi_display = gdi_display;
1966         gdi_display = display;
1967     }
1968     XGrabPointer( display, X11DRV_get_whole_window(hwnd), False,
1969                   PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
1970                   GrabModeAsync, GrabModeAsync,
1971                   parent ? X11DRV_get_client_window(parent) : root_window,
1972                   None, CurrentTime );
1973     wine_tsx11_unlock();
1974
1975     while(1)
1976     {
1977         int dx = 0, dy = 0;
1978
1979         if (!GetMessageW( &msg, 0, WM_KEYFIRST, WM_MOUSELAST )) break;
1980         if (CallMsgFilterW( &msg, MSGF_SIZE )) continue;
1981
1982         /* Exit on button-up, Return, or Esc */
1983         if ((msg.message == WM_LBUTTONUP) ||
1984             ((msg.message == WM_KEYDOWN) &&
1985              ((msg.wParam == VK_RETURN) || (msg.wParam == VK_ESCAPE)))) break;
1986
1987         if ((msg.message != WM_KEYDOWN) && (msg.message != WM_MOUSEMOVE))
1988             continue;  /* We are not interested in other messages */
1989
1990         pt = msg.pt;
1991
1992         if (msg.message == WM_KEYDOWN) switch(msg.wParam)
1993         {
1994         case VK_UP:    pt.y -= 8; break;
1995         case VK_DOWN:  pt.y += 8; break;
1996         case VK_LEFT:  pt.x -= 8; break;
1997         case VK_RIGHT: pt.x += 8; break;
1998         }
1999
2000         pt.x = max( pt.x, mouseRect.left );
2001         pt.x = min( pt.x, mouseRect.right );
2002         pt.y = max( pt.y, mouseRect.top );
2003         pt.y = min( pt.y, mouseRect.bottom );
2004
2005         dx = pt.x - capturePoint.x;
2006         dy = pt.y - capturePoint.y;
2007
2008         if (dx || dy)
2009         {
2010             if( !moved )
2011             {
2012                 moved = TRUE;
2013
2014                 if( iconic ) /* ok, no system popup tracking */
2015                 {
2016                     hOldCursor = SetCursor(hDragCursor);
2017                     ShowCursor( TRUE );
2018                     WINPOS_ShowIconTitle( hwnd, FALSE );
2019                 }
2020                 else if(!DragFullWindows)
2021                     draw_moving_frame( hdc, &sizingRect, thickframe );
2022             }
2023
2024             if (msg.message == WM_KEYDOWN) SetCursorPos( pt.x, pt.y );
2025             else
2026             {
2027                 RECT newRect = sizingRect;
2028                 WPARAM wpSizingHit = 0;
2029
2030                 if (hittest == HTCAPTION) OffsetRect( &newRect, dx, dy );
2031                 if (ON_LEFT_BORDER(hittest)) newRect.left += dx;
2032                 else if (ON_RIGHT_BORDER(hittest)) newRect.right += dx;
2033                 if (ON_TOP_BORDER(hittest)) newRect.top += dy;
2034                 else if (ON_BOTTOM_BORDER(hittest)) newRect.bottom += dy;
2035                 if(!iconic && !DragFullWindows) draw_moving_frame( hdc, &sizingRect, thickframe );
2036                 capturePoint = pt;
2037
2038                 /* determine the hit location */
2039                 if (hittest >= HTLEFT && hittest <= HTBOTTOMRIGHT)
2040                     wpSizingHit = WMSZ_LEFT + (hittest - HTLEFT);
2041                 SendMessageA( hwnd, WM_SIZING, wpSizingHit, (LPARAM)&newRect );
2042
2043                 if (!iconic)
2044                 {
2045                     if(!DragFullWindows)
2046                         draw_moving_frame( hdc, &newRect, thickframe );
2047                     else {
2048                         /* To avoid any deadlocks, all the locks on the windows
2049                            structures must be suspended before the SetWindowPos */
2050                         iWndsLocks = WIN_SuspendWndsLock();
2051                         SetWindowPos( hwnd, 0, newRect.left, newRect.top,
2052                                       newRect.right - newRect.left,
2053                                       newRect.bottom - newRect.top,
2054                                       ( hittest == HTCAPTION ) ? SWP_NOSIZE : 0 );
2055                         WIN_RestoreWndsLock(iWndsLocks);
2056                     }
2057                 }
2058                 sizingRect = newRect;
2059             }
2060         }
2061     }
2062
2063     set_movesize_capture(0);
2064     if( iconic )
2065     {
2066         if( moved ) /* restore cursors, show icon title later on */
2067         {
2068             ShowCursor( FALSE );
2069             SetCursor( hOldCursor );
2070         }
2071     }
2072     else if (moved && !DragFullWindows)
2073         draw_moving_frame( hdc, &sizingRect, thickframe );
2074
2075     ReleaseDC( parent, hdc );
2076
2077     wine_tsx11_lock();
2078     XUngrabPointer( display, CurrentTime );
2079     if (grab)
2080     {
2081         XSync( display, False );
2082         XUngrabServer( display );
2083         XSync( display, False );
2084         gdi_display = old_gdi_display;
2085     }
2086     wine_tsx11_unlock();
2087
2088     if (HOOK_CallHooks( WH_CBT, HCBT_MOVESIZE, (WPARAM)hwnd, (LPARAM)&sizingRect, TRUE ))
2089         moved = FALSE;
2090
2091     SendMessageA( hwnd, WM_EXITSIZEMOVE, 0, 0 );
2092     SendMessageA( hwnd, WM_SETVISIBLE, !IsIconic(hwnd), 0L);
2093
2094     /* window moved or resized */
2095     if (moved)
2096     {
2097         /* To avoid any deadlocks, all the locks on the windows
2098            structures must be suspended before the SetWindowPos */
2099         iWndsLocks = WIN_SuspendWndsLock();
2100
2101         /* if the moving/resizing isn't canceled call SetWindowPos
2102          * with the new position or the new size of the window
2103          */
2104         if (!((msg.message == WM_KEYDOWN) && (msg.wParam == VK_ESCAPE)) )
2105         {
2106             /* NOTE: SWP_NOACTIVATE prevents document window activation in Word 6 */
2107             if(!DragFullWindows)
2108                 SetWindowPos( hwnd, 0, sizingRect.left, sizingRect.top,
2109                               sizingRect.right - sizingRect.left,
2110                               sizingRect.bottom - sizingRect.top,
2111                               ( hittest == HTCAPTION ) ? SWP_NOSIZE : 0 );
2112         }
2113         else
2114         { /* restore previous size/position */
2115             if(DragFullWindows)
2116                 SetWindowPos( hwnd, 0, origRect.left, origRect.top,
2117                               origRect.right - origRect.left,
2118                               origRect.bottom - origRect.top,
2119                               ( hittest == HTCAPTION ) ? SWP_NOSIZE : 0 );
2120         }
2121
2122         WIN_RestoreWndsLock(iWndsLocks);
2123     }
2124
2125     if (IsIconic(hwnd))
2126     {
2127         /* Single click brings up the system menu when iconized */
2128
2129         if( !moved )
2130         {
2131             if(style & WS_SYSMENU )
2132                 SendMessageA( hwnd, WM_SYSCOMMAND,
2133                               SC_MOUSEMENU + HTSYSMENU, MAKELONG(pt.x,pt.y));
2134         }
2135         else WINPOS_ShowIconTitle( hwnd, TRUE );
2136     }
2137 }
2138
2139
2140 /***********************************************************************
2141  *              ForceWindowRaise   (X11DRV.@)
2142  *
2143  * Raise a window on top of the X stacking order, while preserving
2144  * the correct Windows Z order.
2145  *
2146  * FIXME: this should go away.
2147  */
2148 void X11DRV_ForceWindowRaise( HWND hwnd )
2149 {
2150     int i = 0;
2151     HWND *list;
2152     XWindowChanges winChanges;
2153     Display *display = thread_display();
2154     WND *wndPtr = WIN_FindWndPtr( hwnd );
2155
2156     if (!wndPtr) return;
2157
2158     if ((wndPtr->dwExStyle & WS_EX_MANAGED) ||
2159         wndPtr->parent != GetDesktopWindow() ||
2160         IsRectEmpty( &wndPtr->rectWindow ) ||
2161         !get_whole_window(wndPtr))
2162     {
2163         WIN_ReleaseWndPtr( wndPtr );
2164         return;
2165     }
2166     WIN_ReleaseWndPtr( wndPtr );
2167
2168     /* Raise all windows up to wndPtr according to their Z order.
2169      * (it would be easier with sibling-related Below but it doesn't
2170      * work very well with SGI mwm for instance)
2171      */
2172     winChanges.stack_mode = Above;
2173     if (!(list = WIN_ListChildren( GetDesktopWindow() ))) return;
2174     while (list[i] && list[i] != hwnd) i++;
2175     if (list[i])
2176     {
2177         for ( ; i >= 0; i--)
2178         {
2179             WND *ptr = WIN_FindWndPtr( list[i] );
2180             if (!ptr) continue;
2181             if (!IsRectEmpty( &ptr->rectWindow ) && get_whole_window(ptr))
2182             {
2183                 wine_tsx11_lock();
2184                 XReconfigureWMWindow( display, get_whole_window(ptr), 0, CWStackMode, &winChanges );
2185                 wine_tsx11_unlock();
2186             }
2187             WIN_ReleaseWndPtr( ptr );
2188         }
2189     }
2190     HeapFree( GetProcessHeap(), 0, list );
2191 }