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