Fix potential memory issue.
[wine] / dlls / x11drv / 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
9 #include "config.h"
10
11 #include <stdlib.h>
12
13 #include "ts_xlib.h"
14 #include "ts_xutil.h"
15
16 #include "winbase.h"
17 #include "wingdi.h"
18 #include "winreg.h"
19 #include "winuser.h"
20 #include "wine/unicode.h"
21
22 #include "debugtools.h"
23 #include "x11drv.h"
24 #include "win.h"
25 #include "winpos.h"
26 #include "dce.h"
27 #include "options.h"
28 #include "hook.h"
29
30 DEFAULT_DEBUG_CHANNEL(x11drv);
31
32 extern Pixmap X11DRV_BITMAP_Pixmap( HBITMAP );
33
34 #define HAS_DLGFRAME(style,exStyle) \
35     (((exStyle) & WS_EX_DLGMODALFRAME) || \
36      (((style) & WS_DLGFRAME) && !((style) & WS_THICKFRAME)))
37
38 /* X context to associate a hwnd to an X window */
39 XContext winContext = 0;
40
41 Atom wmProtocols = None;
42 Atom wmDeleteWindow = None;
43 Atom wmTakeFocus = None;
44 Atom dndProtocol = None;
45 Atom dndSelection = None;
46 Atom wmChangeState = None;
47 Atom kwmDockWindow = None;
48 Atom _kde_net_wm_system_tray_window_for = None; /* KDE 2 Final */
49
50 static LPCSTR whole_window_atom;
51 static LPCSTR client_window_atom;
52 static LPCSTR icon_window_atom;
53
54 /***********************************************************************
55  *              is_window_managed
56  *
57  * Check if a given window should be managed
58  */
59 inline static BOOL is_window_managed( WND *win )
60 {
61     if (!Options.managed) return FALSE;
62
63     /* tray window is always managed */
64     if (win->dwExStyle & WS_EX_TRAYWINDOW) return TRUE;
65     /* child windows are not managed */
66     if (win->dwStyle & WS_CHILD) return FALSE;
67     /* tool windows are not managed */
68     if (win->dwExStyle & WS_EX_TOOLWINDOW) return FALSE;
69     /* windows with caption or thick frame are managed */
70     if ((win->dwStyle & WS_CAPTION) == WS_CAPTION) return TRUE;
71     if (win->dwStyle & WS_THICKFRAME) return TRUE;
72     /* default: not managed */
73     return FALSE;
74 }
75
76
77 /***********************************************************************
78  *              is_window_top_level
79  *
80  * Check if a given window is a top level X11 window
81  */
82 inline static BOOL is_window_top_level( WND *win )
83 {
84     return (root_window == DefaultRootWindow(gdi_display) && win->parent == GetDesktopWindow());
85 }
86
87
88 /***********************************************************************
89  *              is_client_window_mapped
90  *
91  * Check if the X client window should be mapped
92  */
93 inline static BOOL is_client_window_mapped( WND *win )
94 {
95     struct x11drv_win_data *data = win->pDriverData;
96     return !(win->dwStyle & WS_MINIMIZE) && !IsRectEmpty( &data->client_rect );
97 }
98
99
100 /***********************************************************************
101  *              get_window_attributes
102  *
103  * Fill the window attributes structure for an X window.
104  * Returned cursor must be freed by caller.
105  */
106 static int get_window_attributes( Display *display, WND *win, XSetWindowAttributes *attr )
107 {
108     BOOL is_top_level = is_window_top_level( win );
109     BOOL managed = is_top_level && is_window_managed( win );
110
111     if (managed) WIN_SetExStyle( win->hwndSelf, win->dwExStyle | WS_EX_MANAGED );
112     else WIN_SetExStyle( win->hwndSelf, win->dwExStyle & ~WS_EX_MANAGED );
113
114     attr->override_redirect = !managed;
115     attr->colormap          = X11DRV_PALETTE_PaletteXColormap;
116     attr->save_under        = ((win->clsStyle & CS_SAVEBITS) != 0);
117     attr->cursor            = None;
118     attr->event_mask        = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
119                                ButtonPressMask | ButtonReleaseMask);
120     if (is_window_top_level( win ))
121     {
122         attr->event_mask |= StructureNotifyMask | FocusChangeMask | KeymapStateMask;
123         attr->cursor = X11DRV_GetCursor( display, GlobalLock16(GetCursor()) );
124     }
125     return (CWOverrideRedirect | CWSaveUnder | CWEventMask | CWColormap | CWCursor);
126 }
127
128
129 /***********************************************************************
130  *              sync_window_style
131  *
132  * Change the X window attributes when the window style has changed.
133  */
134 static void sync_window_style( Display *display, WND *win )
135 {
136     XSetWindowAttributes attr;
137     int mask;
138
139     wine_tsx11_lock();
140     mask = get_window_attributes( display, win, &attr );
141     XChangeWindowAttributes( display, get_whole_window(win), mask, &attr );
142     if (attr.cursor) XFreeCursor( display, attr.cursor );
143     wine_tsx11_unlock();
144 }
145
146
147 /***********************************************************************
148  *              get_window_changes
149  *
150  * fill the window changes structure
151  */
152 static int get_window_changes( XWindowChanges *changes, const RECT *old, const RECT *new )
153 {
154     int mask = 0;
155
156     if (old->right - old->left != new->right - new->left )
157     {
158         if (!(changes->width = new->right - new->left)) changes->width = 1;
159         mask |= CWWidth;
160     }
161     if (old->bottom - old->top != new->bottom - new->top)
162     {
163         if (!(changes->height = new->bottom - new->top)) changes->height = 1;
164         mask |= CWHeight;
165     }
166     if (old->left != new->left)
167     {
168         changes->x = new->left;
169         mask |= CWX;
170     }
171     if (old->top != new->top)
172     {
173         changes->y = new->top;
174         mask |= CWY;
175     }
176     return mask;
177 }
178
179
180 /***********************************************************************
181  *              create_icon_window
182  */
183 static Window create_icon_window( Display *display, WND *win )
184 {
185     struct x11drv_win_data *data = win->pDriverData;
186     XSetWindowAttributes attr;
187
188     attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
189                        ButtonPressMask | ButtonReleaseMask);
190     attr.bit_gravity = NorthWestGravity;
191     attr.backing_store = NotUseful/*WhenMapped*/;
192     attr.colormap      = X11DRV_PALETTE_PaletteXColormap; /* Needed due to our visual */
193
194     wine_tsx11_lock();
195     data->icon_window = XCreateWindow( display, root_window, 0, 0,
196                                        GetSystemMetrics( SM_CXICON ),
197                                        GetSystemMetrics( SM_CYICON ),
198                                        0, screen_depth,
199                                        InputOutput, visual,
200                                        CWEventMask | CWBitGravity | CWBackingStore | CWColormap, &attr );
201     XSaveContext( display, data->icon_window, winContext, (char *)win->hwndSelf );
202     wine_tsx11_unlock();
203
204     TRACE( "created %lx\n", data->icon_window );
205     SetPropA( win->hwndSelf, icon_window_atom, (HANDLE)data->icon_window );
206     return data->icon_window;
207 }
208
209
210
211 /***********************************************************************
212  *              destroy_icon_window
213  */
214 inline static void destroy_icon_window( Display *display, WND *win )
215 {
216     struct x11drv_win_data *data = win->pDriverData;
217
218     if (!data->icon_window) return;
219     wine_tsx11_lock();
220     XDeleteContext( display, data->icon_window, winContext );
221     XDestroyWindow( display, data->icon_window );
222     data->icon_window = 0;
223     wine_tsx11_unlock();
224     RemovePropA( win->hwndSelf, icon_window_atom );
225 }
226
227
228 /***********************************************************************
229  *              set_icon_hints
230  *
231  * Set the icon wm hints
232  */
233 static void set_icon_hints( Display *display, WND *wndPtr, XWMHints *hints )
234 {
235     X11DRV_WND_DATA *data = wndPtr->pDriverData;
236     HICON hIcon = GetClassLongA( wndPtr->hwndSelf, GCL_HICON );
237
238     if (data->hWMIconBitmap) DeleteObject( data->hWMIconBitmap );
239     if (data->hWMIconMask) DeleteObject( data->hWMIconMask);
240     data->hWMIconBitmap = 0;
241     data->hWMIconMask = 0;
242
243     if (!(wndPtr->dwExStyle & WS_EX_MANAGED))
244     {
245         destroy_icon_window( display, wndPtr );
246         hints->flags &= ~(IconPixmapHint | IconMaskHint | IconWindowHint);
247     }
248     else if (!hIcon)
249     {
250         if (!data->icon_window) create_icon_window( display, wndPtr );
251         hints->icon_window = data->icon_window;
252         hints->flags = (hints->flags & ~(IconPixmapHint | IconMaskHint)) | IconWindowHint;
253     }
254     else
255     {
256         HBITMAP hbmOrig;
257         RECT rcMask;
258         BITMAP bmMask;
259         ICONINFO ii;
260         HDC hDC;
261
262         GetIconInfo(hIcon, &ii);
263
264         X11DRV_CreateBitmap(ii.hbmMask);
265         X11DRV_CreateBitmap(ii.hbmColor);
266
267         GetObjectA(ii.hbmMask, sizeof(bmMask), &bmMask);
268         rcMask.top    = 0;
269         rcMask.left   = 0;
270         rcMask.right  = bmMask.bmWidth;
271         rcMask.bottom = bmMask.bmHeight;
272
273         hDC = CreateCompatibleDC(0);
274         hbmOrig = SelectObject(hDC, ii.hbmMask);
275         InvertRect(hDC, &rcMask);
276         SelectObject(hDC, hbmOrig);
277         DeleteDC(hDC);
278
279         data->hWMIconBitmap = ii.hbmColor;
280         data->hWMIconMask = ii.hbmMask;
281
282         hints->icon_pixmap = X11DRV_BITMAP_Pixmap(data->hWMIconBitmap);
283         hints->icon_mask = X11DRV_BITMAP_Pixmap(data->hWMIconMask);
284         destroy_icon_window( display, wndPtr );
285         hints->flags = (hints->flags & ~IconWindowHint) | IconPixmapHint | IconMaskHint;
286     }
287 }
288
289
290 /***********************************************************************
291  *              set_size_hints
292  *
293  * set the window size hints
294  */
295 static void set_size_hints( Display *display, WND *win )
296 {
297     XSizeHints* size_hints;
298     struct x11drv_win_data *data = win->pDriverData;
299
300     if ((size_hints = XAllocSizeHints()))
301     {
302         size_hints->win_gravity = StaticGravity;
303         size_hints->x = data->whole_rect.left;
304         size_hints->y = data->whole_rect.top;
305         size_hints->flags = PWinGravity | PPosition;
306
307         if (HAS_DLGFRAME( win->dwStyle, win->dwExStyle ))
308         {
309             size_hints->max_width = data->whole_rect.right - data->whole_rect.left;
310             size_hints->max_height = data->whole_rect.bottom - data->whole_rect.top;
311             size_hints->min_width = size_hints->max_width;
312             size_hints->min_height = size_hints->max_height;
313             size_hints->flags |= PMinSize | PMaxSize;
314         }
315         XSetWMNormalHints( display, data->whole_window, size_hints );
316         XFree( size_hints );
317     }
318 }
319
320
321 /***********************************************************************
322  *              set_wm_hints
323  *
324  * Set the window manager hints for a newly-created window
325  */
326 static void set_wm_hints( Display *display, WND *win )
327 {
328     struct x11drv_win_data *data = win->pDriverData;
329     Window group_leader;
330     XClassHint *class_hints;
331     XWMHints* wm_hints;
332     Atom protocols[2];
333     int i;
334
335     wine_tsx11_lock();
336
337     /* wm protocols */
338     i = 0;
339     protocols[i++] = wmDeleteWindow;
340     if (wmTakeFocus) protocols[i++] = wmTakeFocus;
341     XSetWMProtocols( display, data->whole_window, protocols, i );
342
343     /* class hints */
344     if ((class_hints = XAllocClassHint()))
345     {
346         class_hints->res_name = "wine";
347         class_hints->res_class = "Wine";
348         XSetClassHint( display, data->whole_window, class_hints );
349         XFree( class_hints );
350     }
351
352     /* transient for hint */
353     if (win->owner)
354     {
355         Window owner_win = X11DRV_get_whole_window( win->owner );
356         XSetTransientForHint( display, data->whole_window, owner_win );
357         group_leader = owner_win;
358     }
359     else group_leader = data->whole_window;
360
361     /* size hints */
362     set_size_hints( display, win );
363
364     /* systray properties (KDE only for now) */
365     if (win->dwExStyle & WS_EX_TRAYWINDOW)
366     {
367         int val = 1;
368         if (kwmDockWindow != None)
369             TSXChangeProperty( display, data->whole_window, kwmDockWindow, kwmDockWindow,
370                                32, PropModeReplace, (char*)&val, 1 );
371         if (_kde_net_wm_system_tray_window_for != None)
372             TSXChangeProperty( display, data->whole_window, _kde_net_wm_system_tray_window_for,
373                                XA_WINDOW, 32, PropModeReplace, (char*)&data->whole_window, 1 );
374     }
375
376     wine_tsx11_unlock();
377
378     /* wm hints */
379     if ((wm_hints = TSXAllocWMHints()))
380     {
381         wm_hints->flags = InputHint | StateHint | WindowGroupHint;
382         /* use globally active model if take focus is supported,
383          * passive model otherwise (cf. ICCCM) */
384         wm_hints->input = !wmTakeFocus;
385
386         set_icon_hints( display, win, wm_hints );
387
388         wm_hints->initial_state = (win->dwStyle & WS_MINIMIZE) ? IconicState : NormalState;
389         wm_hints->window_group = group_leader;
390
391         wine_tsx11_lock();
392         XSetWMHints( display, data->whole_window, wm_hints );
393         XFree(wm_hints);
394         wine_tsx11_unlock();
395     }
396 }
397
398
399 /***********************************************************************
400  *              X11DRV_set_iconic_state
401  *
402  * Set the X11 iconic state according to the window style.
403  */
404 void X11DRV_set_iconic_state( WND *win )
405 {
406     Display *display = thread_display();
407     struct x11drv_win_data *data = win->pDriverData;
408     XWMHints* wm_hints;
409     BOOL iconic = IsIconic( win->hwndSelf );
410
411     wine_tsx11_lock();
412
413     if (iconic) XUnmapWindow( display, data->client_window );
414     else if (is_client_window_mapped( win )) XMapWindow( display, data->client_window );
415
416     if (!(wm_hints = XGetWMHints( display, data->whole_window ))) wm_hints = XAllocWMHints();
417     wm_hints->flags |= StateHint | IconPositionHint;
418     wm_hints->initial_state = iconic ? IconicState : NormalState;
419     wm_hints->icon_x = win->rectWindow.left;
420     wm_hints->icon_y = win->rectWindow.top;
421     XSetWMHints( display, data->whole_window, wm_hints );
422
423     if (win->dwStyle & WS_VISIBLE)
424     {
425         if (iconic)
426             XIconifyWindow( display, data->whole_window, DefaultScreen(display) );
427         else
428             if (!IsRectEmpty( &win->rectWindow )) XMapWindow( display, data->whole_window );
429     }
430
431     XFree(wm_hints);
432     wine_tsx11_unlock();
433 }
434
435
436 /***********************************************************************
437  *              X11DRV_window_to_X_rect
438  *
439  * Convert a rect from client to X window coordinates
440  */
441 void X11DRV_window_to_X_rect( WND *win, RECT *rect )
442 {
443     RECT rc;
444
445     if (!(win->dwExStyle & WS_EX_MANAGED)) return;
446     if (IsRectEmpty( rect )) return;
447
448     rc.top = rc.bottom = rc.left = rc.right = 0;
449
450     AdjustWindowRectEx( &rc, win->dwStyle & ~(WS_HSCROLL|WS_VSCROLL), FALSE, win->dwExStyle );
451
452     rect->left   -= rc.left;
453     rect->right  -= rc.right;
454     rect->top    -= rc.top;
455     rect->bottom -= rc.bottom;
456     if (rect->top >= rect->bottom) rect->bottom = rect->top + 1;
457     if (rect->left >= rect->right) rect->right = rect->left + 1;
458 }
459
460
461 /***********************************************************************
462  *              X11DRV_X_to_window_rect
463  *
464  * Opposite of X11DRV_window_to_X_rect
465  */
466 void X11DRV_X_to_window_rect( WND *win, RECT *rect )
467 {
468     if (!(win->dwExStyle & WS_EX_MANAGED)) return;
469     if (IsRectEmpty( rect )) return;
470
471     AdjustWindowRectEx( rect, win->dwStyle & ~(WS_HSCROLL|WS_VSCROLL), FALSE, win->dwExStyle );
472
473     if (rect->top >= rect->bottom) rect->bottom = rect->top + 1;
474     if (rect->left >= rect->right) rect->right = rect->left + 1;
475 }
476
477
478 /***********************************************************************
479  *              X11DRV_sync_whole_window_position
480  *
481  * Synchronize the X whole window position with the Windows one
482  */
483 int X11DRV_sync_whole_window_position( Display *display, WND *win, int zorder )
484 {
485     XWindowChanges changes;
486     int mask;
487     struct x11drv_win_data *data = win->pDriverData;
488     RECT whole_rect = win->rectWindow;
489
490     X11DRV_window_to_X_rect( win, &whole_rect );
491     mask = get_window_changes( &changes, &data->whole_rect, &whole_rect );
492
493     if (zorder)
494     {
495         /* find window that this one must be after */
496         HWND prev = GetWindow( win->hwndSelf, GW_HWNDPREV );
497         while (prev && !(GetWindowLongW( prev, GWL_STYLE ) & WS_VISIBLE))
498             prev = GetWindow( prev, GW_HWNDPREV );
499         if (!prev)  /* top child */
500         {
501             changes.stack_mode = Above;
502             mask |= CWStackMode;
503         }
504         else
505         {
506             changes.stack_mode = Below;
507             changes.sibling = X11DRV_get_whole_window(prev);
508             mask |= CWStackMode | CWSibling;
509         }
510     }
511
512     data->whole_rect = whole_rect;
513
514     if (mask)
515     {
516         TRACE( "setting win %lx pos %d,%d,%dx%d after %lx changes=%x\n",
517                data->whole_window, whole_rect.left, whole_rect.top,
518                whole_rect.right - whole_rect.left, whole_rect.bottom - whole_rect.top,
519                changes.sibling, mask );
520         wine_tsx11_lock();
521         XSync( gdi_display, False );  /* flush graphics operations before moving the window */
522         if (is_window_top_level( win ))
523         {
524             if (mask & (CWWidth|CWHeight)) set_size_hints( display, win );
525             XReconfigureWMWindow( display, data->whole_window,
526                                   DefaultScreen(display), mask, &changes );
527         }
528         else XConfigureWindow( display, data->whole_window, mask, &changes );
529         wine_tsx11_unlock();
530     }
531     return mask;
532 }
533
534
535 /***********************************************************************
536  *              X11DRV_sync_client_window_position
537  *
538  * Synchronize the X client window position with the Windows one
539  */
540 int X11DRV_sync_client_window_position( Display *display, WND *win )
541 {
542     XWindowChanges changes;
543     int mask;
544     struct x11drv_win_data *data = win->pDriverData;
545     RECT client_rect = win->rectClient;
546
547     OffsetRect( &client_rect, -data->whole_rect.left, -data->whole_rect.top );
548
549     if ((mask = get_window_changes( &changes, &data->client_rect, &client_rect )))
550     {
551         BOOL was_mapped = is_client_window_mapped( win );
552
553         TRACE( "setting win %lx pos %d,%d,%dx%d (was %d,%d,%dx%d) after %lx changes=%x\n",
554                data->client_window, client_rect.left, client_rect.top,
555                client_rect.right - client_rect.left, client_rect.bottom - client_rect.top,
556                data->client_rect.left, data->client_rect.top,
557                data->client_rect.right - data->client_rect.left,
558                data->client_rect.bottom - data->client_rect.top,
559                changes.sibling, mask );
560         data->client_rect = client_rect;
561         wine_tsx11_lock();
562         XSync( gdi_display, False );  /* flush graphics operations before moving the window */
563         if (was_mapped && !is_client_window_mapped( win ))
564             XUnmapWindow( display, data->client_window );
565         XConfigureWindow( display, data->client_window, mask, &changes );
566         if (!was_mapped && is_client_window_mapped( win ))
567             XMapWindow( display, data->client_window );
568         wine_tsx11_unlock();
569     }
570     return mask;
571 }
572
573
574 /***********************************************************************
575  *              X11DRV_register_window
576  *
577  * Associate an X window to a HWND.
578  */
579 void X11DRV_register_window( Display *display, HWND hwnd, struct x11drv_win_data *data )
580 {
581     wine_tsx11_lock();
582     XSaveContext( display, data->whole_window, winContext, (char *)hwnd );
583     XSaveContext( display, data->client_window, winContext, (char *)hwnd );
584     wine_tsx11_unlock();
585 }
586
587
588 /**********************************************************************
589  *              create_desktop
590  */
591 static void create_desktop( Display *display, WND *wndPtr, CREATESTRUCTA *cs )
592 {
593     X11DRV_WND_DATA *data = wndPtr->pDriverData;
594
595     wine_tsx11_lock();
596     winContext     = XUniqueContext();
597     wmProtocols    = XInternAtom( display, "WM_PROTOCOLS", False );
598     wmDeleteWindow = XInternAtom( display, "WM_DELETE_WINDOW", False );
599 /*    wmTakeFocus    = XInternAtom( display, "WM_TAKE_FOCUS", False );*/
600     wmTakeFocus = 0;  /* not yet */
601     dndProtocol = XInternAtom( display, "DndProtocol" , False );
602     dndSelection = XInternAtom( display, "DndSelection" , False );
603     wmChangeState = XInternAtom (display, "WM_CHANGE_STATE", False);
604     kwmDockWindow = XInternAtom( display, "KWM_DOCKWINDOW", False );
605     _kde_net_wm_system_tray_window_for = XInternAtom( display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", False );
606     wine_tsx11_unlock();
607
608     whole_window_atom  = MAKEINTATOMA( GlobalAddAtomA( "__wine_x11_whole_window" ));
609     client_window_atom = MAKEINTATOMA( GlobalAddAtomA( "__wine_x11_client_window" ));
610     icon_window_atom   = MAKEINTATOMA( GlobalAddAtomA( "__wine_x11_icon_window" ));
611
612     data->whole_window = data->client_window = root_window;
613     data->whole_rect = data->client_rect = wndPtr->rectWindow;
614
615     SetPropA( wndPtr->hwndSelf, whole_window_atom, (HANDLE)root_window );
616     SetPropA( wndPtr->hwndSelf, client_window_atom, (HANDLE)root_window );
617     SetPropA( wndPtr->hwndSelf, "__wine_x11_visual_id", (HANDLE)XVisualIDFromVisual(visual) );
618
619     SendMessageW( wndPtr->hwndSelf, WM_NCCREATE, 0, (LPARAM)cs );
620     if (root_window != DefaultRootWindow(display)) X11DRV_create_desktop_thread();
621 }
622
623
624 /**********************************************************************
625  *              create_whole_window
626  *
627  * Create the whole X window for a given window
628  */
629 static Window create_whole_window( Display *display, WND *win )
630 {
631     struct x11drv_win_data *data = win->pDriverData;
632     int cx, cy, mask;
633     XSetWindowAttributes attr;
634     Window parent;
635     RECT rect;
636     BOOL is_top_level = is_window_top_level( win );
637
638     rect = win->rectWindow;
639     X11DRV_window_to_X_rect( win, &rect );
640
641     if (!(cx = rect.right - rect.left)) cx = 1;
642     if (!(cy = rect.bottom - rect.top)) cy = 1;
643
644     parent = X11DRV_get_client_window( win->parent );
645
646     wine_tsx11_lock();
647
648     mask = get_window_attributes( display, win, &attr );
649
650     /* set the attributes that don't change over the lifetime of the window */
651     attr.bit_gravity       = ForgetGravity;
652     attr.win_gravity       = NorthWestGravity;
653     attr.backing_store     = NotUseful/*WhenMapped*/;
654     mask |= CWBitGravity | CWWinGravity | CWBackingStore;
655
656     data->whole_rect = rect;
657     data->whole_window = XCreateWindow( display, parent, rect.left, rect.top, cx, cy,
658                                         0, screen_depth, InputOutput, visual,
659                                         mask, &attr );
660     if (attr.cursor) XFreeCursor( display, attr.cursor );
661
662     if (!data->whole_window)
663     {
664         wine_tsx11_unlock();
665         return 0;
666     }
667
668     /* non-maximized child must be at bottom of Z order */
669     if ((win->dwStyle & (WS_CHILD|WS_MAXIMIZE)) == WS_CHILD)
670     {
671         XWindowChanges changes;
672         changes.stack_mode = Below;
673         XConfigureWindow( display, data->whole_window, CWStackMode, &changes );
674     }
675
676     wine_tsx11_unlock();
677
678     if (is_top_level) set_wm_hints( display, win );
679
680     return data->whole_window;
681 }
682
683
684 /**********************************************************************
685  *              create_client_window
686  *
687  * Create the client window for a given window
688  */
689 static Window create_client_window( Display *display, WND *win )
690 {
691     struct x11drv_win_data *data = win->pDriverData;
692     RECT rect = data->whole_rect;
693     XSetWindowAttributes attr;
694
695     OffsetRect( &rect, -data->whole_rect.left, -data->whole_rect.top );
696     data->client_rect = rect;
697
698     attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
699                        ButtonPressMask | ButtonReleaseMask);
700     attr.bit_gravity = (win->clsStyle & (CS_VREDRAW | CS_HREDRAW)) ?
701                        ForgetGravity : NorthWestGravity;
702     attr.backing_store = NotUseful/*WhenMapped*/;
703
704     wine_tsx11_lock();
705     data->client_window = XCreateWindow( display, data->whole_window, 0, 0,
706                                          max( rect.right - rect.left, 1 ),
707                                          max( rect.bottom - rect.top, 1 ),
708                                          0, screen_depth,
709                                          InputOutput, visual,
710                                          CWEventMask | CWBitGravity | CWBackingStore, &attr );
711     if (data->client_window && is_client_window_mapped( win ))
712         XMapWindow( display, data->client_window );
713     wine_tsx11_unlock();
714     return data->client_window;
715 }
716
717
718 /*****************************************************************
719  *              SetWindowText   (X11DRV.@)
720  */
721 BOOL X11DRV_SetWindowText( HWND hwnd, LPCWSTR text )
722 {
723     Display *display = thread_display();
724     UINT count;
725     char *buffer;
726     char *utf8_buffer;
727     static UINT text_cp = (UINT)-1;
728     Window win;
729
730     if ((win = X11DRV_get_whole_window( hwnd )))
731     {
732         if (text_cp == (UINT)-1)
733         {
734             HKEY hkey;
735             /* default value */
736             text_cp = CP_ACP;
737             if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", &hkey))
738             {
739                 char buffer[20];
740                 DWORD type, count = sizeof(buffer);
741                 if(!RegQueryValueExA(hkey, "TextCP", 0, &type, buffer, &count))
742                     text_cp = atoi(buffer);
743                 RegCloseKey(hkey);
744             }
745             TRACE("text_cp = %u\n", text_cp);
746         }
747
748         /* allocate new buffer for window text */
749         count = WideCharToMultiByte(text_cp, 0, text, -1, NULL, 0, NULL, NULL);
750         if (!(buffer = HeapAlloc( GetProcessHeap(), 0, count )))
751         {
752             ERR("Not enough memory for window text\n");
753             return FALSE;
754         }
755         WideCharToMultiByte(text_cp, 0, text, -1, buffer, count, NULL, NULL);
756
757         count = WideCharToMultiByte(CP_UTF8, 0, text, strlenW(text), NULL, 0, NULL, NULL);
758         if (!(utf8_buffer = HeapAlloc( GetProcessHeap(), 0, count )))
759         {
760             ERR("Not enough memory for window text in UTF-8\n");
761             return FALSE;
762         }
763         WideCharToMultiByte(CP_UTF8, 0, text, strlenW(text), utf8_buffer, count, NULL, NULL);
764
765         wine_tsx11_lock();
766         XStoreName( display, win, buffer );
767         XSetIconName( display, win, buffer );
768         /*
769         Implements a NET_WM UTF-8 title. It should be without a trailing \0,
770         according to the standard
771         ( http://www.pps.jussieu.fr/~jch/software/UTF8_STRING/UTF8_STRING.text ).
772         */
773         XChangeProperty( display, win,
774             XInternAtom(display, "_NET_WM_NAME", False),
775             XInternAtom(display, "UTF8_STRING", False),
776             8, PropModeReplace, (unsigned char *) utf8_buffer,
777             count);
778         wine_tsx11_unlock();
779
780         HeapFree( GetProcessHeap(), 0, utf8_buffer );
781         HeapFree( GetProcessHeap(), 0, buffer );
782     }
783     return TRUE;
784 }
785
786
787 /***********************************************************************
788  *              DestroyWindow   (X11DRV.@)
789  */
790 BOOL X11DRV_DestroyWindow( HWND hwnd )
791 {
792     Display *display = thread_display();
793     WND *wndPtr = WIN_GetPtr( hwnd );
794     X11DRV_WND_DATA *data = wndPtr->pDriverData;
795
796     if (!data) goto done;
797
798     if (data->whole_window)
799     {
800         TRACE( "win %x xwin %lx/%lx\n", hwnd, data->whole_window, data->client_window );
801         wine_tsx11_lock();
802         XSync( gdi_display, False );  /* flush any reference to this drawable in GDI queue */
803         XDeleteContext( display, data->whole_window, winContext );
804         XDeleteContext( display, data->client_window, winContext );
805         XDestroyWindow( display, data->whole_window );  /* this destroys client too */
806         destroy_icon_window( display, wndPtr );
807         wine_tsx11_unlock();
808     }
809
810     if (data->hWMIconBitmap) DeleteObject( data->hWMIconBitmap );
811     if (data->hWMIconMask) DeleteObject( data->hWMIconMask);
812     HeapFree( GetProcessHeap(), 0, data );
813     wndPtr->pDriverData = NULL;
814  done:
815     WIN_ReleasePtr( wndPtr );
816     return TRUE;
817 }
818
819
820 /**********************************************************************
821  *              CreateWindow   (X11DRV.@)
822  */
823 BOOL X11DRV_CreateWindow( HWND hwnd, CREATESTRUCTA *cs, BOOL unicode )
824 {
825     HWND hwndLinkAfter;
826     Display *display = thread_display();
827     WND *wndPtr;
828     struct x11drv_win_data *data;
829     RECT rect;
830     BOOL ret = FALSE;
831
832     if (!(data = HeapAlloc(GetProcessHeap(), 0, sizeof(*data)))) return FALSE;
833     data->whole_window  = 0;
834     data->client_window = 0;
835     data->icon_window   = 0;
836     data->hWMIconBitmap = 0;
837     data->hWMIconMask   = 0;
838
839     wndPtr = WIN_GetPtr( hwnd );
840     wndPtr->pDriverData = data;
841
842     /* initialize the dimensions before sending WM_GETMINMAXINFO */
843     SetRect( &rect, cs->x, cs->y, cs->x + cs->cx, cs->y + cs->cy );
844     WIN_SetRectangles( hwnd, &rect, &rect );
845
846     if (!wndPtr->parent)
847     {
848         create_desktop( display, wndPtr, cs );
849         WIN_ReleasePtr( wndPtr );
850         return TRUE;
851     }
852
853     if (!create_whole_window( display, wndPtr )) goto failed;
854     if (!create_client_window( display, wndPtr )) goto failed;
855     TSXSync( display, False );
856
857     SetPropA( hwnd, whole_window_atom, (HANDLE)data->whole_window );
858     SetPropA( hwnd, client_window_atom, (HANDLE)data->client_window );
859
860     /* Call the WH_CBT hook */
861
862     hwndLinkAfter = ((cs->style & (WS_CHILD|WS_MAXIMIZE)) == WS_CHILD)
863  ? HWND_BOTTOM : HWND_TOP;
864
865     if (HOOK_IsHooked( WH_CBT ))
866     {
867         CBT_CREATEWNDA cbtc;
868         LRESULT lret;
869
870         cbtc.lpcs = cs;
871         cbtc.hwndInsertAfter = hwndLinkAfter;
872         lret = (unicode) ? HOOK_CallHooksW(WH_CBT, HCBT_CREATEWND,
873                                                        (WPARAM)hwnd, (LPARAM)&cbtc)
874                         : HOOK_CallHooksA(WH_CBT, HCBT_CREATEWND,
875                                                        (WPARAM)hwnd, (LPARAM)&cbtc);
876         if (lret)
877         {
878             TRACE("CBT-hook returned !0\n");
879             goto failed;
880         } 
881     }
882
883
884
885     /* Send the WM_GETMINMAXINFO message and fix the size if needed */
886     if ((cs->style & WS_THICKFRAME) || !(cs->style & (WS_POPUP | WS_CHILD)))
887     {
888         POINT maxSize, maxPos, minTrack, maxTrack;
889
890         WIN_ReleasePtr( wndPtr );
891         WINPOS_GetMinMaxInfo( hwnd, &maxSize, &maxPos, &minTrack, &maxTrack);
892         if (maxSize.x < cs->cx) cs->cx = maxSize.x;
893         if (maxSize.y < cs->cy) cs->cy = maxSize.y;
894         if (cs->cx < minTrack.x ) cs->cx = minTrack.x;
895         if (cs->cy < minTrack.y ) cs->cy = minTrack.y;
896         if (cs->cx < 0) cs->cx = 0;
897         if (cs->cy < 0) cs->cy = 0;
898
899         if (!(wndPtr = WIN_GetPtr( hwnd ))) return FALSE;
900         SetRect( &rect, cs->x, cs->y, cs->x + cs->cx, cs->y + cs->cy );
901         WIN_SetRectangles( hwnd, &rect, &rect );
902         X11DRV_sync_whole_window_position( display, wndPtr, 0 );
903     }
904     WIN_ReleasePtr( wndPtr );
905
906     /* send WM_NCCREATE */
907     TRACE( "hwnd %x cs %d,%d %dx%d\n", hwnd, cs->x, cs->y, cs->cx, cs->cy );
908     if (unicode)
909         ret = SendMessageW( hwnd, WM_NCCREATE, 0, (LPARAM)cs );
910     else
911         ret = SendMessageA( hwnd, WM_NCCREATE, 0, (LPARAM)cs );
912     if (!ret)
913     {
914         WARN("aborted by WM_xxCREATE!\n");
915         return FALSE;
916     }
917
918     if (!(wndPtr = WIN_GetPtr(hwnd))) return FALSE;
919
920     sync_window_style( display, wndPtr );
921
922     /* send WM_NCCALCSIZE */
923     rect = wndPtr->rectWindow;
924     WIN_ReleasePtr( wndPtr );
925     SendMessageW( hwnd, WM_NCCALCSIZE, FALSE, (LPARAM)&rect );
926
927     if (!(wndPtr = WIN_GetPtr(hwnd))) return FALSE;
928     if (rect.left > rect.right || rect.top > rect.bottom) rect = wndPtr->rectWindow;
929     WIN_SetRectangles( hwnd, &wndPtr->rectWindow, &rect );
930     X11DRV_sync_client_window_position( display, wndPtr );
931     X11DRV_register_window( display, hwnd, data );
932
933     TRACE( "win %x window %d,%d,%d,%d client %d,%d,%d,%d whole %d,%d,%d,%d X client %d,%d,%d,%d xwin %x/%x\n",
934            hwnd, wndPtr->rectWindow.left, wndPtr->rectWindow.top,
935            wndPtr->rectWindow.right, wndPtr->rectWindow.bottom,
936            wndPtr->rectClient.left, wndPtr->rectClient.top,
937            wndPtr->rectClient.right, wndPtr->rectClient.bottom,
938            data->whole_rect.left, data->whole_rect.top,
939            data->whole_rect.right, data->whole_rect.bottom,
940            data->client_rect.left, data->client_rect.top,
941            data->client_rect.right, data->client_rect.bottom,
942            (unsigned int)data->whole_window, (unsigned int)data->client_window );
943
944     if ((wndPtr->dwStyle & (WS_CHILD|WS_MAXIMIZE)) == WS_CHILD)
945         WIN_LinkWindow( hwnd, wndPtr->parent, HWND_BOTTOM );
946     else
947         WIN_LinkWindow( hwnd, wndPtr->parent, HWND_TOP );
948
949     WIN_ReleasePtr( wndPtr );
950
951     if (unicode)
952         ret = (SendMessageW( hwnd, WM_CREATE, 0, (LPARAM)cs ) != -1);
953     else
954         ret = (SendMessageA( hwnd, WM_CREATE, 0, (LPARAM)cs ) != -1);
955
956     if (!ret)
957     {
958         WIN_UnlinkWindow( hwnd );
959         return FALSE;
960     }
961
962     /* Send the size messages */
963
964     if (!(wndPtr = WIN_FindWndPtr(hwnd))) return FALSE;
965     if (!(wndPtr->flags & WIN_NEED_SIZE))
966     {
967         /* send it anyway */
968         if (((wndPtr->rectClient.right-wndPtr->rectClient.left) <0)
969             ||((wndPtr->rectClient.bottom-wndPtr->rectClient.top)<0))
970             WARN("sending bogus WM_SIZE message 0x%08lx\n",
971                  MAKELONG(wndPtr->rectClient.right-wndPtr->rectClient.left,
972                           wndPtr->rectClient.bottom-wndPtr->rectClient.top));
973         SendMessageW( hwnd, WM_SIZE, SIZE_RESTORED,
974                       MAKELONG(wndPtr->rectClient.right-wndPtr->rectClient.left,
975                                wndPtr->rectClient.bottom-wndPtr->rectClient.top));
976         SendMessageW( hwnd, WM_MOVE, 0,
977                       MAKELONG( wndPtr->rectClient.left, wndPtr->rectClient.top ) );
978     }
979
980     /* Show the window, maximizing or minimizing if needed */
981
982     if (wndPtr->dwStyle & (WS_MINIMIZE | WS_MAXIMIZE))
983     {
984         extern UINT WINPOS_MinMaximize( HWND hwnd, UINT cmd, LPRECT rect ); /*FIXME*/
985
986         RECT newPos;
987         UINT swFlag = (wndPtr->dwStyle & WS_MINIMIZE) ? SW_MINIMIZE : SW_MAXIMIZE;
988         WIN_SetStyle( hwnd, wndPtr->dwStyle & ~(WS_MAXIMIZE | WS_MINIMIZE) );
989         WINPOS_MinMaximize( hwnd, swFlag, &newPos );
990         swFlag = ((wndPtr->dwStyle & WS_CHILD) || GetActiveWindow())
991             ? SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED
992             : SWP_NOZORDER | SWP_FRAMECHANGED;
993         SetWindowPos( hwnd, 0, newPos.left, newPos.top,
994                       newPos.right, newPos.bottom, swFlag );
995     }
996
997     WIN_ReleaseWndPtr( wndPtr );
998     return TRUE;
999
1000
1001  failed:
1002     X11DRV_DestroyWindow( hwnd );
1003     if (wndPtr) WIN_ReleasePtr( wndPtr );
1004     return FALSE;
1005 }
1006
1007
1008 /***********************************************************************
1009  *              X11DRV_get_client_window
1010  *
1011  * Return the X window associated with the client area of a window
1012  */
1013 Window X11DRV_get_client_window( HWND hwnd )
1014 {
1015     Window ret = 0;
1016     WND *win = WIN_GetPtr( hwnd );
1017
1018     if (win == WND_OTHER_PROCESS)
1019         return GetPropA( hwnd, client_window_atom );
1020
1021     if (win)
1022     {
1023         struct x11drv_win_data *data = win->pDriverData;
1024         ret = data->client_window;
1025         WIN_ReleasePtr( win );
1026     }
1027     return ret;
1028 }
1029
1030
1031 /***********************************************************************
1032  *              X11DRV_get_whole_window
1033  *
1034  * Return the X window associated with the full area of a window
1035  */
1036 Window X11DRV_get_whole_window( HWND hwnd )
1037 {
1038     Window ret = 0;
1039     WND *win = WIN_GetPtr( hwnd );
1040
1041     if (win == WND_OTHER_PROCESS)
1042         return GetPropA( hwnd, whole_window_atom );
1043
1044     if (win)
1045     {
1046         struct x11drv_win_data *data = win->pDriverData;
1047         ret = data->whole_window;
1048         WIN_ReleasePtr( win );
1049     }
1050     return ret;
1051 }
1052
1053
1054 /*****************************************************************
1055  *              SetParent   (X11DRV.@)
1056  */
1057 HWND X11DRV_SetParent( HWND hwnd, HWND parent )
1058 {
1059     Display *display = thread_display();
1060     WND *wndPtr;
1061     HWND retvalue;
1062
1063     /* Windows hides the window first, then shows it again
1064      * including the WM_SHOWWINDOW messages and all */
1065     BOOL was_visible = ShowWindow( hwnd, SW_HIDE );
1066
1067     if (!IsWindow( parent )) return 0;
1068     if (!(wndPtr = WIN_GetPtr(hwnd)) || wndPtr == WND_OTHER_PROCESS) return 0;
1069
1070     retvalue = wndPtr->parent;  /* old parent */
1071     if (parent != retvalue)
1072     {
1073         struct x11drv_win_data *data = wndPtr->pDriverData;
1074
1075         WIN_LinkWindow( hwnd, parent, HWND_TOP );
1076
1077         if (parent != GetDesktopWindow()) /* a child window */
1078         {
1079             if (!(wndPtr->dwStyle & WS_CHILD))
1080             {
1081                 HMENU menu = (HMENU)SetWindowLongW( hwnd, GWL_ID, 0 );
1082                 if (menu) DestroyMenu( menu );
1083             }
1084         }
1085
1086         if (is_window_top_level( wndPtr )) set_wm_hints( display, wndPtr );
1087         wine_tsx11_lock();
1088         sync_window_style( display, wndPtr );
1089         XReparentWindow( display, data->whole_window, X11DRV_get_client_window(parent),
1090                          data->whole_rect.left, data->whole_rect.top );
1091         wine_tsx11_unlock();
1092     }
1093     WIN_ReleasePtr( wndPtr );
1094
1095     /* SetParent additionally needs to make hwnd the topmost window
1096        in the x-order and send the expected WM_WINDOWPOSCHANGING and
1097        WM_WINDOWPOSCHANGED notification messages. 
1098     */
1099     SetWindowPos( hwnd, HWND_TOPMOST, 0, 0, 0, 0,
1100                   SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | (was_visible ? SWP_SHOWWINDOW : 0) );
1101     /* FIXME: a WM_MOVE is also generated (in the DefWindowProc handler
1102      * for WM_WINDOWPOSCHANGED) in Windows, should probably remove SWP_NOMOVE */
1103
1104     return retvalue;
1105 }
1106
1107
1108 /*****************************************************************
1109  *              SetFocus   (X11DRV.@)
1110  *
1111  * Set the X focus.
1112  * Explicit colormap management seems to work only with OLVWM.
1113  */
1114 void X11DRV_SetFocus( HWND hwnd )
1115 {
1116     Display *display = thread_display();
1117     XWindowAttributes win_attr;
1118     Window win;
1119
1120     /* Only mess with the X focus if there's */
1121     /* no desktop window and if the window is not managed by the WM. */
1122     if (root_window != DefaultRootWindow(display)) return;
1123
1124     if (!hwnd)  /* If setting the focus to 0, uninstall the colormap */
1125     {
1126         if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
1127             TSXUninstallColormap( display, X11DRV_PALETTE_PaletteXColormap );
1128         return;
1129     }
1130
1131     hwnd = GetAncestor( hwnd, GA_ROOT );
1132     if (GetWindowLongW( hwnd, GWL_EXSTYLE ) & WS_EX_MANAGED) return;
1133     if (!(win = X11DRV_get_whole_window( hwnd ))) return;
1134
1135     /* Set X focus and install colormap */
1136     wine_tsx11_lock();
1137     if (XGetWindowAttributes( display, win, &win_attr ) &&
1138         (win_attr.map_state == IsViewable))
1139     {
1140         /* If window is not viewable, don't change anything */
1141
1142         /* we must not use CurrentTime (ICCCM), so try to use last message time instead */
1143         /* FIXME: this is not entirely correct */
1144         XSetInputFocus( display, win, RevertToParent,
1145                         /*CurrentTime*/ GetMessageTime() + X11DRV_server_startticks );
1146         if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
1147             XInstallColormap( display, X11DRV_PALETTE_PaletteXColormap );
1148     }
1149     wine_tsx11_unlock();
1150 }
1151
1152
1153 /**********************************************************************
1154  *              SetWindowIcon (X11DRV.@)
1155  *
1156  * hIcon or hIconSm has changed (or is being initialised for the
1157  * first time). Complete the X11 driver-specific initialisation
1158  * and set the window hints.
1159  *
1160  * This is not entirely correct, may need to create
1161  * an icon window and set the pixmap as a background
1162  */
1163 HICON X11DRV_SetWindowIcon( HWND hwnd, HICON icon, BOOL small )
1164 {
1165     WND *wndPtr;
1166     Display *display = thread_display();
1167     HICON old = SetClassLongW( hwnd, small ? GCL_HICONSM : GCL_HICON, icon );
1168
1169     SetWindowPos( hwnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOSIZE |
1170                   SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER );
1171
1172     if (!(wndPtr = WIN_GetPtr( hwnd )) || wndPtr == WND_OTHER_PROCESS) return old;
1173
1174     if (wndPtr->dwExStyle & WS_EX_MANAGED)
1175     {
1176         Window win = get_whole_window(wndPtr);
1177         XWMHints* wm_hints = TSXGetWMHints( display, win );
1178
1179         if (!wm_hints) wm_hints = TSXAllocWMHints();
1180         if (wm_hints)
1181         {
1182             set_icon_hints( display, wndPtr, wm_hints );
1183             TSXSetWMHints( display, win, wm_hints );
1184             TSXFree( wm_hints );
1185         }
1186     }
1187     WIN_ReleasePtr( wndPtr );
1188     return old;
1189 }