Fix loading saved states on 64-bit systems
[wmaker-crm.git] / src / window.c
1 /* window.c - client window managing stuffs
2  *
3  *  Window Maker window manager
4  *
5  *  Copyright (c) 1997-2003 Alfredo K. Kojima
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program 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
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20  *  USA.
21  */
22
23 #include "wconfig.h"
24
25 #include <X11/Xlib.h>
26 #include <X11/Xutil.h>
27 #ifdef SHAPE
28 #include <X11/extensions/shape.h>
29 #endif
30 #ifdef KEEP_XKB_LOCK_STATUS
31 #include <X11/XKBlib.h>
32 #endif    /* KEEP_XKB_LOCK_STATUS */
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdint.h>
37 #include <math.h>
38
39 /* For getting mouse wheel mappings from WINGs */
40 #include <WINGs/WINGsP.h>
41
42 #include "WindowMaker.h"
43 #include "GNUstep.h"
44 #include "wcore.h"
45 #include "framewin.h"
46 #include "texture.h"
47 #include "window.h"
48 #include "winspector.h"
49 #include "icon.h"
50 #include "properties.h"
51 #include "actions.h"
52 #include "client.h"
53 #include "funcs.h"
54 #include "keybind.h"
55 #include "stacking.h"
56 #include "defaults.h"
57 #include "workspace.h"
58 #include "xinerama.h"
59
60 #ifdef MWM_HINTS
61 # include "motif.h"
62 #endif
63 #include "wmspec.h"
64
65 #define MOD_MASK wPreferences.modifier_mask
66
67 /****** Global Variables ******/
68 extern WShortKey wKeyBindings[WKBD_LAST];
69
70 #ifdef SHAPE
71 extern Bool wShapeSupported;
72 #endif
73
74 /* contexts */
75 extern XContext wWinContext;
76
77 /* cursors */
78 extern Cursor wCursor[WCUR_LAST];
79
80 /* protocol atoms */
81 extern Atom _XA_WM_DELETE_WINDOW;
82 extern Atom _XA_GNUSTEP_WM_MINIATURIZE_WINDOW;
83 extern Atom _XA_WINDOWMAKER_STATE;
84
85 extern WPreferences wPreferences;
86 extern Time LastTimestamp;
87
88 /* superfluous... */
89 extern void DoWindowBirth(WWindow *wwin);
90
91 /***** Local Stuff *****/
92 static WWindowState *windowState = NULL;
93
94 static FocusMode getFocusMode(WWindow *wwin);
95 static int getSavedState(Window window, WSavedState **state);
96 static void setupGNUstepHints(WWindow *wwin, GNUstepWMAttributes *gs_hints);
97
98 /* frame window (during window grabs) */
99 static void frameMouseDown(WObjDescriptor *desc, XEvent *event);
100
101 /* close button */
102 static void windowCloseClick(WCoreWindow *sender, void *data, XEvent *event);
103 static void windowCloseDblClick(WCoreWindow *sender, void *data, XEvent *event);
104
105 /* iconify button */
106 static void windowIconifyClick(WCoreWindow *sender, void *data, XEvent *event);
107
108 #ifdef XKB_BUTTON_HINT
109 static void windowLanguageClick(WCoreWindow *sender, void *data, XEvent *event);
110 #endif
111
112 static void titlebarMouseDown(WCoreWindow *sender, void *data, XEvent *event);
113 static void titlebarDblClick(WCoreWindow *sender, void *data, XEvent *event);
114 static void resizebarMouseDown(WCoreWindow *sender, void *data, XEvent *event);
115
116 /****** Notification Observers ******/
117
118 static void appearanceObserver(void *self, WMNotification * notif)
119 {
120         WWindow *wwin = (WWindow *) self;
121         uintptr_t flags = (uintptr_t)WMGetNotificationClientData(notif);
122
123         if (!wwin->frame || (!wwin->frame->titlebar && !wwin->frame->resizebar))
124                 return;
125
126         if (flags & WFontSettings) {
127                 wWindowConfigureBorders(wwin);
128                 if (wwin->flags.shaded) {
129                         wFrameWindowResize(wwin->frame, wwin->frame->core->width, wwin->frame->top_width - 1);
130
131                         wwin->client.y = wwin->frame_y - wwin->client.height + wwin->frame->top_width;
132                         wWindowSynthConfigureNotify(wwin);
133                 }
134         }
135         if (flags & WTextureSettings) {
136                 wwin->frame->flags.need_texture_remake = 1;
137         }
138         if (flags & (WTextureSettings | WColorSettings)) {
139                 if (wwin->frame->titlebar)
140                         XClearWindow(dpy, wwin->frame->titlebar->window);
141
142                 wFrameWindowPaint(wwin->frame);
143         }
144 }
145
146
147 WWindow *wWindowFor(Window window)
148 {
149         WObjDescriptor *desc;
150
151         if (window == None)
152                 return NULL;
153
154         if (XFindContext(dpy, window, wWinContext, (XPointer *) & desc) == XCNOENT)
155                 return NULL;
156
157         if (desc->parent_type == WCLASS_WINDOW)
158                 return desc->parent;
159         else if (desc->parent_type == WCLASS_FRAME) {
160                 WFrameWindow *frame = (WFrameWindow *) desc->parent;
161                 if (frame->flags.is_client_window_frame)
162                         return frame->child;
163         }
164
165         return NULL;
166 }
167
168 WWindow *wWindowCreate()
169 {
170         WWindow *wwin;
171
172         wwin = wmalloc(sizeof(WWindow));
173         wretain(wwin);
174
175         memset(wwin, 0, sizeof(WWindow));
176
177         wwin->client_descriptor.handle_mousedown = frameMouseDown;
178         wwin->client_descriptor.parent = wwin;
179         wwin->client_descriptor.self = wwin;
180         wwin->client_descriptor.parent_type = WCLASS_WINDOW;
181
182         return wwin;
183 }
184
185 void wWindowDestroy(WWindow *wwin)
186 {
187         int i;
188
189         if (wwin->screen_ptr->cmap_window == wwin)
190                 wwin->screen_ptr->cmap_window = NULL;
191
192         WMRemoveNotificationObserver(wwin);
193
194         wwin->flags.destroyed = 1;
195
196         for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
197                 if (!wwin->screen_ptr->shortcutWindows[i])
198                         continue;
199
200                 WMRemoveFromArray(wwin->screen_ptr->shortcutWindows[i], wwin);
201
202                 if (!WMGetArrayItemCount(wwin->screen_ptr->shortcutWindows[i])) {
203                         WMFreeArray(wwin->screen_ptr->shortcutWindows[i]);
204                         wwin->screen_ptr->shortcutWindows[i] = NULL;
205                 }
206         }
207
208         if (wwin->fake_group && wwin->fake_group->retainCount > 0) {
209                 wwin->fake_group->retainCount--;
210                 if (wwin->fake_group->retainCount == 0 && wwin->fake_group->leader != None) {
211                         XDestroyWindow(dpy, wwin->fake_group->leader);
212                         wwin->fake_group->leader = None;
213                         wwin->fake_group->origLeader = None;
214                         XFlush(dpy);
215                 }
216         }
217
218         if (wwin->normal_hints)
219                 XFree(wwin->normal_hints);
220
221         if (wwin->wm_hints)
222                 XFree(wwin->wm_hints);
223
224         if (wwin->wm_instance)
225                 XFree(wwin->wm_instance);
226
227         if (wwin->wm_class)
228                 XFree(wwin->wm_class);
229
230         if (wwin->wm_gnustep_attr)
231                 wfree(wwin->wm_gnustep_attr);
232
233         if (wwin->cmap_windows)
234                 XFree(wwin->cmap_windows);
235
236         XDeleteContext(dpy, wwin->client_win, wWinContext);
237
238         if (wwin->frame)
239                 wFrameWindowDestroy(wwin->frame);
240
241         if (wwin->icon) {
242                 RemoveFromStackList(wwin->icon->core);
243                 wIconDestroy(wwin->icon);
244                 if (wPreferences.auto_arrange_icons)
245                         wArrangeIcons(wwin->screen_ptr, True);
246         }
247         if (wwin->net_icon_image)
248                 RReleaseImage(wwin->net_icon_image);
249
250         wrelease(wwin);
251 }
252
253 static void setupGNUstepHints(WWindow *wwin, GNUstepWMAttributes *gs_hints)
254 {
255         if (gs_hints->flags & GSWindowStyleAttr) {
256                 if (gs_hints->window_style == WMBorderlessWindowMask) {
257                         wwin->client_flags.no_border = 1;
258                         wwin->client_flags.no_titlebar = 1;
259                         wwin->client_flags.no_closable = 1;
260                         wwin->client_flags.no_miniaturizable = 1;
261                         wwin->client_flags.no_resizable = 1;
262                         wwin->client_flags.no_close_button = 1;
263                         wwin->client_flags.no_miniaturize_button = 1;
264                         wwin->client_flags.no_resizebar = 1;
265                 } else {
266                         wwin->client_flags.no_close_button =
267                             ((gs_hints->window_style & WMClosableWindowMask) ? 0 : 1);
268
269                         wwin->client_flags.no_closable = ((gs_hints->window_style & WMClosableWindowMask) ? 0 : 1);
270
271                         wwin->client_flags.no_miniaturize_button =
272                             ((gs_hints->window_style & WMMiniaturizableWindowMask) ? 0 : 1);
273
274                         wwin->client_flags.no_miniaturizable = wwin->client_flags.no_miniaturize_button;
275
276                         wwin->client_flags.no_resizebar =
277                             ((gs_hints->window_style & WMResizableWindowMask) ? 0 : 1);
278
279                         wwin->client_flags.no_resizable = wwin->client_flags.no_resizebar;
280
281                         /* these attributes supposedly imply in the existence
282                          * of a titlebar */
283                         if (gs_hints->window_style & (WMResizableWindowMask |
284                                                       WMClosableWindowMask | WMMiniaturizableWindowMask)) {
285                                 wwin->client_flags.no_titlebar = 0;
286                         } else {
287                                 wwin->client_flags.no_titlebar =
288                                     ((gs_hints->window_style & WMTitledWindowMask) ? 0 : 1);
289                         }
290
291                 }
292         } else {
293                 /* setup the defaults */
294                 wwin->client_flags.no_border = 0;
295                 wwin->client_flags.no_titlebar = 0;
296                 wwin->client_flags.no_closable = 0;
297                 wwin->client_flags.no_miniaturizable = 0;
298                 wwin->client_flags.no_resizable = 0;
299                 wwin->client_flags.no_close_button = 0;
300                 wwin->client_flags.no_miniaturize_button = 0;
301                 wwin->client_flags.no_resizebar = 0;
302         }
303         if (gs_hints->extra_flags & GSNoApplicationIconFlag)
304                 wwin->client_flags.no_appicon = 1;
305 }
306
307 void wWindowSetupInitialAttributes(WWindow *wwin, int *level, int *workspace)
308 {
309         WScreen *scr = wwin->screen_ptr;
310
311         /* sets global default stuff */
312         wDefaultFillAttributes(scr, wwin->wm_instance, wwin->wm_class, &wwin->client_flags, NULL, True);
313         /*
314          * Decoration setting is done in this precedence (lower to higher)
315          * - use global default in the resource database
316          * - guess some settings
317          * - use GNUstep/external window attributes
318          * - set hints specified for the app in the resource DB
319          *
320          */
321         WSETUFLAG(wwin, broken_close, 0);
322
323         if (wwin->protocols.DELETE_WINDOW)
324                 WSETUFLAG(wwin, kill_close, 0);
325         else
326                 WSETUFLAG(wwin, kill_close, 1);
327
328         /* transients can't be iconified or maximized */
329         if (wwin->transient_for != None && wwin->transient_for != scr->root_win) {
330                 WSETUFLAG(wwin, no_miniaturizable, 1);
331                 WSETUFLAG(wwin, no_miniaturize_button, 1);
332         }
333
334         /* if the window can't be resized, remove the resizebar */
335         if (wwin->normal_hints->flags & (PMinSize | PMaxSize)
336             && (wwin->normal_hints->min_width == wwin->normal_hints->max_width)
337             && (wwin->normal_hints->min_height == wwin->normal_hints->max_height)) {
338                 WSETUFLAG(wwin, no_resizable, 1);
339                 WSETUFLAG(wwin, no_resizebar, 1);
340         }
341
342         /* set GNUstep window attributes */
343         if (wwin->wm_gnustep_attr) {
344                 setupGNUstepHints(wwin, wwin->wm_gnustep_attr);
345
346                 if (wwin->wm_gnustep_attr->flags & GSWindowLevelAttr) {
347
348                         *level = wwin->wm_gnustep_attr->window_level;
349                         /*
350                          * INT_MIN is the only illegal window level.
351                          */
352                         if (*level == INT_MIN)
353                                 *level = INT_MIN + 1;
354                 } else {
355                         /* setup defaults */
356                         *level = WMNormalLevel;
357                 }
358         } else {
359                 int tmp_workspace = -1;
360                 int tmp_level = INT_MIN;        /* INT_MIN is never used by the window levels */
361                 Bool check;
362
363                 check = False;
364
365 #ifdef MWM_HINTS
366                 wMWMCheckClientHints(wwin);
367 #endif                          /* MWM_HINTS */
368
369                 if (!check)
370                         check = wNETWMCheckClientHints(wwin, &tmp_level, &tmp_workspace);
371
372                 /* window levels are between INT_MIN+1 and INT_MAX, so if we still
373                  * have INT_MIN that means that no window level was requested. -Dan
374                  */
375                 if (tmp_level == INT_MIN) {
376                         if (WFLAGP(wwin, floating))
377                                 *level = WMFloatingLevel;
378                         else if (WFLAGP(wwin, sunken))
379                                 *level = WMSunkenLevel;
380                         else
381                                 *level = WMNormalLevel;
382                 } else {
383                         *level = tmp_level;
384                 }
385
386                 if (wwin->transient_for != None && wwin->transient_for != scr->root_win) {
387                         WWindow *transientOwner = wWindowFor(wwin->transient_for);
388                         if (transientOwner) {
389                                 int ownerLevel = transientOwner->frame->core->stacking->window_level;
390                                 if (ownerLevel > *level)
391                                         *level = ownerLevel;
392                         }
393                 }
394
395                 if (tmp_workspace >= 0)
396                         *workspace = tmp_workspace % scr->workspace_count;
397         }
398
399         /*
400          * Set attributes specified only for that window/class.
401          * This might do duplicate work with the 1st wDefaultFillAttributes().
402          */
403         wDefaultFillAttributes(scr, wwin->wm_instance, wwin->wm_class,
404                                &wwin->user_flags, &wwin->defined_user_flags, False);
405         /*
406          * Sanity checks for attributes that depend on other attributes
407          */
408         if (wwin->user_flags.no_appicon && wwin->defined_user_flags.no_appicon)
409                 wwin->user_flags.emulate_appicon = 0;
410
411         if (wwin->main_window != None) {
412                 WApplication *wapp = wApplicationOf(wwin->main_window);
413                 if (wapp && !wapp->flags.emulated)
414                         wwin->user_flags.emulate_appicon = 0;
415         }
416
417         if (wwin->transient_for != None && wwin->transient_for != wwin->screen_ptr->root_win)
418                 wwin->user_flags.emulate_appicon = 0;
419
420         if (wwin->user_flags.sunken && wwin->defined_user_flags.sunken
421             && wwin->user_flags.floating && wwin->defined_user_flags.floating)
422                 wwin->user_flags.sunken = 0;
423
424         WSETUFLAG(wwin, no_shadeable, WFLAGP(wwin, no_titlebar));
425
426         /* windows that have takefocus=False shouldn't take focus at all */
427         if (wwin->focus_mode == WFM_NO_INPUT)
428                 wwin->client_flags.no_focusable = 1;
429 }
430
431 Bool wWindowCanReceiveFocus(WWindow *wwin)
432 {
433         if (!wwin->flags.mapped && (!wwin->flags.shaded || wwin->flags.hidden))
434                 return False;
435         if (WFLAGP(wwin, no_focusable) || wwin->flags.miniaturized)
436                 return False;
437         if (wwin->frame->workspace != wwin->screen_ptr->current_workspace)
438                 return False;
439
440         return True;
441 }
442
443 Bool wWindowObscuresWindow(WWindow *wwin, WWindow *obscured)
444 {
445         int w1, h1, w2, h2;
446
447         w1 = wwin->frame->core->width;
448         h1 = wwin->frame->core->height;
449         w2 = obscured->frame->core->width;
450         h2 = obscured->frame->core->height;
451
452         if (!IS_OMNIPRESENT(wwin) && !IS_OMNIPRESENT(obscured)
453             && wwin->frame->workspace != obscured->frame->workspace)
454                 return False;
455
456         if (wwin->frame_x + w1 < obscured->frame_x
457             || wwin->frame_y + h1 < obscured->frame_y
458             || wwin->frame_x > obscured->frame_x + w2 || wwin->frame_y > obscured->frame_y + h2)
459                 return False;
460
461         return True;
462 }
463
464 static void fixLeaderProperties(WWindow *wwin)
465 {
466         XClassHint *classHint;
467         XWMHints *hints, *clientHints;
468         Window leaders[2], window;
469         char **argv, *command;
470         int argc, i, pid;
471         Bool haveCommand;
472
473         classHint = XAllocClassHint();
474         clientHints = XGetWMHints(dpy, wwin->client_win);
475         pid = wNETWMGetPidForWindow(wwin->client_win);
476         if (pid > 0)
477                 haveCommand = GetCommandForPid(pid, &argv, &argc);
478         else
479                 haveCommand = False;
480
481         leaders[0] = wwin->client_leader;
482         leaders[1] = wwin->group_id;
483
484         if (haveCommand) {
485                 command = GetCommandForWindow(wwin->client_win);
486                 if (command) {
487                         /* command already set. nothing to do. */
488                         wfree(command);
489                 } else {
490                         XSetCommand(dpy, wwin->client_win, argv, argc);
491                 }
492         }
493
494         for (i = 0; i < 2; i++) {
495                 window = leaders[i];
496                 if (window) {
497                         if (XGetClassHint(dpy, window, classHint) == 0) {
498                                 classHint->res_name = wwin->wm_instance;
499                                 classHint->res_class = wwin->wm_class;
500                                 XSetClassHint(dpy, window, classHint);
501                         }
502                         hints = XGetWMHints(dpy, window);
503                         if (hints) {
504                                 XFree(hints);
505                         } else if (clientHints) {
506                                 /* set window group leader to self */
507                                 clientHints->window_group = window;
508                                 clientHints->flags |= WindowGroupHint;
509                                 XSetWMHints(dpy, window, clientHints);
510                         }
511
512                         if (haveCommand) {
513                                 command = GetCommandForWindow(window);
514                                 if (command) {
515                                         /* command already set. nothing to do. */
516                                         wfree(command);
517                                 } else {
518                                         XSetCommand(dpy, window, argv, argc);
519                                 }
520                         }
521                 }
522         }
523
524         XFree(classHint);
525         if (clientHints)
526                 XFree(clientHints);
527         if (haveCommand)
528                 wfree(argv);
529 }
530
531 static Window createFakeWindowGroupLeader(WScreen *scr, Window win, char *instance, char *class)
532 {
533         XClassHint *classHint;
534         XWMHints *hints;
535         Window leader;
536         int argc;
537         char **argv;
538
539         leader = XCreateSimpleWindow(dpy, scr->root_win, 10, 10, 10, 10, 0, 0, 0);
540         /* set class hint */
541         classHint = XAllocClassHint();
542         classHint->res_name = instance;
543         classHint->res_class = class;
544         XSetClassHint(dpy, leader, classHint);
545         XFree(classHint);
546
547         /* inherit these from the original leader if available */
548         hints = XGetWMHints(dpy, win);
549         if (!hints) {
550                 hints = XAllocWMHints();
551                 hints->flags = 0;
552         }
553         /* set window group leader to self */
554         hints->window_group = leader;
555         hints->flags |= WindowGroupHint;
556         XSetWMHints(dpy, leader, hints);
557         XFree(hints);
558
559         if (XGetCommand(dpy, win, &argv, &argc) != 0 && argc > 0) {
560                 XSetCommand(dpy, leader, argv, argc);
561                 XFreeStringList(argv);
562         }
563
564         return leader;
565 }
566
567 static int matchIdentifier(const void *item, const void *cdata)
568 {
569         return (strcmp(((WFakeGroupLeader *) item)->identifier, (char *)cdata) == 0);
570 }
571
572 /*
573  *----------------------------------------------------------------
574  * wManageWindow--
575  *      reparents the window and allocates a descriptor for it.
576  * Window manager hints and other hints are fetched to configure
577  * the window decoration attributes and others. User preferences
578  * for the window are used if available, to configure window
579  * decorations and some behaviour.
580  *      If in startup, windows that are override redirect,
581  * unmapped and never were managed and are Withdrawn are not
582  * managed.
583  *
584  * Returns:
585  *      the new window descriptor
586  *
587  * Side effects:
588  *      The window is reparented and appropriate notification
589  * is done to the client. Input mask for the window is setup.
590  *      The window descriptor is also associated with various window
591  * contexts and inserted in the head of the window list.
592  * Event handler contexts are associated for some objects
593  * (buttons, titlebar and resizebar)
594  *
595  *----------------------------------------------------------------
596  */
597 WWindow *wManageWindow(WScreen *scr, Window window)
598 {
599         WWindow *wwin;
600         int x, y;
601         unsigned width, height;
602         XWindowAttributes wattribs;
603         XSetWindowAttributes attribs;
604         WWindowState *win_state;
605         WWindow *transientOwner = NULL;
606         int window_level;
607         int wm_state;
608         int foo;
609         int workspace = -1;
610         char *title;
611         Bool withdraw = False;
612         Bool raise = False;
613
614         /* mutex. */
615         XGrabServer(dpy);
616         XSync(dpy, False);
617         /* make sure the window is still there */
618         if (!XGetWindowAttributes(dpy, window, &wattribs)) {
619                 XUngrabServer(dpy);
620                 return NULL;
621         }
622
623         /* if it's an override-redirect, ignore it */
624         if (wattribs.override_redirect) {
625                 XUngrabServer(dpy);
626                 return NULL;
627         }
628
629         wm_state = PropGetWindowState(window);
630
631         /* if it's startup and the window is unmapped, don't manage it */
632         if (scr->flags.startup && wm_state < 0 && wattribs.map_state == IsUnmapped) {
633                 XUngrabServer(dpy);
634                 return NULL;
635         }
636
637         wwin = wWindowCreate();
638
639         title = wNETWMGetWindowName(window);
640         if (title)
641                 wwin->flags.net_has_title = 1;
642         if (!title && !wFetchName(dpy, window, &title))
643                 title = NULL;
644
645         XSaveContext(dpy, window, wWinContext, (XPointer) & wwin->client_descriptor);
646
647 #ifdef SHAPE
648         if (wShapeSupported) {
649                 int junk;
650                 unsigned int ujunk;
651                 int b_shaped;
652
653                 XShapeSelectInput(dpy, window, ShapeNotifyMask);
654                 XShapeQueryExtents(dpy, window, &b_shaped, &junk, &junk, &ujunk,
655                                    &ujunk, &junk, &junk, &junk, &ujunk, &ujunk);
656                 wwin->flags.shaped = b_shaped;
657         }
658 #endif
659
660         /*
661          * Get hints and other information in properties
662          */
663         PropGetWMClass(window, &wwin->wm_class, &wwin->wm_instance);
664
665         /* setup descriptor */
666         wwin->client_win = window;
667         wwin->screen_ptr = scr;
668         wwin->old_border_width = wattribs.border_width;
669         wwin->event_mask = CLIENT_EVENTS;
670         attribs.event_mask = CLIENT_EVENTS;
671         attribs.do_not_propagate_mask = ButtonPressMask | ButtonReleaseMask;
672         attribs.save_under = False;
673
674         XChangeWindowAttributes(dpy, window, CWEventMask | CWDontPropagate | CWSaveUnder, &attribs);
675         XSetWindowBorderWidth(dpy, window, 0);
676
677         /* get hints from GNUstep app */
678         if (wwin->wm_class != 0 && strcmp(wwin->wm_class, "GNUstep") == 0) {
679                 wwin->flags.is_gnustep = 1;
680         }
681         if (!PropGetGNUstepWMAttr(window, &wwin->wm_gnustep_attr)) {
682                 wwin->wm_gnustep_attr = NULL;
683         }
684
685         wwin->client_leader = PropGetClientLeader(window);
686         if (wwin->client_leader != None)
687                 wwin->main_window = wwin->client_leader;
688
689         wwin->wm_hints = XGetWMHints(dpy, window);
690
691         if (wwin->wm_hints) {
692                 if (wwin->wm_hints->flags & StateHint) {
693
694                         if (wwin->wm_hints->initial_state == IconicState) {
695
696                                 wwin->flags.miniaturized = 1;
697
698                         } else if (wwin->wm_hints->initial_state == WithdrawnState) {
699
700                                 withdraw = True;
701                         }
702                 }
703
704                 if (wwin->wm_hints->flags & WindowGroupHint) {
705                         wwin->group_id = wwin->wm_hints->window_group;
706                         /* window_group has priority over CLIENT_LEADER */
707                         wwin->main_window = wwin->group_id;
708                 } else {
709                         wwin->group_id = None;
710                 }
711
712                 if (wwin->wm_hints->flags & UrgencyHint)
713                         wwin->flags.urgent = 1;
714         } else {
715                 wwin->group_id = None;
716         }
717
718         PropGetProtocols(window, &wwin->protocols);
719
720         if (!XGetTransientForHint(dpy, window, &wwin->transient_for)) {
721                 wwin->transient_for = None;
722         } else {
723                 if (wwin->transient_for == None || wwin->transient_for == window) {
724                         wwin->transient_for = scr->root_win;
725                 } else {
726                         transientOwner = wWindowFor(wwin->transient_for);
727                         if (transientOwner && transientOwner->main_window != None)
728                                 wwin->main_window = transientOwner->main_window;
729                 }
730         }
731
732         /* guess the focus mode */
733         wwin->focus_mode = getFocusMode(wwin);
734
735         /* get geometry stuff */
736         wClientGetNormalHints(wwin, &wattribs, True, &x, &y, &width, &height);
737
738         /* get colormap windows */
739         GetColormapWindows(wwin);
740
741         /*
742          * Setup the decoration/window attributes and
743          * geometry
744          */
745         wWindowSetupInitialAttributes(wwin, &window_level, &workspace);
746
747         /* Make broken apps behave as a nice app. */
748         if (WFLAGP(wwin, emulate_appicon))
749                 wwin->main_window = wwin->client_win;
750
751         fixLeaderProperties(wwin);
752
753         wwin->orig_main_window = wwin->main_window;
754
755         if (wwin->flags.is_gnustep)
756                 WSETUFLAG(wwin, shared_appicon, 0);
757
758         if (wwin->main_window) {
759                 extern Atom _XA_WINDOWMAKER_MENU;
760                 XTextProperty text_prop;
761
762                 if (XGetTextProperty(dpy, wwin->main_window, &text_prop, _XA_WINDOWMAKER_MENU)) {
763                         WSETUFLAG(wwin, shared_appicon, 0);
764                 }
765         }
766
767         if (!withdraw && wwin->main_window && WFLAGP(wwin, shared_appicon)) {
768                 char *buffer, *instance, *class;
769                 WFakeGroupLeader *fPtr;
770                 int index;
771
772 #define ADEQUATE(x) ((x)!=None && (x)!=wwin->client_win && (x)!=fPtr->leader)
773
774                 /* // only enter here if PropGetWMClass() succeds */
775                 PropGetWMClass(wwin->main_window, &class, &instance);
776                 buffer = StrConcatDot(instance, class);
777
778                 index = WMFindInArray(scr->fakeGroupLeaders, matchIdentifier, (void *)buffer);
779                 if (index != WANotFound) {
780                         fPtr = WMGetFromArray(scr->fakeGroupLeaders, index);
781                         if (fPtr->retainCount == 0) {
782                                 fPtr->leader = createFakeWindowGroupLeader(scr, wwin->main_window,
783                                                                            instance, class);
784                         }
785                         fPtr->retainCount++;
786                         if (fPtr->origLeader == None) {
787                                 if (ADEQUATE(wwin->main_window)) {
788                                         fPtr->retainCount++;
789                                         fPtr->origLeader = wwin->main_window;
790                                 }
791                         }
792                         wwin->fake_group = fPtr;
793                         /*wwin->group_id = fPtr->leader; */
794                         wwin->main_window = fPtr->leader;
795                         wfree(buffer);
796                 } else {
797                         fPtr = (WFakeGroupLeader *) wmalloc(sizeof(WFakeGroupLeader));
798
799                         fPtr->identifier = buffer;
800                         fPtr->leader = createFakeWindowGroupLeader(scr, wwin->main_window, instance, class);
801                         fPtr->origLeader = None;
802                         fPtr->retainCount = 1;
803
804                         WMAddToArray(scr->fakeGroupLeaders, fPtr);
805
806                         if (ADEQUATE(wwin->main_window)) {
807                                 fPtr->retainCount++;
808                                 fPtr->origLeader = wwin->main_window;
809                         }
810                         wwin->fake_group = fPtr;
811                         /*wwin->group_id = fPtr->leader; */
812                         wwin->main_window = fPtr->leader;
813                 }
814                 if (instance)
815                         XFree(instance);
816                 if (class)
817                         XFree(class);
818 #undef ADEQUATE
819         }
820
821         /*
822          * Setup the initial state of the window
823          */
824         if (WFLAGP(wwin, start_miniaturized) && !WFLAGP(wwin, no_miniaturizable))
825                 wwin->flags.miniaturized = 1;
826
827         if (WFLAGP(wwin, start_maximized) && IS_RESIZABLE(wwin))
828                 wwin->flags.maximized = MAX_VERTICAL | MAX_HORIZONTAL;
829
830         wNETWMCheckInitialClientState(wwin);
831
832         /* apply previous state if it exists and we're in startup */
833         if (scr->flags.startup && wm_state >= 0) {
834
835                 if (wm_state == IconicState) {
836
837                         wwin->flags.miniaturized = 1;
838
839                 } else if (wm_state == WithdrawnState) {
840
841                         withdraw = True;
842                 }
843         }
844
845         /* if there is a saved state (from file), restore it */
846         win_state = NULL;
847         if (wwin->main_window != None)
848                 win_state = (WWindowState *) wWindowGetSavedState(wwin->main_window);
849         else
850                 win_state = (WWindowState *) wWindowGetSavedState(window);
851
852         if (win_state && !withdraw) {
853                 if (win_state->state->hidden > 0)
854                         wwin->flags.hidden = win_state->state->hidden;
855
856                 if (win_state->state->shaded > 0 && !WFLAGP(wwin, no_shadeable))
857                         wwin->flags.shaded = win_state->state->shaded;
858
859                 if (win_state->state->miniaturized > 0 && !WFLAGP(wwin, no_miniaturizable)) {
860                         wwin->flags.miniaturized = win_state->state->miniaturized;
861                 }
862
863                 if (!IS_OMNIPRESENT(wwin)) {
864                         int w = wDefaultGetStartWorkspace(scr, wwin->wm_instance,
865                                                           wwin->wm_class);
866                         if (w < 0 || w >= scr->workspace_count) {
867                                 workspace = win_state->state->workspace;
868                                 if (workspace >= scr->workspace_count)
869                                         workspace = scr->current_workspace;
870                         } else {
871                                 workspace = w;
872                         }
873                 } else {
874                         workspace = scr->current_workspace;
875                 }
876         }
877
878         /* if we're restarting, restore saved state (from hints).
879          * This will overwrite previous */
880         {
881                 WSavedState *wstate;
882
883                 if (getSavedState(window, &wstate)) {
884                         wwin->flags.shaded = wstate->shaded;
885                         wwin->flags.hidden = wstate->hidden;
886                         wwin->flags.miniaturized = wstate->miniaturized;
887                         wwin->flags.maximized = wstate->maximized;
888                         if (wwin->flags.maximized) {
889                                 wwin->old_geometry.x = wstate->x;
890                                 wwin->old_geometry.y = wstate->y;
891                                 wwin->old_geometry.width = wstate->w;
892                                 wwin->old_geometry.height = wstate->h;
893                         }
894
895                         workspace = wstate->workspace;
896                 } else {
897                         wstate = NULL;
898                 }
899
900                 /* restore window shortcut */
901                 if (wstate != NULL || win_state != NULL) {
902                         unsigned mask = 0;
903
904                         if (win_state != NULL)
905                                 mask = win_state->state->window_shortcuts;
906
907                         if (wstate != NULL && mask == 0)
908                                 mask = wstate->window_shortcuts;
909
910                         if (mask > 0) {
911                                 int i;
912
913                                 for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
914                                         if (mask & (1 << i)) {
915                                                 if (!scr->shortcutWindows[i])
916                                                         scr->shortcutWindows[i] = WMCreateArray(4);
917
918                                                 WMAddToArray(scr->shortcutWindows[i], wwin);
919                                         }
920                                 }
921                         }
922                 }
923                 if (wstate != NULL)
924                         wfree(wstate);
925         }
926
927         /* don't let transients start miniaturized if their owners are not */
928         if (transientOwner && !transientOwner->flags.miniaturized && wwin->flags.miniaturized && !withdraw) {
929                 wwin->flags.miniaturized = 0;
930                 if (wwin->wm_hints)
931                         wwin->wm_hints->initial_state = NormalState;
932         }
933
934         /* set workspace on which the window starts */
935         if (workspace >= 0) {
936                 if (workspace > scr->workspace_count - 1) {
937                         workspace = workspace % scr->workspace_count;
938                 }
939         } else {
940                 int w;
941
942                 w = wDefaultGetStartWorkspace(scr, wwin->wm_instance, wwin->wm_class);
943
944                 if (w >= 0 && w < scr->workspace_count && !(IS_OMNIPRESENT(wwin))) {
945
946                         workspace = w;
947
948                 } else {
949                         if (wPreferences.open_transients_with_parent && transientOwner) {
950
951                                 workspace = transientOwner->frame->workspace;
952
953                         } else {
954
955                                 workspace = scr->current_workspace;
956                         }
957                 }
958         }
959
960         /* setup window geometry */
961         if (win_state && win_state->state->w > 0) {
962                 width = win_state->state->w;
963                 height = win_state->state->h;
964         }
965         wWindowConstrainSize(wwin, &width, &height);
966
967         /* do not ask for window placement if the window is
968          * transient, during startup, if the initial workspace is another one
969          * or if the window wants to start iconic.
970          * If geometry was saved, restore it. */
971         {
972                 Bool dontBring = False;
973
974                 if (win_state && win_state->state->w > 0) {
975                         x = win_state->state->x;
976                         y = win_state->state->y;
977                 } else if ((wwin->transient_for == None || wPreferences.window_placement != WPM_MANUAL)
978                            && !scr->flags.startup
979                            && workspace == scr->current_workspace
980                            && !wwin->flags.miniaturized
981                            && !wwin->flags.maximized && !(wwin->normal_hints->flags & (USPosition | PPosition))) {
982
983                         if (transientOwner && transientOwner->flags.mapped) {
984                                 int offs = WMAX(20, 2 * transientOwner->frame->top_width);
985                                 WMRect rect;
986                                 int head;
987
988                                 x = transientOwner->frame_x +
989                                     abs((transientOwner->frame->core->width - width) / 2) + offs;
990                                 y = transientOwner->frame_y +
991                                     abs((transientOwner->frame->core->height - height) / 3) + offs;
992
993                                 /*
994                                  * limit transient windows to be inside their parent's head
995                                  */
996                                 rect.pos.x = transientOwner->frame_x;
997                                 rect.pos.y = transientOwner->frame_y;
998                                 rect.size.width = transientOwner->frame->core->width;
999                                 rect.size.height = transientOwner->frame->core->height;
1000
1001                                 head = wGetHeadForRect(scr, rect);
1002                                 rect = wGetRectForHead(scr, head);
1003
1004                                 if (x < rect.pos.x)
1005                                         x = rect.pos.x;
1006                                 else if (x + width > rect.pos.x + rect.size.width)
1007                                         x = rect.pos.x + rect.size.width - width;
1008
1009                                 if (y < rect.pos.y)
1010                                         y = rect.pos.y;
1011                                 else if (y + height > rect.pos.y + rect.size.height)
1012                                         y = rect.pos.y + rect.size.height - height;
1013
1014                         } else {
1015                                 PlaceWindow(wwin, &x, &y, width, height);
1016                         }
1017                         if (wPreferences.window_placement == WPM_MANUAL) {
1018                                 dontBring = True;
1019                         }
1020                 } else if (scr->xine_info.count && (wwin->normal_hints->flags & PPosition)) {
1021                         int head, flags;
1022                         WMRect rect;
1023                         int reposition = 0;
1024
1025                         /*
1026                          * Make spash screens come out in the center of a head
1027                          * trouble is that most splashies never get here
1028                          * they are managed trough atoms but god knows where.
1029                          * Dan, do you know ? -peter
1030                          *
1031                          * Most of them are not managed, they have set
1032                          * OverrideRedirect, which means we can't do anything about
1033                          * them. -alfredo
1034                          */
1035                         {
1036                                 /*
1037                                  * xinerama checks for: across head and dead space
1038                                  */
1039                                 rect.pos.x = x;
1040                                 rect.pos.y = y;
1041                                 rect.size.width = width;
1042                                 rect.size.height = height;
1043
1044                                 head = wGetRectPlacementInfo(scr, rect, &flags);
1045
1046                                 if (flags & XFLAG_DEAD)
1047                                         reposition = 1;
1048
1049                                 if (flags & XFLAG_MULTIPLE)
1050                                         reposition = 2;
1051                         }
1052
1053                         switch (reposition) {
1054                         case 1:
1055                                 head = wGetHeadForPointerLocation(scr);
1056                                 rect = wGetRectForHead(scr, head);
1057
1058                                 x = rect.pos.x + (x * rect.size.width) / scr->scr_width;
1059                                 y = rect.pos.y + (y * rect.size.height) / scr->scr_height;
1060                                 break;
1061
1062                         case 2:
1063                                 rect = wGetRectForHead(scr, head);
1064
1065                                 if (x < rect.pos.x)
1066                                         x = rect.pos.x;
1067                                 else if (x + width > rect.pos.x + rect.size.width)
1068                                         x = rect.pos.x + rect.size.width - width;
1069
1070                                 if (y < rect.pos.y)
1071                                         y = rect.pos.y;
1072                                 else if (y + height > rect.pos.y + rect.size.height)
1073                                         y = rect.pos.y + rect.size.height - height;
1074
1075                                 break;
1076
1077                         default:
1078                                 break;
1079                         }
1080                 }
1081
1082                 if (WFLAGP(wwin, dont_move_off) && dontBring)
1083                         wScreenBringInside(scr, &x, &y, width, height);
1084         }
1085
1086         wNETWMPositionSplash(wwin, &x, &y, width, height);
1087
1088         if (wwin->flags.urgent) {
1089                 if (!IS_OMNIPRESENT(wwin))
1090                         wwin->flags.omnipresent ^= 1;
1091         }
1092
1093         /*
1094          * Create frame, borders and do reparenting
1095          */
1096         foo = WFF_LEFT_BUTTON | WFF_RIGHT_BUTTON;
1097 #ifdef XKB_BUTTON_HINT
1098         if (wPreferences.modelock)
1099                 foo |= WFF_LANGUAGE_BUTTON;
1100 #endif
1101         if (HAS_TITLEBAR(wwin))
1102                 foo |= WFF_TITLEBAR;
1103         if (HAS_RESIZEBAR(wwin))
1104                 foo |= WFF_RESIZEBAR;
1105         if (HAS_BORDER(wwin))
1106                 foo |= WFF_BORDER;
1107
1108         wwin->frame = wFrameWindowCreate(scr, window_level,
1109                                          x, y, width, height,
1110                                          &wPreferences.window_title_clearance, foo,
1111                                          scr->window_title_texture,
1112                                          scr->resizebar_texture, scr->window_title_color, &scr->title_font);
1113
1114         wwin->frame->flags.is_client_window_frame = 1;
1115         wwin->frame->flags.justification = wPreferences.title_justification;
1116
1117         /* setup button images */
1118         wWindowUpdateButtonImages(wwin);
1119
1120         /* hide unused buttons */
1121         foo = 0;
1122         if (WFLAGP(wwin, no_close_button))
1123                 foo |= WFF_RIGHT_BUTTON;
1124         if (WFLAGP(wwin, no_miniaturize_button))
1125                 foo |= WFF_LEFT_BUTTON;
1126 #ifdef XKB_BUTTON_HINT
1127         if (WFLAGP(wwin, no_language_button) || WFLAGP(wwin, no_focusable))
1128                 foo |= WFF_LANGUAGE_BUTTON;
1129 #endif
1130         if (foo != 0)
1131                 wFrameWindowHideButton(wwin->frame, foo);
1132
1133         wwin->frame->child = wwin;
1134         wwin->frame->workspace = workspace;
1135         wwin->frame->on_click_left = windowIconifyClick;
1136
1137 #ifdef XKB_BUTTON_HINT
1138         if (wPreferences.modelock)
1139                 wwin->frame->on_click_language = windowLanguageClick;
1140 #endif
1141
1142         wwin->frame->on_click_right = windowCloseClick;
1143         wwin->frame->on_dblclick_right = windowCloseDblClick;
1144         wwin->frame->on_mousedown_titlebar = titlebarMouseDown;
1145         wwin->frame->on_dblclick_titlebar = titlebarDblClick;
1146         wwin->frame->on_mousedown_resizebar = resizebarMouseDown;
1147
1148         XSelectInput(dpy, wwin->client_win, wwin->event_mask & ~StructureNotifyMask);
1149         XReparentWindow(dpy, wwin->client_win, wwin->frame->core->window, 0, wwin->frame->top_width);
1150         XSelectInput(dpy, wwin->client_win, wwin->event_mask);
1151
1152         {
1153                 int gx, gy;
1154
1155                 wClientGetGravityOffsets(wwin, &gx, &gy);
1156
1157                 /* if gravity is to the south, account for the border sizes */
1158                 if (gy > 0)
1159                         y -= wwin->frame->top_width + wwin->frame->bottom_width;
1160         }
1161
1162         /*
1163          * wWindowConfigure() will init the client window's size
1164          * (wwin->client.{width,height}) and all other geometry
1165          * related variables (frame_x,frame_y)
1166          */
1167         wWindowConfigure(wwin, x, y, width, height);
1168
1169         /* to make sure the window receives it's new position after reparenting */
1170         wWindowSynthConfigureNotify(wwin);
1171
1172         /*
1173          * Setup descriptors and save window to internal
1174          * lists
1175          */
1176         if (wwin->main_window != None) {
1177                 WApplication *app;
1178                 WWindow *leader;
1179
1180                 /* Leader windows do not necessary set themselves as leaders.
1181                  * If this is the case, point the leader of this window to
1182                  * itself */
1183                 leader = wWindowFor(wwin->main_window);
1184                 if (leader && leader->main_window == None) {
1185                         leader->main_window = leader->client_win;
1186                 }
1187                 app = wApplicationCreate(wwin);
1188                 if (app) {
1189                         app->last_workspace = workspace;
1190
1191                         /*
1192                          * Do application specific stuff, like setting application
1193                          * wide attributes.
1194                          */
1195
1196                         if (wwin->flags.hidden) {
1197                                 /* if the window was set to hidden because it was hidden
1198                                  * in a previous incarnation and that state was restored */
1199                                 app->flags.hidden = 1;
1200                         } else if (app->flags.hidden) {
1201                                 if (WFLAGP(app->main_window_desc, start_hidden)) {
1202                                         wwin->flags.hidden = 1;
1203                                 } else {
1204                                         wUnhideApplication(app, False, False);
1205                                         raise = True;
1206                                 }
1207                         }
1208                 }
1209         }
1210
1211         /* setup the frame descriptor */
1212         wwin->frame->core->descriptor.handle_mousedown = frameMouseDown;
1213         wwin->frame->core->descriptor.parent = wwin;
1214         wwin->frame->core->descriptor.parent_type = WCLASS_WINDOW;
1215
1216         /* don't let windows go away if we die */
1217         XAddToSaveSet(dpy, window);
1218
1219         XLowerWindow(dpy, window);
1220
1221         /* if window is in this workspace and should be mapped, then  map it */
1222         if (!wwin->flags.miniaturized && (workspace == scr->current_workspace || IS_OMNIPRESENT(wwin))
1223             && !wwin->flags.hidden && !withdraw) {
1224
1225                 /* The following "if" is to avoid crashing of clients that expect
1226                  * WM_STATE set before they get mapped. Else WM_STATE is set later,
1227                  * after the return from this function.
1228                  */
1229                 if (wwin->wm_hints && (wwin->wm_hints->flags & StateHint)) {
1230                         wClientSetState(wwin, wwin->wm_hints->initial_state, None);
1231                 } else {
1232                         wClientSetState(wwin, NormalState, None);
1233                 }
1234
1235 #if 0
1236                 /* if not auto focus, then map the window under the currently
1237                  * focused window */
1238 #define _WIDTH(w) (w)->frame->core->width
1239 #define _HEIGHT(w) (w)->frame->core->height
1240                 if (!wPreferences.auto_focus && scr->focused_window
1241                     && !scr->flags.startup && !transientOwner && ((wWindowObscuresWindow(wwin, scr->focused_window)
1242                                                                    && (_WIDTH(wwin) >
1243                                                                        (_WIDTH(scr->focused_window) * 5) / 3
1244                                                                        || _HEIGHT(wwin) >
1245                                                                        (_HEIGHT(scr->focused_window) * 5) / 3)
1246                                                                    && WINDOW_LEVEL(scr->focused_window) ==
1247                                                                    WINDOW_LEVEL(wwin))
1248                                                                   || wwin->flags.maximized)) {
1249                         MoveInStackListUnder(scr->focused_window->frame->core, wwin->frame->core);
1250                 }
1251 #undef _WIDTH
1252 #undef _HEIGHT
1253
1254 #endif
1255
1256                 if (wPreferences.superfluous && !wPreferences.no_animations
1257                     && !scr->flags.startup && (wwin->transient_for == None || wwin->transient_for == scr->root_win)
1258                     /*
1259                      * The brain damaged idiotic non-click to focus modes will
1260                      * have trouble with this because:
1261                      *
1262                      * 1. window is created and mapped by the client
1263                      * 2. window is mapped by wmaker in small size
1264                      * 3. window is animated to grow to normal size
1265                      * 4. this function returns to normal event loop
1266                      * 5. eventually, the EnterNotify event that would trigger
1267                      * the window focusing (if the mouse is over that window)
1268                      * will be processed by wmaker.
1269                      * But since this event will be rather delayed
1270                      * (step 3 has a large delay) the time when the event ocurred
1271                      * and when it is processed, the client that owns that window
1272                      * will reject the XSetInputFocus() for it.
1273                      */
1274                     && (wPreferences.focus_mode == WKF_CLICK || wPreferences.auto_focus)) {
1275                         DoWindowBirth(wwin);
1276                 }
1277
1278                 wWindowMap(wwin);
1279         }
1280
1281         /* setup stacking descriptor */
1282         if (transientOwner) {
1283                 wwin->frame->core->stacking->child_of = transientOwner->frame->core;
1284         } else {
1285                 wwin->frame->core->stacking->child_of = NULL;
1286         }
1287
1288         if (!scr->focused_window) {
1289                 /* first window on the list */
1290                 wwin->next = NULL;
1291                 wwin->prev = NULL;
1292                 scr->focused_window = wwin;
1293         } else {
1294                 WWindow *tmp;
1295
1296                 /* add window at beginning of focus window list */
1297                 tmp = scr->focused_window;
1298                 while (tmp->prev)
1299                         tmp = tmp->prev;
1300                 tmp->prev = wwin;
1301                 wwin->next = tmp;
1302                 wwin->prev = NULL;
1303         }
1304
1305         /* raise is set to true if we un-hid the app when this window was born.
1306          * we raise, else old windows of this app will be above this new one. */
1307         if (raise) {
1308                 wRaiseFrame(wwin->frame->core);
1309         }
1310
1311         /* Update name must come after WApplication stuff is done */
1312         wWindowUpdateName(wwin, title);
1313         if (title)
1314                 XFree(title);
1315
1316         XUngrabServer(dpy);
1317
1318         /*
1319          * Final preparations before window is ready to go
1320          */
1321         wFrameWindowChangeState(wwin->frame, WS_UNFOCUSED);
1322
1323         if (!wwin->flags.miniaturized && workspace == scr->current_workspace && !wwin->flags.hidden) {
1324                 if (((transientOwner && transientOwner->flags.focused)
1325                      || wPreferences.auto_focus) && !WFLAGP(wwin, no_focusable)) {
1326
1327                         /* only auto_focus if on same screen as mouse
1328                          * (and same head for xinerama mode)
1329                          * TODO: make it an option */
1330
1331                         /*TODO add checking the head of the window, is it available? */
1332                         short same_screen = 0, same_head = 1;
1333
1334                         int foo;
1335                         unsigned int bar;
1336                         Window dummy;
1337
1338                         if (XQueryPointer(dpy, scr->root_win, &dummy, &dummy,
1339                                           &foo, &foo, &foo, &foo, &bar) != False) {
1340                                 same_screen = 1;
1341                         }
1342
1343                         if (same_screen == 1 && same_head == 1) {
1344                                 wSetFocusTo(scr, wwin);
1345                         }
1346                 }
1347         }
1348         wWindowResetMouseGrabs(wwin);
1349
1350         if (!WFLAGP(wwin, no_bind_keys))
1351                 wWindowSetKeyGrabs(wwin);
1352
1353         WMPostNotificationName(WMNManaged, wwin, NULL);
1354         wColormapInstallForWindow(scr, scr->cmap_window);
1355
1356         /* Setup Notification Observers */
1357         WMAddNotificationObserver(appearanceObserver, wwin, WNWindowAppearanceSettingsChanged, wwin);
1358
1359         /*  Cleanup temporary stuff */
1360         if (win_state)
1361                 wWindowDeleteSavedState(win_state);
1362
1363         /* If the window must be withdrawed, then do it now.
1364          * Must do some optimization, 'though */
1365         if (withdraw) {
1366                 wwin->flags.mapped = 0;
1367                 wClientSetState(wwin, WithdrawnState, None);
1368                 wUnmanageWindow(wwin, True, False);
1369                 wwin = NULL;
1370         }
1371
1372         return wwin;
1373 }
1374
1375 WWindow *wManageInternalWindow(WScreen *scr, Window window, Window owner,
1376                                char *title, int x, int y, int width, int height)
1377 {
1378         WWindow *wwin;
1379         int foo;
1380
1381         wwin = wWindowCreate();
1382
1383         WMAddNotificationObserver(appearanceObserver, wwin, WNWindowAppearanceSettingsChanged, wwin);
1384
1385         wwin->flags.internal_window = 1;
1386
1387         WSETUFLAG(wwin, omnipresent, 1);
1388         WSETUFLAG(wwin, no_shadeable, 1);
1389         WSETUFLAG(wwin, no_resizable, 1);
1390         WSETUFLAG(wwin, no_miniaturizable, 1);
1391
1392         wwin->focus_mode = WFM_PASSIVE;
1393         wwin->client_win = window;
1394         wwin->screen_ptr = scr;
1395         wwin->transient_for = owner;
1396         wwin->client.x = x;
1397         wwin->client.y = y;
1398         wwin->client.width = width;
1399         wwin->client.height = height;
1400         wwin->frame_x = wwin->client.x;
1401         wwin->frame_y = wwin->client.y;
1402
1403         foo = WFF_RIGHT_BUTTON | WFF_BORDER;
1404         foo |= WFF_TITLEBAR;
1405 #ifdef XKB_BUTTON_HINT
1406         foo |= WFF_LANGUAGE_BUTTON;
1407 #endif
1408
1409         wwin->frame = wFrameWindowCreate(scr, WMFloatingLevel,
1410                                          wwin->frame_x, wwin->frame_y,
1411                                          width, height,
1412                                          &wPreferences.window_title_clearance, foo,
1413                                          scr->window_title_texture,
1414                                          scr->resizebar_texture, scr->window_title_color, &scr->title_font);
1415
1416         XSaveContext(dpy, window, wWinContext, (XPointer) & wwin->client_descriptor);
1417
1418         wwin->frame->flags.is_client_window_frame = 1;
1419         wwin->frame->flags.justification = wPreferences.title_justification;
1420
1421         wFrameWindowChangeTitle(wwin->frame, title);
1422
1423         /* setup button images */
1424         wWindowUpdateButtonImages(wwin);
1425
1426         /* hide buttons */
1427         wFrameWindowHideButton(wwin->frame, WFF_RIGHT_BUTTON);
1428
1429         wwin->frame->child = wwin;
1430         wwin->frame->workspace = wwin->screen_ptr->current_workspace;
1431
1432 #ifdef XKB_BUTTON_HINT
1433         if (wPreferences.modelock)
1434                 wwin->frame->on_click_language = windowLanguageClick;
1435 #endif
1436
1437         wwin->frame->on_click_right = windowCloseClick;
1438         wwin->frame->on_mousedown_titlebar = titlebarMouseDown;
1439         wwin->frame->on_dblclick_titlebar = titlebarDblClick;
1440         wwin->frame->on_mousedown_resizebar = resizebarMouseDown;
1441         wwin->client.y += wwin->frame->top_width;
1442
1443         XReparentWindow(dpy, wwin->client_win, wwin->frame->core->window, 0, wwin->frame->top_width);
1444         wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, wwin->client.width, wwin->client.height);
1445
1446         /* setup the frame descriptor */
1447         wwin->frame->core->descriptor.handle_mousedown = frameMouseDown;
1448         wwin->frame->core->descriptor.parent = wwin;
1449         wwin->frame->core->descriptor.parent_type = WCLASS_WINDOW;
1450
1451         XLowerWindow(dpy, window);
1452         XMapSubwindows(dpy, wwin->frame->core->window);
1453
1454         /* setup stacking descriptor */
1455         if (wwin->transient_for != None && wwin->transient_for != scr->root_win) {
1456                 WWindow *tmp;
1457                 tmp = wWindowFor(wwin->transient_for);
1458                 if (tmp)
1459                         wwin->frame->core->stacking->child_of = tmp->frame->core;
1460         } else {
1461                 wwin->frame->core->stacking->child_of = NULL;
1462         }
1463
1464         if (!scr->focused_window) {
1465                 /* first window on the list */
1466                 wwin->next = NULL;
1467                 wwin->prev = NULL;
1468                 scr->focused_window = wwin;
1469         } else {
1470                 WWindow *tmp;
1471
1472                 /* add window at beginning of focus window list */
1473                 tmp = scr->focused_window;
1474                 while (tmp->prev)
1475                         tmp = tmp->prev;
1476                 tmp->prev = wwin;
1477                 wwin->next = tmp;
1478                 wwin->prev = NULL;
1479         }
1480
1481         if (wwin->flags.is_gnustep == 0)
1482                 wFrameWindowChangeState(wwin->frame, WS_UNFOCUSED);
1483
1484         /*    if (wPreferences.auto_focus) */
1485         wSetFocusTo(scr, wwin);
1486         wWindowResetMouseGrabs(wwin);
1487         wWindowSetKeyGrabs(wwin);
1488
1489         return wwin;
1490 }
1491
1492 /*
1493  *----------------------------------------------------------------------
1494  * wUnmanageWindow--
1495  *      Removes the frame window from a window and destroys all data
1496  * related to it. The window will be reparented back to the root window
1497  * if restore is True.
1498  *
1499  * Side effects:
1500  *      Everything related to the window is destroyed and the window
1501  * is removed from the window lists. Focus is set to the previous on the
1502  * window list.
1503  *----------------------------------------------------------------------
1504  */
1505 void wUnmanageWindow(WWindow *wwin, Bool restore, Bool destroyed)
1506 {
1507         WCoreWindow *frame = wwin->frame->core;
1508         WWindow *owner = NULL;
1509         WWindow *newFocusedWindow = NULL;
1510         int wasFocused;
1511         WScreen *scr = wwin->screen_ptr;
1512
1513         /* First close attribute editor window if open */
1514         if (wwin->flags.inspector_open) {
1515                 wCloseInspectorForWindow(wwin);
1516         }
1517
1518         /* Close window menu if it's open for this window */
1519         if (wwin->flags.menu_open_for_me) {
1520                 CloseWindowMenu(scr);
1521         }
1522
1523         if (!destroyed) {
1524                 if (!wwin->flags.internal_window)
1525                         XRemoveFromSaveSet(dpy, wwin->client_win);
1526
1527                 XSelectInput(dpy, wwin->client_win, NoEventMask);
1528
1529                 XUngrabButton(dpy, AnyButton, AnyModifier, wwin->client_win);
1530                 XUngrabKey(dpy, AnyKey, AnyModifier, wwin->client_win);
1531         }
1532
1533         XUnmapWindow(dpy, frame->window);
1534
1535         XUnmapWindow(dpy, wwin->client_win);
1536
1537         /* deselect window */
1538         wSelectWindow(wwin, False);
1539
1540         /* remove all pending events on window */
1541         /* I think this only matters for autoraise */
1542         if (wPreferences.raise_delay)
1543                 WMDeleteTimerWithClientData(wwin->frame->core);
1544
1545         XFlush(dpy);
1546
1547         /* reparent the window back to the root */
1548         if (restore)
1549                 wClientRestore(wwin);
1550
1551         if (wwin->transient_for != scr->root_win) {
1552                 owner = wWindowFor(wwin->transient_for);
1553                 if (owner) {
1554                         if (!owner->flags.semi_focused) {
1555                                 owner = NULL;
1556                         } else {
1557                                 owner->flags.semi_focused = 0;
1558                         }
1559                 }
1560         }
1561
1562         wasFocused = wwin->flags.focused;
1563
1564         /* remove from window focus list */
1565         if (!wwin->prev && !wwin->next) {
1566                 /* was the only window */
1567                 scr->focused_window = NULL;
1568                 newFocusedWindow = NULL;
1569         } else {
1570                 WWindow *tmp;
1571
1572                 if (wwin->prev)
1573                         wwin->prev->next = wwin->next;
1574                 if (wwin->next)
1575                         wwin->next->prev = wwin->prev;
1576                 else {
1577                         scr->focused_window = wwin->prev;
1578                         scr->focused_window->next = NULL;
1579                 }
1580
1581                 if (wPreferences.focus_mode == WKF_CLICK) {
1582
1583                         /* if in click to focus mode and the window
1584                          * was a transient, focus the owner window
1585                          */
1586                         tmp = NULL;
1587                         if (wPreferences.focus_mode == WKF_CLICK) {
1588                                 tmp = wWindowFor(wwin->transient_for);
1589                                 if (tmp && (!tmp->flags.mapped || WFLAGP(tmp, no_focusable))) {
1590                                         tmp = NULL;
1591                                 }
1592                         }
1593                         /* otherwise, focus the next one in the focus list */
1594                         if (!tmp) {
1595                                 tmp = scr->focused_window;
1596                                 while (tmp) {   /* look for one in the window list first */
1597                                         if (!WFLAGP(tmp, no_focusable) && !WFLAGP(tmp, skip_window_list)
1598                                             && (tmp->flags.mapped || tmp->flags.shaded))
1599                                                 break;
1600                                         tmp = tmp->prev;
1601                                 }
1602                                 if (!tmp) {     /* if unsuccessful, choose any focusable window */
1603                                         tmp = scr->focused_window;
1604                                         while (tmp) {
1605                                                 if (!WFLAGP(tmp, no_focusable)
1606                                                     && (tmp->flags.mapped || tmp->flags.shaded))
1607                                                         break;
1608                                                 tmp = tmp->prev;
1609                                         }
1610                                 }
1611                         }
1612
1613                         newFocusedWindow = tmp;
1614
1615                 } else if (wPreferences.focus_mode == WKF_SLOPPY) {
1616                         unsigned int mask;
1617                         int foo;
1618                         Window bar, win;
1619
1620                         /*  This is to let the root window get the keyboard input
1621                          * if Sloppy focus mode and no other window get focus.
1622                          * This way keybindings will not freeze.
1623                          */
1624                         tmp = NULL;
1625                         if (XQueryPointer(dpy, scr->root_win, &bar, &win, &foo, &foo, &foo, &foo, &mask))
1626                                 tmp = wWindowFor(win);
1627                         if (tmp == wwin)
1628                                 tmp = NULL;
1629                         newFocusedWindow = tmp;
1630                 } else {
1631                         newFocusedWindow = NULL;
1632                 }
1633         }
1634
1635         if (!wwin->flags.internal_window)
1636                 WMPostNotificationName(WMNUnmanaged, wwin, NULL);
1637         if (wasFocused) {
1638                 if (newFocusedWindow != owner && owner) {
1639                         if (wwin->flags.is_gnustep == 0)
1640                                 wFrameWindowChangeState(owner->frame, WS_UNFOCUSED);
1641                 }
1642                 wSetFocusTo(scr, newFocusedWindow);
1643         }
1644         wWindowDestroy(wwin);
1645         XFlush(dpy);
1646 }
1647
1648 void wWindowMap(WWindow *wwin)
1649 {
1650         XMapWindow(dpy, wwin->frame->core->window);
1651         if (!wwin->flags.shaded) {
1652                 /* window will be remapped when getting MapNotify */
1653                 XSelectInput(dpy, wwin->client_win, wwin->event_mask & ~StructureNotifyMask);
1654                 XMapWindow(dpy, wwin->client_win);
1655                 XSelectInput(dpy, wwin->client_win, wwin->event_mask);
1656
1657                 wwin->flags.mapped = 1;
1658         }
1659 }
1660
1661 void wWindowUnmap(WWindow *wwin)
1662 {
1663         wwin->flags.mapped = 0;
1664
1665         /* prevent window withdrawal when getting UnmapNotify */
1666         XSelectInput(dpy, wwin->client_win, wwin->event_mask & ~StructureNotifyMask);
1667         XUnmapWindow(dpy, wwin->client_win);
1668         XSelectInput(dpy, wwin->client_win, wwin->event_mask);
1669
1670         XUnmapWindow(dpy, wwin->frame->core->window);
1671 }
1672
1673 void wWindowFocus(WWindow *wwin, WWindow *owin)
1674 {
1675         WWindow *nowner;
1676         WWindow *oowner;
1677
1678 #ifdef KEEP_XKB_LOCK_STATUS
1679         if (wPreferences.modelock) {
1680                 XkbLockGroup(dpy, XkbUseCoreKbd, wwin->frame->languagemode);
1681         }
1682 #endif /* KEEP_XKB_LOCK_STATUS */
1683
1684         wwin->flags.semi_focused = 0;
1685
1686         if (wwin->flags.is_gnustep == 0)
1687                 wFrameWindowChangeState(wwin->frame, WS_FOCUSED);
1688
1689         wwin->flags.focused = 1;
1690
1691         wWindowResetMouseGrabs(wwin);
1692
1693         WMPostNotificationName(WMNChangedFocus, wwin, (void *)True);
1694
1695         if (owin == wwin || !owin)
1696                 return;
1697
1698         nowner = wWindowFor(wwin->transient_for);
1699
1700         /* new window is a transient for the old window */
1701         if (nowner == owin) {
1702                 owin->flags.semi_focused = 1;
1703                 wWindowUnfocus(nowner);
1704                 return;
1705         }
1706
1707         oowner = wWindowFor(owin->transient_for);
1708
1709         /* new window is owner of old window */
1710         if (wwin == oowner) {
1711                 wWindowUnfocus(owin);
1712                 return;
1713         }
1714
1715         if (!nowner) {
1716                 wWindowUnfocus(owin);
1717                 return;
1718         }
1719
1720         /* new window has same owner of old window */
1721         if (oowner == nowner) {
1722                 /* prevent unfocusing of owner */
1723                 oowner->flags.semi_focused = 0;
1724                 wWindowUnfocus(owin);
1725                 oowner->flags.semi_focused = 1;
1726
1727                 return;
1728         }
1729
1730         /* nowner != NULL && oowner != nowner */
1731         nowner->flags.semi_focused = 1;
1732         wWindowUnfocus(nowner);
1733         wWindowUnfocus(owin);
1734 }
1735
1736 void wWindowUnfocus(WWindow *wwin)
1737 {
1738         CloseWindowMenu(wwin->screen_ptr);
1739
1740         if (wwin->flags.is_gnustep == 0)
1741                 wFrameWindowChangeState(wwin->frame, wwin->flags.semi_focused ? WS_PFOCUSED : WS_UNFOCUSED);
1742
1743         if (wwin->transient_for != None && wwin->transient_for != wwin->screen_ptr->root_win) {
1744                 WWindow *owner;
1745                 owner = wWindowFor(wwin->transient_for);
1746                 if (owner && owner->flags.semi_focused) {
1747                         owner->flags.semi_focused = 0;
1748                         if (owner->flags.mapped || owner->flags.shaded) {
1749                                 wWindowUnfocus(owner);
1750                                 wFrameWindowPaint(owner->frame);
1751                         }
1752                 }
1753         }
1754         wwin->flags.focused = 0;
1755         wWindowResetMouseGrabs(wwin);
1756         WMPostNotificationName(WMNChangedFocus, wwin, (void *)False);
1757 }
1758
1759 void wWindowUpdateName(WWindow *wwin, char *newTitle)
1760 {
1761         char *title;
1762
1763         if (!wwin->frame)
1764                 return;
1765
1766         wwin->flags.wm_name_changed = 1;
1767
1768         if (!newTitle) {
1769                 /* the hint was removed */
1770                 title = DEF_WINDOW_TITLE;
1771         } else {
1772                 title = newTitle;
1773         }
1774
1775         if (wFrameWindowChangeTitle(wwin->frame, title)) {
1776                 WMPostNotificationName(WMNChangedName, wwin, NULL);
1777         }
1778 }
1779
1780 /*
1781  *----------------------------------------------------------------------
1782  *
1783  * wWindowConstrainSize--
1784  *      Constrains size for the client window, taking the maximal size,
1785  * window resize increments and other size hints into account.
1786  *
1787  * Returns:
1788  *      The closest size to what was given that the client window can
1789  * have.
1790  *
1791  *----------------------------------------------------------------------
1792  */
1793 void wWindowConstrainSize(WWindow *wwin, unsigned int *nwidth, unsigned int *nheight)
1794 {
1795         int width = (int)*nwidth;
1796         int height = (int)*nheight;
1797         int winc = 1;
1798         int hinc = 1;
1799         int minW = 1, minH = 1;
1800         int maxW = wwin->screen_ptr->scr_width * 2;
1801         int maxH = wwin->screen_ptr->scr_height * 2;
1802         int minAX = -1, minAY = -1;
1803         int maxAX = -1, maxAY = -1;
1804         int baseW = 0;
1805         int baseH = 0;
1806
1807         if (wwin->normal_hints) {
1808                 winc = wwin->normal_hints->width_inc;
1809                 hinc = wwin->normal_hints->height_inc;
1810                 minW = wwin->normal_hints->min_width;
1811                 minH = wwin->normal_hints->min_height;
1812                 maxW = wwin->normal_hints->max_width;
1813                 maxH = wwin->normal_hints->max_height;
1814                 if (wwin->normal_hints->flags & PAspect) {
1815                         minAX = wwin->normal_hints->min_aspect.x;
1816                         minAY = wwin->normal_hints->min_aspect.y;
1817                         maxAX = wwin->normal_hints->max_aspect.x;
1818                         maxAY = wwin->normal_hints->max_aspect.y;
1819                 }
1820
1821                 baseW = wwin->normal_hints->base_width;
1822                 baseH = wwin->normal_hints->base_height;
1823         }
1824
1825         if (width < minW)
1826                 width = minW;
1827         if (height < minH)
1828                 height = minH;
1829
1830         if (width > maxW)
1831                 width = maxW;
1832         if (height > maxH)
1833                 height = maxH;
1834
1835         /* aspect ratio code borrowed from olwm */
1836         if (minAX > 0) {
1837                 /* adjust max aspect ratio */
1838                 if (!(maxAX == 1 && maxAY == 1) && width * maxAY > height * maxAX) {
1839                         if (maxAX > maxAY) {
1840                                 height = (width * maxAY) / maxAX;
1841                                 if (height > maxH) {
1842                                         height = maxH;
1843                                         width = (height * maxAX) / maxAY;
1844                                 }
1845                         } else {
1846                                 width = (height * maxAX) / maxAY;
1847                                 if (width > maxW) {
1848                                         width = maxW;
1849                                         height = (width * maxAY) / maxAX;
1850                                 }
1851                         }
1852                 }
1853
1854                 /* adjust min aspect ratio */
1855                 if (!(minAX == 1 && minAY == 1) && width * minAY < height * minAX) {
1856                         if (minAX > minAY) {
1857                                 height = (width * minAY) / minAX;
1858                                 if (height < minH) {
1859                                         height = minH;
1860                                         width = (height * minAX) / minAY;
1861                                 }
1862                         } else {
1863                                 width = (height * minAX) / minAY;
1864                                 if (width < minW) {
1865                                         width = minW;
1866                                         height = (width * minAY) / minAX;
1867                                 }
1868                         }
1869                 }
1870         }
1871
1872         if (baseW != 0)
1873                 width = (((width - baseW) / winc) * winc) + baseW;
1874         else
1875                 width = (((width - minW) / winc) * winc) + minW;
1876
1877         if (baseH != 0)
1878                 height = (((height - baseH) / hinc) * hinc) + baseH;
1879         else
1880                 height = (((height - minH) / hinc) * hinc) + minH;
1881
1882         /* broken stupid apps may cause preposterous values for these.. */
1883         if (width > 0)
1884                 *nwidth = width;
1885         if (height > 0)
1886                 *nheight = height;
1887 }
1888
1889 void wWindowCropSize(WWindow *wwin, unsigned int maxW, unsigned int maxH,
1890                      unsigned int *width, unsigned int *height)
1891 {
1892         int baseW = 0, baseH = 0;
1893         int winc = 1, hinc = 1;
1894
1895         if (wwin->normal_hints) {
1896                 baseW = wwin->normal_hints->base_width;
1897                 baseH = wwin->normal_hints->base_height;
1898
1899                 winc = wwin->normal_hints->width_inc;
1900                 hinc = wwin->normal_hints->height_inc;
1901         }
1902
1903         if (*width > maxW)
1904                 *width = maxW - (maxW - baseW) % winc;
1905
1906         if (*height > maxH)
1907                 *height = maxH - (maxH - baseH) % hinc;
1908 }
1909
1910 void wWindowChangeWorkspace(WWindow *wwin, int workspace)
1911 {
1912         WScreen *scr = wwin->screen_ptr;
1913         WApplication *wapp;
1914         int unmap = 0;
1915
1916         if (workspace >= scr->workspace_count || workspace < 0 || workspace == wwin->frame->workspace)
1917                 return;
1918
1919         if (workspace != scr->current_workspace) {
1920                 /* Sent to other workspace. Unmap window */
1921                 if ((wwin->flags.mapped
1922                      || wwin->flags.shaded || (wwin->flags.miniaturized && !wPreferences.sticky_icons))
1923                     && !IS_OMNIPRESENT(wwin) && !wwin->flags.changing_workspace) {
1924
1925                         wapp = wApplicationOf(wwin->main_window);
1926                         if (wapp) {
1927                                 wapp->last_workspace = workspace;
1928                         }
1929                         if (wwin->flags.miniaturized) {
1930                                 if (wwin->icon) {
1931                                         XUnmapWindow(dpy, wwin->icon->core->window);
1932                                         wwin->icon->mapped = 0;
1933                                 }
1934                         } else {
1935                                 unmap = 1;
1936                                 wSetFocusTo(scr, NULL);
1937                         }
1938                 }
1939         } else {
1940                 /* brought to current workspace. Map window */
1941                 if (wwin->flags.miniaturized && !wPreferences.sticky_icons) {
1942                         if (wwin->icon) {
1943                                 XMapWindow(dpy, wwin->icon->core->window);
1944                                 wwin->icon->mapped = 1;
1945                         }
1946                 } else if (!wwin->flags.mapped && !(wwin->flags.miniaturized || wwin->flags.hidden)) {
1947                         wWindowMap(wwin);
1948                 }
1949         }
1950         if (!IS_OMNIPRESENT(wwin)) {
1951                 int oldWorkspace = wwin->frame->workspace;
1952
1953                 wwin->frame->workspace = workspace;
1954
1955                 WMPostNotificationName(WMNChangedWorkspace, wwin, (void *)(uintptr_t) oldWorkspace);
1956         }
1957
1958         if (unmap)
1959                 wWindowUnmap(wwin);
1960 }
1961
1962 void wWindowSynthConfigureNotify(WWindow *wwin)
1963 {
1964         XEvent sevent;
1965
1966         sevent.type = ConfigureNotify;
1967         sevent.xconfigure.display = dpy;
1968         sevent.xconfigure.event = wwin->client_win;
1969         sevent.xconfigure.window = wwin->client_win;
1970
1971         sevent.xconfigure.x = wwin->client.x;
1972         sevent.xconfigure.y = wwin->client.y;
1973         sevent.xconfigure.width = wwin->client.width;
1974         sevent.xconfigure.height = wwin->client.height;
1975
1976         sevent.xconfigure.border_width = wwin->old_border_width;
1977         if (HAS_TITLEBAR(wwin) && wwin->frame->titlebar)
1978                 sevent.xconfigure.above = wwin->frame->titlebar->window;
1979         else
1980                 sevent.xconfigure.above = None;
1981
1982         sevent.xconfigure.override_redirect = False;
1983         XSendEvent(dpy, wwin->client_win, False, StructureNotifyMask, &sevent);
1984         XFlush(dpy);
1985 }
1986
1987 /*
1988  *----------------------------------------------------------------------
1989  * wWindowConfigure()
1990  *
1991  * req_x, req_y: new requested positions for the frame
1992  * req_width, req_height: new requested sizes for the client
1993  *
1994  * Configures the frame, decorations and client window to the specified
1995  * geometry, whose validity is not checked --  wWindowConstrainSize()
1996  * must be used for that.
1997  *      The size parameters are for the client window, but the position is
1998  * for the frame.
1999  *      The client window receives a ConfigureNotify event, according
2000  * to what ICCCM says.
2001  *
2002  * Returns:
2003  *      None
2004  *
2005  * Side effects:
2006  *      Window size and position are changed and client window receives
2007  * a ConfigureNotify event.
2008  *----------------------------------------------------------------------
2009  */
2010 void wWindowConfigure(WWindow *wwin, int req_x, int req_y, int req_width, int req_height)
2011 {
2012         int synth_notify = False;
2013         int resize;
2014
2015         resize = (req_width != wwin->client.width || req_height != wwin->client.height);
2016         /*
2017          * if the window is being moved but not resized then
2018          * send a synthetic ConfigureNotify
2019          */
2020         if ((req_x != wwin->frame_x || req_y != wwin->frame_y) && !resize) {
2021                 synth_notify = True;
2022         }
2023
2024         if (WFLAGP(wwin, dont_move_off))
2025                 wScreenBringInside(wwin->screen_ptr, &req_x, &req_y, req_width, req_height);
2026         if (resize) {
2027                 if (req_width < MIN_WINDOW_SIZE)
2028                         req_width = MIN_WINDOW_SIZE;
2029                 if (req_height < MIN_WINDOW_SIZE)
2030                         req_height = MIN_WINDOW_SIZE;
2031
2032                 /* If growing, resize inner part before frame,
2033                  * if shrinking, resize frame before.
2034                  * This will prevent the frame (that can have a different color)
2035                  * to be exposed, causing flicker */
2036                 if (req_height > wwin->frame->core->height || req_width > wwin->frame->core->width)
2037                         XResizeWindow(dpy, wwin->client_win, req_width, req_height);
2038
2039                 if (wwin->flags.shaded) {
2040                         wFrameWindowConfigure(wwin->frame, req_x, req_y, req_width, wwin->frame->core->height);
2041                         wwin->old_geometry.height = req_height;
2042                 } else {
2043                         int h;
2044
2045                         h = req_height + wwin->frame->top_width + wwin->frame->bottom_width;
2046
2047                         wFrameWindowConfigure(wwin->frame, req_x, req_y, req_width, h);
2048                 }
2049
2050                 if (!(req_height > wwin->frame->core->height || req_width > wwin->frame->core->width))
2051                         XResizeWindow(dpy, wwin->client_win, req_width, req_height);
2052
2053                 wwin->client.x = req_x;
2054                 wwin->client.y = req_y + wwin->frame->top_width;
2055                 wwin->client.width = req_width;
2056                 wwin->client.height = req_height;
2057         } else {
2058                 wwin->client.x = req_x;
2059                 wwin->client.y = req_y + wwin->frame->top_width;
2060
2061                 XMoveWindow(dpy, wwin->frame->core->window, req_x, req_y);
2062         }
2063         wwin->frame_x = req_x;
2064         wwin->frame_y = req_y;
2065         if (HAS_BORDER(wwin)) {
2066                 wwin->client.x += FRAME_BORDER_WIDTH;
2067                 wwin->client.y += FRAME_BORDER_WIDTH;
2068         }
2069 #ifdef SHAPE
2070         if (wShapeSupported && wwin->flags.shaped && resize) {
2071                 wWindowSetShape(wwin);
2072         }
2073 #endif
2074
2075         if (synth_notify)
2076                 wWindowSynthConfigureNotify(wwin);
2077         XFlush(dpy);
2078 }
2079
2080 /* req_x, req_y:  new position of the frame */
2081 void wWindowMove(WWindow *wwin, int req_x, int req_y)
2082 {
2083 #ifdef CONFIGURE_WINDOW_WHILE_MOVING
2084         int synth_notify = False;
2085
2086         /* Send a synthetic ConfigureNotify event for every window movement. */
2087         if ((req_x != wwin->frame_x || req_y != wwin->frame_y)) {
2088                 synth_notify = True;
2089         }
2090 #else
2091         /* A single synthetic ConfigureNotify event is sent at the end of
2092          * a completed (opaque) movement in moveres.c */
2093 #endif
2094
2095         if (WFLAGP(wwin, dont_move_off))
2096                 wScreenBringInside(wwin->screen_ptr, &req_x, &req_y,
2097                                    wwin->frame->core->width, wwin->frame->core->height);
2098
2099         wwin->client.x = req_x;
2100         wwin->client.y = req_y + wwin->frame->top_width;
2101         if (HAS_BORDER(wwin)) {
2102                 wwin->client.x += FRAME_BORDER_WIDTH;
2103                 wwin->client.y += FRAME_BORDER_WIDTH;
2104         }
2105
2106         XMoveWindow(dpy, wwin->frame->core->window, req_x, req_y);
2107
2108         wwin->frame_x = req_x;
2109         wwin->frame_y = req_y;
2110
2111 #ifdef CONFIGURE_WINDOW_WHILE_MOVING
2112         if (synth_notify)
2113                 wWindowSynthConfigureNotify(wwin);
2114 #endif
2115 }
2116
2117 void wWindowUpdateButtonImages(WWindow *wwin)
2118 {
2119         WScreen *scr = wwin->screen_ptr;
2120         Pixmap pixmap, mask;
2121         WFrameWindow *fwin = wwin->frame;
2122
2123         if (!HAS_TITLEBAR(wwin))
2124                 return;
2125
2126         /* miniaturize button */
2127         if (!WFLAGP(wwin, no_miniaturize_button)) {
2128                 if (wwin->wm_gnustep_attr && wwin->wm_gnustep_attr->flags & GSMiniaturizePixmapAttr) {
2129                         pixmap = wwin->wm_gnustep_attr->miniaturize_pixmap;
2130
2131                         if (wwin->wm_gnustep_attr->flags & GSMiniaturizeMaskAttr) {
2132                                 mask = wwin->wm_gnustep_attr->miniaturize_mask;
2133                         } else {
2134                                 mask = None;
2135                         }
2136
2137                         if (fwin->lbutton_image
2138                             && (fwin->lbutton_image->image != pixmap || fwin->lbutton_image->mask != mask)) {
2139                                 wPixmapDestroy(fwin->lbutton_image);
2140                                 fwin->lbutton_image = NULL;
2141                         }
2142
2143                         if (!fwin->lbutton_image) {
2144                                 fwin->lbutton_image = wPixmapCreate(scr, pixmap, mask);
2145                                 fwin->lbutton_image->client_owned = 1;
2146                                 fwin->lbutton_image->client_owned_mask = 1;
2147                         }
2148                 } else {
2149                         if (fwin->lbutton_image && !fwin->lbutton_image->shared) {
2150                                 wPixmapDestroy(fwin->lbutton_image);
2151                         }
2152                         fwin->lbutton_image = scr->b_pixmaps[WBUT_ICONIFY];
2153                 }
2154         }
2155 #ifdef XKB_BUTTON_HINT
2156         if (!WFLAGP(wwin, no_language_button)) {
2157                 if (fwin->languagebutton_image && !fwin->languagebutton_image->shared) {
2158                         wPixmapDestroy(fwin->languagebutton_image);
2159                 }
2160                 fwin->languagebutton_image = scr->b_pixmaps[WBUT_XKBGROUP1 + fwin->languagemode];
2161         }
2162 #endif
2163
2164         /* close button */
2165
2166         /* redefine WFLAGP to MGFLAGP to allow broken close operation */
2167 #define MGFLAGP(wwin, FLAG)     (wwin)->client_flags.FLAG
2168
2169         if (!WFLAGP(wwin, no_close_button)) {
2170                 if (wwin->wm_gnustep_attr && wwin->wm_gnustep_attr->flags & GSClosePixmapAttr) {
2171                         pixmap = wwin->wm_gnustep_attr->close_pixmap;
2172
2173                         if (wwin->wm_gnustep_attr->flags & GSCloseMaskAttr)
2174                                 mask = wwin->wm_gnustep_attr->close_mask;
2175                         else
2176                                 mask = None;
2177
2178                         if (fwin->rbutton_image && (fwin->rbutton_image->image != pixmap
2179                                                     || fwin->rbutton_image->mask != mask)) {
2180                                 wPixmapDestroy(fwin->rbutton_image);
2181                                 fwin->rbutton_image = NULL;
2182                         }
2183
2184                         if (!fwin->rbutton_image) {
2185                                 fwin->rbutton_image = wPixmapCreate(scr, pixmap, mask);
2186                                 fwin->rbutton_image->client_owned = 1;
2187                                 fwin->rbutton_image->client_owned_mask = 1;
2188                         }
2189
2190                 } else if (WFLAGP(wwin, kill_close)) {
2191
2192                         if (fwin->rbutton_image && !fwin->rbutton_image->shared)
2193                                 wPixmapDestroy(fwin->rbutton_image);
2194
2195                         fwin->rbutton_image = scr->b_pixmaps[WBUT_KILL];
2196
2197                 } else if (MGFLAGP(wwin, broken_close)) {
2198
2199                         if (fwin->rbutton_image && !fwin->rbutton_image->shared)
2200                                 wPixmapDestroy(fwin->rbutton_image);
2201
2202                         fwin->rbutton_image = scr->b_pixmaps[WBUT_BROKENCLOSE];
2203
2204                 } else {
2205
2206                         if (fwin->rbutton_image && !fwin->rbutton_image->shared)
2207                                 wPixmapDestroy(fwin->rbutton_image);
2208
2209                         fwin->rbutton_image = scr->b_pixmaps[WBUT_CLOSE];
2210                 }
2211         }
2212
2213         /* force buttons to be redrawn */
2214         fwin->flags.need_texture_change = 1;
2215         wFrameWindowPaint(fwin);
2216 }
2217
2218 /*
2219  *---------------------------------------------------------------------------
2220  * wWindowConfigureBorders--
2221  *      Update window border configuration according to attribute flags.
2222  *
2223  *---------------------------------------------------------------------------
2224  */
2225 void wWindowConfigureBorders(WWindow *wwin)
2226 {
2227         if (wwin->frame) {
2228                 int flags;
2229                 int newy, oldh;
2230
2231                 flags = WFF_LEFT_BUTTON | WFF_RIGHT_BUTTON;
2232
2233 #ifdef XKB_BUTTON_HINT
2234         if (wPreferences.modelock)
2235                 flags |= WFF_LANGUAGE_BUTTON;
2236 #endif
2237
2238                 if (HAS_TITLEBAR(wwin))
2239                         flags |= WFF_TITLEBAR;
2240                 if (HAS_RESIZEBAR(wwin) && IS_RESIZABLE(wwin))
2241                         flags |= WFF_RESIZEBAR;
2242                 if (HAS_BORDER(wwin))
2243                         flags |= WFF_BORDER;
2244                 if (wwin->flags.shaded)
2245                         flags |= WFF_IS_SHADED;
2246
2247                 oldh = wwin->frame->top_width;
2248                 wFrameWindowUpdateBorders(wwin->frame, flags);
2249                 if (oldh != wwin->frame->top_width) {
2250                         newy = wwin->frame_y + oldh - wwin->frame->top_width;
2251
2252                         XMoveWindow(dpy, wwin->client_win, 0, wwin->frame->top_width);
2253                         wWindowConfigure(wwin, wwin->frame_x, newy, wwin->client.width, wwin->client.height);
2254                 }
2255
2256                 flags = 0;
2257                 if (!WFLAGP(wwin, no_miniaturize_button)
2258                     && wwin->frame->flags.hide_left_button)
2259                         flags |= WFF_LEFT_BUTTON;
2260
2261 #ifdef XKB_BUTTON_HINT
2262                 if (!WFLAGP(wwin, no_language_button)
2263                     && wwin->frame->flags.hide_language_button) {
2264                         flags |= WFF_LANGUAGE_BUTTON;
2265                 }
2266 #endif
2267
2268                 if (!WFLAGP(wwin, no_close_button)
2269                     && wwin->frame->flags.hide_right_button)
2270                         flags |= WFF_RIGHT_BUTTON;
2271
2272                 if (flags != 0) {
2273                         wWindowUpdateButtonImages(wwin);
2274                         wFrameWindowShowButton(wwin->frame, flags);
2275                 }
2276
2277                 flags = 0;
2278                 if (WFLAGP(wwin, no_miniaturize_button)
2279                     && !wwin->frame->flags.hide_left_button)
2280                         flags |= WFF_LEFT_BUTTON;
2281
2282 #ifdef XKB_BUTTON_HINT
2283                 if (WFLAGP(wwin, no_language_button)
2284                     && !wwin->frame->flags.hide_language_button)
2285                         flags |= WFF_LANGUAGE_BUTTON;
2286 #endif
2287
2288                 if (WFLAGP(wwin, no_close_button)
2289                     && !wwin->frame->flags.hide_right_button)
2290                         flags |= WFF_RIGHT_BUTTON;
2291
2292                 if (flags != 0)
2293                         wFrameWindowHideButton(wwin->frame, flags);
2294
2295 #ifdef SHAPE
2296                 if (wShapeSupported && wwin->flags.shaped) {
2297                         wWindowSetShape(wwin);
2298                 }
2299 #endif
2300         }
2301 }
2302
2303 void wWindowSaveState(WWindow * wwin)
2304 {
2305         long data[10];
2306         int i;
2307
2308         memset(data, 0, sizeof(long) * 10);
2309         data[0] = wwin->frame->workspace;
2310         data[1] = wwin->flags.miniaturized;
2311         data[2] = wwin->flags.shaded;
2312         data[3] = wwin->flags.hidden;
2313         data[4] = wwin->flags.maximized;
2314         if (wwin->flags.maximized == 0) {
2315                 data[5] = wwin->frame_x;
2316                 data[6] = wwin->frame_y;
2317                 data[7] = wwin->frame->core->width;
2318                 data[8] = wwin->frame->core->height;
2319         } else {
2320                 data[5] = wwin->old_geometry.x;
2321                 data[6] = wwin->old_geometry.y;
2322                 data[7] = wwin->old_geometry.width;
2323                 data[8] = wwin->old_geometry.height;
2324         }
2325
2326         for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
2327                 if (wwin->screen_ptr->shortcutWindows[i] &&
2328                     WMCountInArray(wwin->screen_ptr->shortcutWindows[i], wwin))
2329                         data[9] |= 1 << i;
2330         }
2331         XChangeProperty(dpy, wwin->client_win, _XA_WINDOWMAKER_STATE,
2332                         _XA_WINDOWMAKER_STATE, 32, PropModeReplace, (unsigned char *)data, 10);
2333 }
2334
2335 static int getSavedState(Window window, WSavedState ** state)
2336 {
2337         Atom type_ret;
2338         int fmt_ret;
2339         unsigned long nitems_ret;
2340         unsigned long bytes_after_ret;
2341         long *data;
2342
2343         if (XGetWindowProperty(dpy, window, _XA_WINDOWMAKER_STATE, 0, 10,
2344                                True, _XA_WINDOWMAKER_STATE,
2345                                &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret,
2346                                (unsigned char **)&data) != Success || !data || nitems_ret < 10)
2347                 return 0;
2348
2349         *state = wmalloc(sizeof(WSavedState));
2350
2351         (*state)->workspace = data[0];
2352         (*state)->miniaturized = data[1];
2353         (*state)->shaded = data[2];
2354         (*state)->hidden = data[3];
2355         (*state)->maximized = data[4];
2356         (*state)->x = data[5];
2357         (*state)->y = data[6];
2358         (*state)->w = data[7];
2359         (*state)->h = data[8];
2360         (*state)->window_shortcuts = data[9];
2361
2362         XFree(data);
2363
2364         if (*state && type_ret == _XA_WINDOWMAKER_STATE)
2365                 return 1;
2366         else
2367                 return 0;
2368 }
2369
2370 #ifdef SHAPE
2371 void wWindowClearShape(WWindow * wwin)
2372 {
2373         XShapeCombineMask(dpy, wwin->frame->core->window, ShapeBounding,
2374                           0, wwin->frame->top_width, None, ShapeSet);
2375         XFlush(dpy);
2376 }
2377
2378 void wWindowSetShape(WWindow * wwin)
2379 {
2380         XRectangle rect[2];
2381         int count;
2382 #ifdef OPTIMIZE_SHAPE
2383         XRectangle *rects;
2384         XRectangle *urec;
2385         int ordering;
2386
2387         /* only shape is the client's */
2388         if (!HAS_TITLEBAR(wwin) && !HAS_RESIZEBAR(wwin)) {
2389                 goto alt_code;
2390         }
2391
2392         /* Get array of rectangles describing the shape mask */
2393         rects = XShapeGetRectangles(dpy, wwin->client_win, ShapeBounding, &count, &ordering);
2394         if (!rects) {
2395                 goto alt_code;
2396         }
2397
2398         urec = malloc(sizeof(XRectangle) * (count + 2));
2399         if (!urec) {
2400                 XFree(rects);
2401                 goto alt_code;
2402         }
2403
2404         /* insert our decoration rectangles in the rect list */
2405         memcpy(urec, rects, sizeof(XRectangle) * count);
2406         XFree(rects);
2407
2408         if (HAS_TITLEBAR(wwin)) {
2409                 urec[count].x = -1;
2410                 urec[count].y = -1 - wwin->frame->top_width;
2411                 urec[count].width = wwin->frame->core->width + 2;
2412                 urec[count].height = wwin->frame->top_width + 1;
2413                 count++;
2414         }
2415         if (HAS_RESIZEBAR(wwin)) {
2416                 urec[count].x = -1;
2417                 urec[count].y = wwin->frame->core->height - wwin->frame->bottom_width - wwin->frame->top_width;
2418                 urec[count].width = wwin->frame->core->width + 2;
2419                 urec[count].height = wwin->frame->bottom_width + 1;
2420                 count++;
2421         }
2422
2423         /* shape our frame window */
2424         XShapeCombineRectangles(dpy, wwin->frame->core->window, ShapeBounding,
2425                                 0, wwin->frame->top_width, urec, count, ShapeSet, Unsorted);
2426         XFlush(dpy);
2427         wfree(urec);
2428         return;
2429
2430  alt_code:
2431 #endif                          /* OPTIMIZE_SHAPE */
2432         count = 0;
2433         if (HAS_TITLEBAR(wwin)) {
2434                 rect[count].x = -1;
2435                 rect[count].y = -1;
2436                 rect[count].width = wwin->frame->core->width + 2;
2437                 rect[count].height = wwin->frame->top_width + 1;
2438                 count++;
2439         }
2440         if (HAS_RESIZEBAR(wwin)) {
2441                 rect[count].x = -1;
2442                 rect[count].y = wwin->frame->core->height - wwin->frame->bottom_width;
2443                 rect[count].width = wwin->frame->core->width + 2;
2444                 rect[count].height = wwin->frame->bottom_width + 1;
2445                 count++;
2446         }
2447         if (count > 0) {
2448                 XShapeCombineRectangles(dpy, wwin->frame->core->window, ShapeBounding,
2449                                         0, 0, rect, count, ShapeSet, Unsorted);
2450         }
2451         XShapeCombineShape(dpy, wwin->frame->core->window, ShapeBounding,
2452                            0, wwin->frame->top_width, wwin->client_win,
2453                            ShapeBounding, (count > 0 ? ShapeUnion : ShapeSet));
2454         XFlush(dpy);
2455 }
2456 #endif                          /* SHAPE */
2457
2458 /* ====================================================================== */
2459
2460 static FocusMode getFocusMode(WWindow * wwin)
2461 {
2462         FocusMode mode;
2463
2464         if ((wwin->wm_hints) && (wwin->wm_hints->flags & InputHint)) {
2465                 if (wwin->wm_hints->input == True) {
2466                         if (wwin->protocols.TAKE_FOCUS)
2467                                 mode = WFM_LOCALLY_ACTIVE;
2468                         else
2469                                 mode = WFM_PASSIVE;
2470                 } else {
2471                         if (wwin->protocols.TAKE_FOCUS)
2472                                 mode = WFM_GLOBALLY_ACTIVE;
2473                         else
2474                                 mode = WFM_NO_INPUT;
2475                 }
2476         } else {
2477                 mode = WFM_PASSIVE;
2478         }
2479         return mode;
2480 }
2481
2482 void wWindowSetKeyGrabs(WWindow * wwin)
2483 {
2484         int i;
2485         WShortKey *key;
2486
2487         for (i = 0; i < WKBD_LAST; i++) {
2488                 key = &wKeyBindings[i];
2489
2490                 if (key->keycode == 0)
2491                         continue;
2492                 if (key->modifier != AnyModifier) {
2493                         XGrabKey(dpy, key->keycode, key->modifier | LockMask,
2494                                  wwin->frame->core->window, True, GrabModeAsync, GrabModeAsync);
2495 #ifdef NUMLOCK_HACK
2496                         /* Also grab all modifier combinations possible that include,
2497                          * LockMask, ScrollLockMask and NumLockMask, so that keygrabs
2498                          * work even if the NumLock/ScrollLock key is on.
2499                          */
2500                         wHackedGrabKey(key->keycode, key->modifier,
2501                                        wwin->frame->core->window, True, GrabModeAsync, GrabModeAsync);
2502 #endif
2503                 }
2504                 XGrabKey(dpy, key->keycode, key->modifier,
2505                          wwin->frame->core->window, True, GrabModeAsync, GrabModeAsync);
2506         }
2507
2508         wRootMenuBindShortcuts(wwin->frame->core->window);
2509 }
2510
2511 void wWindowResetMouseGrabs(WWindow * wwin)
2512 {
2513         /* Mouse grabs can't be done on the client window because of
2514          * ICCCM and because clients that try to do the same will crash.
2515          *
2516          * But there is a problem wich makes tbar buttons of unfocused
2517          * windows not usable as the click goes to the frame window instead
2518          * of the button itself. Must figure a way to fix that.
2519          */
2520
2521         XUngrabButton(dpy, AnyButton, AnyModifier, wwin->client_win);
2522
2523         if (!WFLAGP(wwin, no_bind_mouse)) {
2524                 /* grabs for Meta+drag */
2525                 wHackedGrabButton(AnyButton, MOD_MASK, wwin->client_win,
2526                                   True, ButtonPressMask | ButtonReleaseMask,
2527                                   GrabModeSync, GrabModeAsync, None, None);
2528
2529                 /* for CTRL+Wheel to Scroll Horiz, we have to grab CTRL as well
2530                  * but we only grab it for Button4 and Button 5 since a lot of apps
2531                  * use CTRL+Button1-3 for app related functionality
2532                  */
2533                 wHackedGrabButton(Button4, ControlMask, wwin->client_win,
2534                                   True, ButtonPressMask | ButtonReleaseMask,
2535                                   GrabModeSync, GrabModeAsync, None, None);
2536                 wHackedGrabButton(Button5, ControlMask, wwin->client_win,
2537                                   True, ButtonPressMask | ButtonReleaseMask,
2538                                   GrabModeSync, GrabModeAsync, None, None);
2539
2540                 wHackedGrabButton(Button4, MOD_MASK | ControlMask, wwin->client_win,
2541                                   True, ButtonPressMask | ButtonReleaseMask,
2542                                   GrabModeSync, GrabModeAsync, None, None);
2543                 wHackedGrabButton(Button5, MOD_MASK | ControlMask, wwin->client_win,
2544                                   True, ButtonPressMask | ButtonReleaseMask,
2545                                   GrabModeSync, GrabModeAsync, None, None);
2546         }
2547
2548         if (!wwin->flags.focused && !WFLAGP(wwin, no_focusable)
2549             && !wwin->flags.is_gnustep) {
2550                 /* the passive grabs to focus the window */
2551                 /* if (wPreferences.focus_mode == WKF_CLICK) */
2552                 XGrabButton(dpy, AnyButton, AnyModifier, wwin->client_win,
2553                             True, ButtonPressMask | ButtonReleaseMask, GrabModeSync, GrabModeAsync, None, None);
2554         }
2555         XFlush(dpy);
2556 }
2557
2558 void wWindowUpdateGNUstepAttr(WWindow * wwin, GNUstepWMAttributes * attr)
2559 {
2560         if (attr->flags & GSExtraFlagsAttr) {
2561                 if (MGFLAGP(wwin, broken_close) != (attr->extra_flags & GSDocumentEditedFlag)) {
2562                         wwin->client_flags.broken_close = !MGFLAGP(wwin, broken_close);
2563                         wWindowUpdateButtonImages(wwin);
2564                 }
2565         }
2566 }
2567
2568 WMagicNumber wWindowAddSavedState(char *instance, char *class, char *command, pid_t pid, WSavedState * state)
2569 {
2570         WWindowState *wstate;
2571
2572         wstate = malloc(sizeof(WWindowState));
2573         if (!wstate)
2574                 return 0;
2575
2576         memset(wstate, 0, sizeof(WWindowState));
2577         wstate->pid = pid;
2578         if (instance)
2579                 wstate->instance = wstrdup(instance);
2580         if (class)
2581                 wstate->class = wstrdup(class);
2582         if (command)
2583                 wstate->command = wstrdup(command);
2584         wstate->state = state;
2585
2586         wstate->next = windowState;
2587         windowState = wstate;
2588
2589         return wstate;
2590 }
2591
2592 #define SAME(x, y) (((x) && (y) && !strcmp((x), (y))) || (!(x) && !(y)))
2593
2594 WMagicNumber wWindowGetSavedState(Window win)
2595 {
2596         char *instance, *class, *command = NULL;
2597         WWindowState *wstate = windowState;
2598
2599         if (!wstate)
2600                 return NULL;
2601
2602         command = GetCommandForWindow(win);
2603         if (!command)
2604                 return NULL;
2605
2606         if (PropGetWMClass(win, &class, &instance)) {
2607                 while (wstate) {
2608                         if (SAME(instance, wstate->instance) &&
2609                             SAME(class, wstate->class) && SAME(command, wstate->command)) {
2610                                 break;
2611                         }
2612                         wstate = wstate->next;
2613                 }
2614         } else {
2615                 wstate = NULL;
2616         }
2617
2618         if (command)
2619                 wfree(command);
2620         if (instance)
2621                 XFree(instance);
2622         if (class)
2623                 XFree(class);
2624
2625         return wstate;
2626 }
2627
2628 void wWindowDeleteSavedState(WMagicNumber id)
2629 {
2630         WWindowState *tmp, *wstate = (WWindowState *) id;
2631
2632         if (!wstate || !windowState)
2633                 return;
2634
2635         tmp = windowState;
2636         if (tmp == wstate) {
2637                 windowState = wstate->next;
2638                 if (wstate->instance)
2639                         wfree(wstate->instance);
2640                 if (wstate->class)
2641                         wfree(wstate->class);
2642                 if (wstate->command)
2643                         wfree(wstate->command);
2644                 wfree(wstate->state);
2645                 wfree(wstate);
2646         } else {
2647                 while (tmp->next) {
2648                         if (tmp->next == wstate) {
2649                                 tmp->next = wstate->next;
2650                                 if (wstate->instance)
2651                                         wfree(wstate->instance);
2652                                 if (wstate->class)
2653                                         wfree(wstate->class);
2654                                 if (wstate->command)
2655                                         wfree(wstate->command);
2656                                 wfree(wstate->state);
2657                                 wfree(wstate);
2658                                 break;
2659                         }
2660                         tmp = tmp->next;
2661                 }
2662         }
2663 }
2664
2665 void wWindowDeleteSavedStatesForPID(pid_t pid)
2666 {
2667         WWindowState *tmp, *wstate;
2668
2669         if (!windowState)
2670                 return;
2671
2672         tmp = windowState;
2673         if (tmp->pid == pid) {
2674                 wstate = windowState;
2675                 windowState = tmp->next;
2676                 if (wstate->instance)
2677                         wfree(wstate->instance);
2678                 if (wstate->class)
2679                         wfree(wstate->class);
2680                 if (wstate->command)
2681                         wfree(wstate->command);
2682                 wfree(wstate->state);
2683                 wfree(wstate);
2684         } else {
2685                 while (tmp->next) {
2686                         if (tmp->next->pid == pid) {
2687                                 wstate = tmp->next;
2688                                 tmp->next = wstate->next;
2689                                 if (wstate->instance)
2690                                         wfree(wstate->instance);
2691                                 if (wstate->class)
2692                                         wfree(wstate->class);
2693                                 if (wstate->command)
2694                                         wfree(wstate->command);
2695                                 wfree(wstate->state);
2696                                 wfree(wstate);
2697                                 break;
2698                         }
2699                         tmp = tmp->next;
2700                 }
2701         }
2702 }
2703
2704 void wWindowSetOmnipresent(WWindow *wwin, Bool flag)
2705 {
2706         if (wwin->flags.omnipresent == flag)
2707                 return;
2708
2709         wwin->flags.omnipresent = flag;
2710         WMPostNotificationName(WMNChangedState, wwin, "omnipresent");
2711 }
2712
2713 static void resizebarMouseDown(WCoreWindow *sender, void *data, XEvent *event)
2714 {
2715         WWindow *wwin = data;
2716
2717 #ifndef NUMLOCK_HACK
2718         if ((event->xbutton.state & ValidModMask)
2719             != (event->xbutton.state & ~LockMask)) {
2720                 wwarning(_("the NumLock, ScrollLock or similar key seems to be turned on.\n"
2721                            "Turn it off or some mouse actions and keyboard shortcuts will not work."));
2722         }
2723 #endif
2724
2725         event->xbutton.state &= ValidModMask;
2726
2727         CloseWindowMenu(wwin->screen_ptr);
2728
2729         if (wPreferences.focus_mode == WKF_CLICK && !(event->xbutton.state & ControlMask)
2730             && !WFLAGP(wwin, no_focusable)) {
2731                 wSetFocusTo(wwin->screen_ptr, wwin);
2732         }
2733
2734         if (event->xbutton.button == Button1)
2735                 wRaiseFrame(wwin->frame->core);
2736
2737         if (event->xbutton.window != wwin->frame->resizebar->window) {
2738                 if (XGrabPointer(dpy, wwin->frame->resizebar->window, True,
2739                                  ButtonMotionMask | ButtonReleaseMask | ButtonPressMask,
2740                                  GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) {
2741                         return;
2742                 }
2743         }
2744
2745         if (event->xbutton.state & MOD_MASK) {
2746                 /* move the window */
2747                 wMouseMoveWindow(wwin, event);
2748                 XUngrabPointer(dpy, CurrentTime);
2749         } else {
2750                 wMouseResizeWindow(wwin, event);
2751                 XUngrabPointer(dpy, CurrentTime);
2752         }
2753 }
2754
2755 static void titlebarDblClick(WCoreWindow *sender, void *data, XEvent *event)
2756 {
2757         WWindow *wwin = data;
2758
2759         event->xbutton.state &= ValidModMask;
2760
2761         if (event->xbutton.button == Button1) {
2762                 if (event->xbutton.state == 0) {
2763                         if (!WFLAGP(wwin, no_shadeable)) {
2764                                 /* shade window */
2765                                 if (wwin->flags.shaded)
2766                                         wUnshadeWindow(wwin);
2767                                 else
2768                                         wShadeWindow(wwin);
2769                         }
2770                 } else {
2771                         int dir = 0;
2772
2773                         if (event->xbutton.state & ControlMask)
2774                                 dir |= MAX_VERTICAL;
2775
2776                         if (event->xbutton.state & ShiftMask) {
2777                                 dir |= MAX_HORIZONTAL;
2778                                 if (!(event->xbutton.state & ControlMask))
2779                                         wSelectWindow(wwin, !wwin->flags.selected);
2780                         }
2781
2782                         /* maximize window */
2783                         if (dir != 0 && IS_RESIZABLE(wwin)) {
2784                                 int ndir = dir ^ wwin->flags.maximized;
2785
2786                                 if (ndir != 0)
2787                                         wMaximizeWindow(wwin, ndir);
2788                                 else
2789                                         wUnmaximizeWindow(wwin);
2790                         }
2791                 }
2792         } else if (event->xbutton.button == Button3) {
2793                 if (event->xbutton.state & MOD_MASK) {
2794                         wHideOtherApplications(wwin);
2795                 }
2796         } else if (event->xbutton.button == Button2) {
2797                 wSelectWindow(wwin, !wwin->flags.selected);
2798         } else if (event->xbutton.button == WINGsConfiguration.mouseWheelUp) {
2799                 wShadeWindow(wwin);
2800         } else if (event->xbutton.button == WINGsConfiguration.mouseWheelDown) {
2801                 wUnshadeWindow(wwin);
2802         }
2803 }
2804
2805 static void frameMouseDown(WObjDescriptor *desc, XEvent *event)
2806 {
2807         WWindow *wwin = desc->parent;
2808         unsigned int new_width, w_scale;
2809         unsigned int new_height, h_scale;
2810         unsigned int resize_width_increment = 0;
2811         unsigned int resize_height_increment = 0;
2812
2813         if (wwin->normal_hints) {
2814                 w_scale = ceil(wPreferences.resize_increment / wwin->normal_hints->width_inc);
2815                 h_scale = ceil(wPreferences.resize_increment / wwin->normal_hints->height_inc);
2816                 resize_width_increment = wwin->normal_hints->width_inc * w_scale;
2817                 resize_height_increment = wwin->normal_hints->height_inc * h_scale;
2818         }
2819         if (resize_width_increment <= 1 && resize_height_increment <= 1) {
2820                 resize_width_increment = wPreferences.resize_increment;
2821                 resize_height_increment = wPreferences.resize_increment;
2822         }
2823
2824         event->xbutton.state &= ValidModMask;
2825
2826         CloseWindowMenu(wwin->screen_ptr);
2827
2828         if (!(event->xbutton.state & ControlMask) && !WFLAGP(wwin, no_focusable))
2829                 wSetFocusTo(wwin->screen_ptr, wwin);
2830
2831         if (event->xbutton.button == Button1)
2832                 wRaiseFrame(wwin->frame->core);
2833
2834         if (event->xbutton.state & ControlMask) {
2835                 if (event->xbutton.button == Button4) {
2836                         new_width = wwin->client.width - resize_width_increment;
2837                         wWindowConstrainSize(wwin, &new_width, &wwin->client.height);
2838                         wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, new_width, wwin->client.height);
2839                 }
2840                 if (event->xbutton.button == Button5) {
2841                         new_width = wwin->client.width + resize_width_increment;
2842                         wWindowConstrainSize(wwin, &new_width, &wwin->client.height);
2843                         wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, new_width, wwin->client.height);
2844                 }
2845         }
2846
2847         if (event->xbutton.state & MOD_MASK) {
2848                 /* move the window */
2849                 if (XGrabPointer(dpy, wwin->client_win, False,
2850                                  ButtonMotionMask | ButtonReleaseMask | ButtonPressMask,
2851                                  GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) {
2852                         return;
2853                 }
2854                 if (event->xbutton.button == Button3) {
2855                         wMouseResizeWindow(wwin, event);
2856                 } else if (event->xbutton.button == Button4) {
2857                         new_height = wwin->client.height - resize_height_increment;
2858                         wWindowConstrainSize(wwin, &wwin->client.width, &new_height);
2859                         wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, wwin->client.width, new_height);
2860                 } else if (event->xbutton.button == Button5) {
2861                         new_height = wwin->client.height + resize_height_increment;
2862                         wWindowConstrainSize(wwin, &wwin->client.width, &new_height);
2863                         wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, wwin->client.width, new_height);
2864                 } else if (event->xbutton.button == Button1 || event->xbutton.button == Button2) {
2865                         wMouseMoveWindow(wwin, event);
2866                 }
2867                 XUngrabPointer(dpy, CurrentTime);
2868         }
2869 }
2870
2871 static void titlebarMouseDown(WCoreWindow *sender, void *data, XEvent *event)
2872 {
2873         WWindow *wwin = (WWindow *) data;
2874
2875 #ifndef NUMLOCK_HACK
2876         if ((event->xbutton.state & ValidModMask)
2877             != (event->xbutton.state & ~LockMask)) {
2878                 wwarning(_("the NumLock, ScrollLock or similar key seems to be turned on.\n"
2879                            "Turn it off or some mouse actions and keyboard shortcuts will not work."));
2880         }
2881 #endif
2882         event->xbutton.state &= ValidModMask;
2883
2884         CloseWindowMenu(wwin->screen_ptr);
2885
2886         if (wPreferences.focus_mode == WKF_CLICK && !(event->xbutton.state & ControlMask)
2887             && !WFLAGP(wwin, no_focusable)) {
2888                 wSetFocusTo(wwin->screen_ptr, wwin);
2889         }
2890
2891         if (event->xbutton.button == Button1 || event->xbutton.button == Button2) {
2892
2893                 if (event->xbutton.button == Button1) {
2894                         if (event->xbutton.state & MOD_MASK) {
2895                                 wLowerFrame(wwin->frame->core);
2896                         } else {
2897                                 wRaiseFrame(wwin->frame->core);
2898                         }
2899                 }
2900                 if ((event->xbutton.state & ShiftMask)
2901                     && !(event->xbutton.state & ControlMask)) {
2902                         wSelectWindow(wwin, !wwin->flags.selected);
2903                         return;
2904                 }
2905                 if (event->xbutton.window != wwin->frame->titlebar->window
2906                     && XGrabPointer(dpy, wwin->frame->titlebar->window, False,
2907                                     ButtonMotionMask | ButtonReleaseMask | ButtonPressMask,
2908                                     GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) {
2909                         return;
2910                 }
2911
2912                 /* move the window */
2913                 wMouseMoveWindow(wwin, event);
2914
2915                 XUngrabPointer(dpy, CurrentTime);
2916         } else if (event->xbutton.button == Button3 && event->xbutton.state == 0
2917                    && !wwin->flags.internal_window && !WCHECK_STATE(WSTATE_MODAL)) {
2918                 WObjDescriptor *desc;
2919
2920                 if (event->xbutton.window != wwin->frame->titlebar->window
2921                     && XGrabPointer(dpy, wwin->frame->titlebar->window, False,
2922                                     ButtonMotionMask | ButtonReleaseMask | ButtonPressMask,
2923                                     GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) {
2924                         return;
2925                 }
2926
2927                 OpenWindowMenu(wwin, event->xbutton.x_root, wwin->frame_y + wwin->frame->top_width, False);
2928
2929                 /* allow drag select */
2930                 desc = &wwin->screen_ptr->window_menu->menu->descriptor;
2931                 event->xany.send_event = True;
2932                 (*desc->handle_mousedown) (desc, event);
2933
2934                 XUngrabPointer(dpy, CurrentTime);
2935         }
2936 }
2937
2938 static void windowCloseClick(WCoreWindow *sender, void *data, XEvent *event)
2939 {
2940         WWindow *wwin = data;
2941
2942         event->xbutton.state &= ValidModMask;
2943
2944         CloseWindowMenu(wwin->screen_ptr);
2945
2946         if (event->xbutton.button < Button1 || event->xbutton.button > Button3)
2947                 return;
2948
2949         /* if control-click, kill the client */
2950         if (event->xbutton.state & ControlMask) {
2951                 wClientKill(wwin);
2952         } else {
2953                 if (wwin->protocols.DELETE_WINDOW && event->xbutton.state == 0) {
2954                         /* send delete message */
2955                         wClientSendProtocol(wwin, _XA_WM_DELETE_WINDOW, LastTimestamp);
2956                 }
2957         }
2958 }
2959
2960 static void windowCloseDblClick(WCoreWindow *sender, void *data, XEvent *event)
2961 {
2962         WWindow *wwin = data;
2963
2964         CloseWindowMenu(wwin->screen_ptr);
2965
2966         if (event->xbutton.button < Button1 || event->xbutton.button > Button3)
2967                 return;
2968
2969         /* send delete message */
2970         if (wwin->protocols.DELETE_WINDOW) {
2971                 wClientSendProtocol(wwin, _XA_WM_DELETE_WINDOW, LastTimestamp);
2972         } else {
2973                 wClientKill(wwin);
2974         }
2975 }
2976
2977 #ifdef XKB_BUTTON_HINT
2978 static void windowLanguageClick(WCoreWindow *sender, void *data, XEvent *event)
2979 {
2980         WWindow *wwin = data;
2981         WFrameWindow *fwin = wwin->frame;
2982         WScreen *scr = fwin->screen_ptr;
2983         int tl;
2984
2985         if (event->xbutton.button != Button1 && event->xbutton.button != Button3)
2986                 return;
2987         tl = wwin->frame->languagemode;
2988         wwin->frame->languagemode = wwin->frame->last_languagemode;
2989         wwin->frame->last_languagemode = tl;
2990         wSetFocusTo(scr, wwin);
2991         wwin->frame->languagebutton_image =
2992             wwin->frame->screen_ptr->b_pixmaps[WBUT_XKBGROUP1 + wwin->frame->languagemode];
2993         wFrameWindowUpdateLanguageButton(wwin->frame);
2994         if (event->xbutton.button == Button3)
2995                 return;
2996         wRaiseFrame(fwin->core);
2997 }
2998 #endif
2999
3000 static void windowIconifyClick(WCoreWindow *sender, void *data, XEvent *event)
3001 {
3002         WWindow *wwin = data;
3003
3004         event->xbutton.state &= ValidModMask;
3005
3006         CloseWindowMenu(wwin->screen_ptr);
3007
3008         if (event->xbutton.button < Button1 || event->xbutton.button > Button3)
3009                 return;
3010
3011         if (wwin->protocols.MINIATURIZE_WINDOW && event->xbutton.state == 0) {
3012                 wClientSendProtocol(wwin, _XA_GNUSTEP_WM_MINIATURIZE_WINDOW, LastTimestamp);
3013         } else {
3014                 WApplication *wapp;
3015                 if ((event->xbutton.state & ControlMask) || (event->xbutton.button == Button3)) {
3016
3017                         wapp = wApplicationOf(wwin->main_window);
3018                         if (wapp && !WFLAGP(wwin, no_appicon))
3019                                 wHideApplication(wapp);
3020                 } else if (event->xbutton.state == 0) {
3021                         wIconifyWindow(wwin);
3022                 }
3023         }
3024 }