]> icculus.org git repositories - mikachu/openbox.git/blob - openbox/client.c
refix for managing iconic windows, without having the frame map which caused flashing.
[mikachu/openbox.git] / openbox / client.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2    
3    client.c for the Openbox window manager
4    Copyright (c) 2006        Mikael Magnusson
5    Copyright (c) 2003-2007   Dana Jansens
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    See the COPYING file for a copy of the GNU General Public License.
18 */
19
20 #include "client.h"
21 #include "debug.h"
22 #include "startupnotify.h"
23 #include "dock.h"
24 #include "xerror.h"
25 #include "screen.h"
26 #include "moveresize.h"
27 #include "place.h"
28 #include "prop.h"
29 #include "extensions.h"
30 #include "frame.h"
31 #include "session.h"
32 #include "event.h"
33 #include "grab.h"
34 #include "focus.h"
35 #include "stacking.h"
36 #include "openbox.h"
37 #include "group.h"
38 #include "config.h"
39 #include "menuframe.h"
40 #include "keyboard.h"
41 #include "mouse.h"
42 #include "render/render.h"
43
44 #include <glib.h>
45 #include <X11/Xutil.h>
46
47 /*! The event mask to grab on client windows */
48 #define CLIENT_EVENTMASK (PropertyChangeMask | StructureNotifyMask)
49
50 #define CLIENT_NOPROPAGATEMASK (ButtonPressMask | ButtonReleaseMask | \
51                                 ButtonMotionMask)
52
53 typedef struct
54 {
55     ObClientDestructor func;
56     gpointer data;
57 } Destructor;
58
59 GList         *client_list           = NULL;
60
61 static GSList *client_destructors    = NULL;
62 static Time    client_last_user_time = CurrentTime;
63
64 static void client_get_all(ObClient *self);
65 static void client_toggle_border(ObClient *self, gboolean show);
66 static void client_get_startup_id(ObClient *self);
67 static void client_get_area(ObClient *self);
68 static void client_get_desktop(ObClient *self);
69 static void client_get_state(ObClient *self);
70 static void client_get_layer(ObClient *self);
71 static void client_get_shaped(ObClient *self);
72 static void client_get_mwm_hints(ObClient *self);
73 static void client_get_gravity(ObClient *self);
74 static void client_change_allowed_actions(ObClient *self);
75 static void client_change_state(ObClient *self);
76 static void client_change_wm_state(ObClient *self);
77 static void client_apply_startup_state(ObClient *self, gint x, gint y);
78 static void client_restore_session_state(ObClient *self);
79 static void client_restore_session_stacking(ObClient *self);
80 static ObAppSettings *client_get_settings_state(ObClient *self);
81
82 void client_startup(gboolean reconfig)
83 {
84     if (reconfig) return;
85
86     client_set_list();
87 }
88
89 void client_shutdown(gboolean reconfig)
90 {
91 }
92
93 void client_add_destructor(ObClientDestructor func, gpointer data)
94 {
95     Destructor *d = g_new(Destructor, 1);
96     d->func = func;
97     d->data = data;
98     client_destructors = g_slist_prepend(client_destructors, d);
99 }
100
101 void client_remove_destructor(ObClientDestructor func)
102 {
103     GSList *it;
104
105     for (it = client_destructors; it; it = g_slist_next(it)) {
106         Destructor *d = it->data;
107         if (d->func == func) {
108             g_free(d);
109             client_destructors = g_slist_delete_link(client_destructors, it);
110             break;
111         }
112     }
113 }
114
115 void client_set_list()
116 {
117     Window *windows, *win_it;
118     GList *it;
119     guint size = g_list_length(client_list);
120
121     /* create an array of the window ids */
122     if (size > 0) {
123         windows = g_new(Window, size);
124         win_it = windows;
125         for (it = client_list; it; it = g_list_next(it), ++win_it)
126             *win_it = ((ObClient*)it->data)->window;
127     } else
128         windows = NULL;
129
130     PROP_SETA32(RootWindow(ob_display, ob_screen),
131                 net_client_list, window, (gulong*)windows, size);
132
133     if (windows)
134         g_free(windows);
135
136     stacking_set_list();
137 }
138
139 /*
140   void client_foreach_transient(ObClient *self, ObClientForeachFunc func, gpointer data)
141   {
142   GSList *it;
143
144   for (it = self->transients; it; it = g_slist_next(it)) {
145   if (!func(it->data, data)) return;
146   client_foreach_transient(it->data, func, data);
147   }
148   }
149
150   void client_foreach_ancestor(ObClient *self, ObClientForeachFunc func, gpointer data)
151   {
152   if (self->transient_for) {
153   if (self->transient_for != OB_TRAN_GROUP) {
154   if (!func(self->transient_for, data)) return;
155   client_foreach_ancestor(self->transient_for, func, data);
156   } else {
157   GSList *it;
158
159   for (it = self->group->members; it; it = g_slist_next(it))
160   if (it->data != self &&
161   !((ObClient*)it->data)->transient_for) {
162   if (!func(it->data, data)) return;
163   client_foreach_ancestor(it->data, func, data);
164   }
165   }
166   }
167   }
168 */
169
170 void client_manage_all()
171 {
172     guint i, j, nchild;
173     Window w, *children;
174     XWMHints *wmhints;
175     XWindowAttributes attrib;
176
177     XQueryTree(ob_display, RootWindow(ob_display, ob_screen),
178                &w, &w, &children, &nchild);
179
180     /* remove all icon windows from the list */
181     for (i = 0; i < nchild; i++) {
182         if (children[i] == None) continue;
183         wmhints = XGetWMHints(ob_display, children[i]);
184         if (wmhints) {
185             if ((wmhints->flags & IconWindowHint) &&
186                 (wmhints->icon_window != children[i]))
187                 for (j = 0; j < nchild; j++)
188                     if (children[j] == wmhints->icon_window) {
189                         children[j] = None;
190                         break;
191                     }
192             XFree(wmhints);
193         }
194     }
195
196     for (i = 0; i < nchild; ++i) {
197         if (children[i] == None)
198             continue;
199         if (XGetWindowAttributes(ob_display, children[i], &attrib)) {
200             if (attrib.override_redirect) continue;
201
202             if (attrib.map_state != IsUnmapped)
203                 client_manage(children[i]);
204         }
205     }
206     XFree(children);
207 }
208
209 void client_manage(Window window)
210 {
211     ObClient *self;
212     XEvent e;
213     XWindowAttributes attrib;
214     XSetWindowAttributes attrib_set;
215     XWMHints *wmhint;
216     gboolean activate = FALSE;
217     ObAppSettings *settings;
218     gint newx, newy;
219
220     grab_server(TRUE);
221
222     /* check if it has already been unmapped by the time we started mapping
223        the grab does a sync so we don't have to here */
224     if (XCheckTypedWindowEvent(ob_display, window, DestroyNotify, &e) ||
225         XCheckTypedWindowEvent(ob_display, window, UnmapNotify, &e))
226     {
227         XPutBackEvent(ob_display, &e);
228
229         grab_server(FALSE);
230         return; /* don't manage it */
231     }
232
233     /* make sure it isn't an override-redirect window */
234     if (!XGetWindowAttributes(ob_display, window, &attrib) ||
235         attrib.override_redirect)
236     {
237         grab_server(FALSE);
238         return; /* don't manage it */
239     }
240   
241     /* is the window a docking app */
242     if ((wmhint = XGetWMHints(ob_display, window))) {
243         if ((wmhint->flags & StateHint) &&
244             wmhint->initial_state == WithdrawnState)
245         {
246             dock_add(window, wmhint);
247             grab_server(FALSE);
248             XFree(wmhint);
249             return;
250         }
251         XFree(wmhint);
252     }
253
254     ob_debug("Managing window: %lx\n", window);
255
256     /* choose the events we want to receive on the CLIENT window */
257     attrib_set.event_mask = CLIENT_EVENTMASK;
258     attrib_set.do_not_propagate_mask = CLIENT_NOPROPAGATEMASK;
259     XChangeWindowAttributes(ob_display, window,
260                             CWEventMask|CWDontPropagate, &attrib_set);
261
262
263     /* create the ObClient struct, and populate it from the hints on the
264        window */
265     self = g_new0(ObClient, 1);
266     self->obwin.type = Window_Client;
267     self->window = window;
268
269     /* non-zero defaults */
270     self->title_count = 1;
271     self->wmstate = WithdrawnState; /* make sure it gets updated first time */
272     self->layer = -1;
273     self->desktop = screen_num_desktops; /* always an invalid value */
274     self->user_time = ~0; /* maximum value, always newer than the real time */
275
276     client_get_all(self);
277     client_restore_session_state(self);
278     /* per-app settings override stuff, and return the settings for other
279        uses too */
280     settings = client_get_settings_state(self);
281
282     client_calc_layer(self);
283
284     {
285         Time t = sn_app_started(self->startup_id, self->class);
286         if (t) self->user_time = t;
287     }
288
289     /* update the focus lists, do this before the call to change_state or
290        it can end up in the list twice! */
291     focus_order_add_new(self);
292
293     /* remove the client's border (and adjust re gravity) */
294     client_toggle_border(self, FALSE);
295      
296     /* specify that if we exit, the window should not be destroyed and should
297        be reparented back to root automatically */
298     XChangeSaveSet(ob_display, window, SetModeInsert);
299
300     /* create the decoration frame for the client window */
301     self->frame = frame_new(self);
302
303     frame_grab_client(self->frame, self);
304
305     /* do this after we have a frame.. it uses the frame to help determine the
306        WM_STATE to apply. */
307     client_change_state(self);
308
309     grab_server(FALSE);
310
311     stacking_add_nonintrusive(CLIENT_AS_WINDOW(self));
312     client_restore_session_stacking(self);
313
314     /* focus the new window? */
315     if (ob_state() != OB_STATE_STARTING &&
316         /* this means focus=true for window is same as config_focus_new=true */
317         ((config_focus_new || (settings && settings->focus == 1)) ||
318          client_search_focus_parent(self)) &&
319         /* this checks for focus=false for the window */
320         (!settings || settings->focus != 0) &&
321         /* note the check against Type_Normal/Dialog, not client_normal(self),
322            which would also include other types. in this case we want more
323            strict rules for focus */
324         (self->type == OB_CLIENT_TYPE_NORMAL ||
325          self->type == OB_CLIENT_TYPE_DIALOG))
326     {
327         activate = TRUE;
328 #if 0
329         if (self->desktop != screen_desktop) {
330             /* activate the window */
331             activate = TRUE;
332         } else {
333             gboolean group_foc = FALSE;
334
335             if (self->group) {
336                 GSList *it;
337
338                 for (it = self->group->members; it; it = g_slist_next(it))
339                 {
340                     if (client_focused(it->data))
341                     {
342                         group_foc = TRUE;
343                         break;
344                     }
345                 }
346             }
347             if ((group_foc ||
348                  (!self->transient_for && (!self->group ||
349                                            !self->group->members->next))) ||
350                 client_search_focus_tree_full(self) ||
351                 !focus_client ||
352                 !client_normal(focus_client))
353             {
354                 /* activate the window */
355                 activate = TRUE;
356             }
357         }
358 #endif
359     }
360
361     /* get the current position */
362     newx = self->area.x;
363     newy = self->area.y;
364
365     /* figure out placement for the window */
366     if (ob_state() == OB_STATE_RUNNING) {
367         gboolean transient;
368
369         transient = place_client(self, &newx, &newy, settings);
370
371         /* make sure the window is visible. */
372         client_find_onscreen(self, &newx, &newy,
373                              self->frame->area.width,
374                              self->frame->area.height,
375                              /* non-normal clients has less rules, and
376                                 windows that are being restored from a
377                                 session do also. we can assume you want
378                                 it back where you saved it. Clients saying
379                                 they placed themselves are subjected to
380                                 harder rules, ones that are placed by
381                                 place.c or by the user are allowed partially
382                                 off-screen and on xinerama divides (ie,
383                                 it is up to the placement routines to avoid
384                                 the xinerama divides) */
385                              transient ||
386                              (((self->positioned & PPosition) &&
387                                !(self->positioned & USPosition)) &&
388                               client_normal(self) &&
389                               !self->session));
390     }
391
392     /* do this after the window is placed, so the premax/prefullscreen numbers
393        won't be all wacko!!
394        also, this moves the window to the position where it has been placed
395     */
396     client_apply_startup_state(self, newx, newy);
397
398     keyboard_grab_for_client(self, TRUE);
399     mouse_grab_for_client(self, TRUE);
400
401     if (activate) {
402         /* This is focus stealing prevention */
403         ob_debug("Want to focus new window 0x%x with time %u (last time %u)\n",
404                  self->window, self->user_time, client_last_user_time);
405
406         /* If a nothing at all, or a parent was focused, then focus this
407            always
408         */
409         if (!focus_client || client_search_focus_parent(self) != NULL)
410             activate = TRUE;
411         else
412         {
413             /* If time stamp is old, don't steal focus */
414             if (self->user_time && self->user_time < client_last_user_time)
415                 activate = FALSE;
416             /* Don't steal focus from globally active clients.
417                I stole this idea from KWin. It seems nice.
418              */
419             if (!focus_client->can_focus && focus_client->focus_notify)
420                 activate = FALSE;
421         }
422
423         if (activate)
424         {
425             /* since focus can change the stacking orders, if we focus the
426                window then the standard raise it gets is not enough, we need
427                to queue one for after the focus change takes place */
428             client_raise(self);
429         } else {
430             ob_debug("Focus stealing prevention activated for %s with time %u "
431                      "(last time %u)\n",
432                      self->title, self->user_time, client_last_user_time);
433             /* if the client isn't focused, then hilite it so the user
434                knows it is there */
435             client_hilite(self, TRUE);
436         }
437     }
438     else {
439         /* This may look rather odd. Well it's because new windows are added
440            to the stacking order non-intrusively. If we're not going to focus
441            the new window or hilite it, then we raise it to the top. This will
442            take affect for things that don't get focused like splash screens.
443            Also if you don't have focus_new enabled, then it's going to get
444            raised to the top. Legacy begets legacy I guess?
445         */
446         client_raise(self);
447     }
448
449     /* this has to happen before we try focus the window, but we want it to
450        happen after the client's stacking has been determined or it looks bad
451     */
452     client_showhide(self);
453
454     /* use client_focus instead of client_activate cuz client_activate does
455        stuff like switch desktops etc and I'm not interested in all that when
456        a window maps since its not based on an action from the user like
457        clicking a window to activate it. so keep the new window out of the way
458        but do focus it. */
459     if (activate) {
460         /* if using focus_delay, stop the timer now so that focus doesn't
461            go moving on us */
462         event_halt_focus_delay();
463         client_focus(self);
464     }
465
466     /* client_activate does this but we aret using it so we have to do it
467        here as well */
468     if (screen_showing_desktop)
469         screen_show_desktop(FALSE);
470
471     /* add to client list/map */
472     client_list = g_list_append(client_list, self);
473     g_hash_table_insert(window_map, &self->window, self);
474
475     /* this has to happen after we're in the client_list */
476     if (STRUT_EXISTS(self->strut))
477         screen_update_areas();
478
479     /* update the list hints */
480     client_set_list();
481
482     ob_debug("Managed window 0x%lx (%s)\n", window, self->class);
483 }
484
485 void client_unmanage_all()
486 {
487     while (client_list != NULL)
488         client_unmanage(client_list->data);
489 }
490
491 void client_unmanage(ObClient *self)
492 {
493     guint j;
494     GSList *it;
495
496     ob_debug("Unmanaging window: %lx (%s) (%s)\n", self->window, self->class,
497              self->title ? self->title : "");
498
499     g_assert(self != NULL);
500
501     keyboard_grab_for_client(self, FALSE);
502     mouse_grab_for_client(self, FALSE);
503
504     /* potentially fix focusLast */
505     if (config_focus_last)
506         grab_pointer(TRUE, OB_CURSOR_NONE);
507
508     /* remove the window from our save set */
509     XChangeSaveSet(ob_display, self->window, SetModeDelete);
510
511     /* we dont want events no more */
512     XSelectInput(ob_display, self->window, NoEventMask);
513
514     frame_hide(self->frame);
515
516     client_list = g_list_remove(client_list, self);
517     stacking_remove(self);
518     g_hash_table_remove(window_map, &self->window);
519
520     /* update the focus lists */
521     focus_order_remove(self);
522
523     /* once the client is out of the list, update the struts to remove it's
524        influence */
525     if (STRUT_EXISTS(self->strut))
526         screen_update_areas();
527
528     for (it = client_destructors; it; it = g_slist_next(it)) {
529         Destructor *d = it->data;
530         d->func(self, d->data);
531     }
532         
533     if (focus_client == self) {
534         XEvent e;
535
536         /* focus the last focused window on the desktop, and ignore enter
537            events from the unmap so it doesnt mess with the focus */
538         while (XCheckTypedEvent(ob_display, EnterNotify, &e));
539         /* remove these flags so we don't end up getting focused in the
540            fallback! */
541         self->can_focus = FALSE;
542         self->focus_notify = FALSE;
543         self->modal = FALSE;
544         client_unfocus(self);
545     }
546
547     /* tell our parent(s) that we're gone */
548     if (self->transient_for == OB_TRAN_GROUP) { /* transient of group */
549         for (it = self->group->members; it; it = g_slist_next(it))
550             if (it->data != self)
551                 ((ObClient*)it->data)->transients =
552                     g_slist_remove(((ObClient*)it->data)->transients, self);
553     } else if (self->transient_for) {        /* transient of window */
554         self->transient_for->transients =
555             g_slist_remove(self->transient_for->transients, self);
556     }
557
558     /* tell our transients that we're gone */
559     for (it = self->transients; it; it = g_slist_next(it)) {
560         if (((ObClient*)it->data)->transient_for != OB_TRAN_GROUP) {
561             ((ObClient*)it->data)->transient_for = NULL;
562             client_calc_layer(it->data);
563         }
564     }
565
566     /* remove from its group */
567     if (self->group) {
568         group_remove(self->group, self);
569         self->group = NULL;
570     }
571
572     /* give the client its border back */
573     client_toggle_border(self, TRUE);
574
575     /* reparent the window out of the frame, and free the frame */
576     frame_release_client(self->frame, self);
577     self->frame = NULL;
578
579     /* restore the window's original geometry so it is not lost */
580     if (self->fullscreen)
581         XMoveResizeWindow(ob_display, self->window,
582                           self->pre_fullscreen_area.x,
583                           self->pre_fullscreen_area.y,
584                           self->pre_fullscreen_area.width,
585                           self->pre_fullscreen_area.height);
586     else if (self->max_horz || self->max_vert) {
587         Rect a = self->area;
588         if (self->max_horz) {
589             a.x = self->pre_max_area.x;
590             a.width = self->pre_max_area.width;
591         }
592         if (self->max_vert) {
593             a.y = self->pre_max_area.y;
594             a.height = self->pre_max_area.height;
595         }
596         XMoveResizeWindow(ob_display, self->window,
597                           a.x, a.y, a.width, a.height);
598     }
599      
600     if (ob_state() != OB_STATE_EXITING) {
601         /* these values should not be persisted across a window
602            unmapping/mapping */
603         PROP_ERASE(self->window, net_wm_desktop);
604         PROP_ERASE(self->window, net_wm_state);
605         PROP_ERASE(self->window, wm_state);
606     } else {
607         /* if we're left in an unmapped state, the client wont be mapped. this
608            is bad, since we will no longer be managing the window on restart */
609         XMapWindow(ob_display, self->window);
610     }
611
612
613     ob_debug("Unmanaged window 0x%lx\n", self->window);
614
615     /* free all data allocated in the client struct */
616     g_slist_free(self->transients);
617     for (j = 0; j < self->nicons; ++j)
618         g_free(self->icons[j].data);
619     if (self->nicons > 0)
620         g_free(self->icons);
621     g_free(self->title);
622     g_free(self->icon_title);
623     g_free(self->name);
624     g_free(self->class);
625     g_free(self->role);
626     g_free(self->sm_client_id);
627     g_free(self);
628      
629     /* update the list hints */
630     client_set_list();
631
632     if (config_focus_last)
633         grab_pointer(FALSE, OB_CURSOR_NONE);
634 }
635
636 static ObAppSettings *client_get_settings_state(ObClient *self)
637 {
638     ObAppSettings *settings = NULL;
639     GSList *it;
640
641     for (it = config_per_app_settings; it; it = g_slist_next(it)) {
642         ObAppSettings *app = it->data;
643         
644         if ((app->name && !app->class && !strcmp(app->name, self->name))
645             || (app->class && !app->name && !strcmp(app->class, self->class))
646             || (app->class && app->name && !strcmp(app->class, self->class)
647                 && !strcmp(app->name, self->name)))
648         {
649             ob_debug("Window matching: %s\n", app->name);
650             /* Match if no role was specified in the per app setting, or if the
651              * string matches the beginning of the role, since apps like to set
652              * the role to things like browser-window-23c4b2f */
653             if (!app->role
654                 || !strncmp(app->role, self->role, strlen(app->role)))
655             {
656                 /* use this one */
657                 settings = app;
658                 break;
659             }
660         }
661     }
662
663     if (settings) {
664         if (settings->shade != -1)
665             self->shaded = !!settings->shade;
666         if (settings->decor != -1)
667             self->undecorated = !settings->decor;
668         if (settings->iconic != -1)
669             self->iconic = !!settings->iconic;
670         if (settings->skip_pager != -1)
671             self->skip_pager = !!settings->skip_pager;
672         if (settings->skip_taskbar != -1)
673             self->skip_taskbar = !!settings->skip_taskbar;
674
675         if (settings->max_vert != -1)
676             self->max_vert = !!settings->max_vert;
677         if (settings->max_horz != -1)
678             self->max_vert = !!settings->max_horz;
679
680         if (settings->fullscreen != -1)
681             self->fullscreen = !!settings->fullscreen;
682
683         if (settings->desktop < screen_num_desktops
684             || settings->desktop == DESKTOP_ALL)
685             client_set_desktop(self, settings->desktop, TRUE);
686
687         if (settings->layer == -1) {
688             self->below = TRUE;
689             self->above = FALSE;
690         }
691         else if (settings->layer == 0) {
692             self->below = FALSE;
693             self->above = FALSE;
694         }
695         else if (settings->layer == 1) {
696             self->below = FALSE;
697             self->above = TRUE;
698         }
699     }
700     return settings;
701 }
702
703 static void client_restore_session_state(ObClient *self)
704 {
705     GList *it;
706
707     if (!(it = session_state_find(self)))
708         return;
709
710     self->session = it->data;
711
712     RECT_SET_POINT(self->area, self->session->x, self->session->y);
713     self->positioned = PPosition;
714     if (self->session->w > 0)
715         self->area.width = self->session->w;
716     if (self->session->h > 0)
717         self->area.height = self->session->h;
718     XResizeWindow(ob_display, self->window,
719                   self->area.width, self->area.height);
720
721     self->desktop = (self->session->desktop == DESKTOP_ALL ?
722                      self->session->desktop :
723                      MIN(screen_num_desktops - 1, self->session->desktop));
724     PROP_SET32(self->window, net_wm_desktop, cardinal, self->desktop);
725
726     self->shaded = self->session->shaded;
727     self->iconic = self->session->iconic;
728     self->skip_pager = self->session->skip_pager;
729     self->skip_taskbar = self->session->skip_taskbar;
730     self->fullscreen = self->session->fullscreen;
731     self->above = self->session->above;
732     self->below = self->session->below;
733     self->max_horz = self->session->max_horz;
734     self->max_vert = self->session->max_vert;
735 }
736
737 static void client_restore_session_stacking(ObClient *self)
738 {
739     GList *it;
740
741     if (!self->session) return;
742
743     it = g_list_find(session_saved_state, self->session);
744     for (it = g_list_previous(it); it; it = g_list_previous(it)) {
745         GList *cit;
746
747         for (cit = client_list; cit; cit = g_list_next(cit))
748             if (session_state_cmp(it->data, cit->data))
749                 break;
750         if (cit) {
751             client_calc_layer(self);
752             stacking_below(CLIENT_AS_WINDOW(self),
753                            CLIENT_AS_WINDOW(cit->data));
754             break;
755         }
756     }
757 }
758
759 void client_move_onscreen(ObClient *self, gboolean rude)
760 {
761     gint x = self->area.x;
762     gint y = self->area.y;
763     if (client_find_onscreen(self, &x, &y,
764                              self->frame->area.width,
765                              self->frame->area.height, rude)) {
766         client_move(self, x, y);
767     }
768 }
769
770 gboolean client_find_onscreen(ObClient *self, gint *x, gint *y, gint w, gint h,
771                               gboolean rude)
772 {
773     Rect *a;
774     gint ox = *x, oy = *y;
775
776     frame_client_gravity(self->frame, x, y); /* get where the frame
777                                                 would be */
778
779     /* XXX watch for xinerama dead areas */
780     /* This makes sure windows aren't entirely outside of the screen so you
781        can't see them at all.
782        It makes sure 10% of the window is on the screen at least. At don't let
783        it move itself off the top of the screen, which would hide the titlebar
784        on you. (The user can still do this if they want too, it's only limiting
785        the application.
786     */
787     if (client_normal(self)) {
788         a = screen_area(self->desktop);
789         if (!self->strut.right &&
790             *x + self->frame->area.width/10 >= a->x + a->width - 1)
791             *x = a->x + a->width - self->frame->area.width/10;
792         if (!self->strut.bottom &&
793             *y + self->frame->area.height/10 >= a->y + a->height - 1)
794             *y = a->y + a->height - self->frame->area.height/10;
795         if (!self->strut.left && *x + self->frame->area.width*9/10 - 1 < a->x)
796             *x = a->x - self->frame->area.width*9/10;
797         if (!self->strut.top && *y + self->frame->area.height*9/10 - 1 < a->y)
798             *y = a->y - self->frame->area.width*9/10;
799     }
800
801     /* This here doesn't let windows even a pixel outside the screen,
802      * when called from client_manage, programs placing themselves are
803      * forced completely onscreen, while things like
804      * xterm -geometry resolution-width/2 will work fine. Trying to
805      * place it completely offscreen will be handled in the above code.
806      * Sorry for this confused comment, i am tired. */
807     if (rude) {
808         /* avoid the xinerama monitor divide while we're at it,
809          * remember to fix the placement stuff to avoid it also and
810          * then remove this XXX */
811         a = screen_area_monitor(self->desktop, client_monitor(self));
812         /* dont let windows map into the strut unless they
813            are bigger than the available area */
814         if (w <= a->width) {
815             if (!self->strut.left && *x < a->x) *x = a->x;
816             if (!self->strut.right && *x + w > a->x + a->width)
817                 *x = a->x + a->width - w;
818         }
819         if (h <= a->height) {
820             if (!self->strut.top && *y < a->y) *y = a->y;
821             if (!self->strut.bottom && *y + h > a->y + a->height)
822                 *y = a->y + a->height - h;
823         }
824     }
825
826     frame_frame_gravity(self->frame, x, y); /* get where the client
827                                                should be */
828
829     return ox != *x || oy != *y;
830 }
831
832 static void client_toggle_border(ObClient *self, gboolean show)
833 {
834     /* adjust our idea of where the client is, based on its border. When the
835        border is removed, the client should now be considered to be in a
836        different position.
837        when re-adding the border to the client, the same operation needs to be
838        reversed. */
839     gint oldx = self->area.x, oldy = self->area.y;
840     gint x = oldx, y = oldy;
841     switch(self->gravity) {
842     default:
843     case NorthWestGravity:
844     case WestGravity:
845     case SouthWestGravity:
846         break;
847     case NorthEastGravity:
848     case EastGravity:
849     case SouthEastGravity:
850         if (show) x -= self->border_width * 2;
851         else      x += self->border_width * 2;
852         break;
853     case NorthGravity:
854     case SouthGravity:
855     case CenterGravity:
856     case ForgetGravity:
857     case StaticGravity:
858         if (show) x -= self->border_width;
859         else      x += self->border_width;
860         break;
861     }
862     switch(self->gravity) {
863     default:
864     case NorthWestGravity:
865     case NorthGravity:
866     case NorthEastGravity:
867         break;
868     case SouthWestGravity:
869     case SouthGravity:
870     case SouthEastGravity:
871         if (show) y -= self->border_width * 2;
872         else      y += self->border_width * 2;
873         break;
874     case WestGravity:
875     case EastGravity:
876     case CenterGravity:
877     case ForgetGravity:
878     case StaticGravity:
879         if (show) y -= self->border_width;
880         else      y += self->border_width;
881         break;
882     }
883     self->area.x = x;
884     self->area.y = y;
885
886     if (show) {
887         XSetWindowBorderWidth(ob_display, self->window, self->border_width);
888
889         /* move the client so it is back it the right spot _with_ its
890            border! */
891         if (x != oldx || y != oldy)
892             XMoveWindow(ob_display, self->window, x, y);
893     } else
894         XSetWindowBorderWidth(ob_display, self->window, 0);
895 }
896
897
898 static void client_get_all(ObClient *self)
899 {
900     client_get_area(self);
901     client_get_mwm_hints(self);
902
903     /* The transient hint is used to pick a type, but the type can also affect
904        transiency (dialogs are always made transients of their group if they
905        have one). This is Havoc's idea, but it is needed to make some apps
906        work right (eg tsclient). */
907     client_update_transient_for(self);
908     client_get_type(self);/* this can change the mwmhints for special cases */
909     client_get_state(self);
910     client_update_transient_for(self);
911
912     client_update_wmhints(self);
913     client_get_startup_id(self);
914     client_get_desktop(self);/* uses transient data/group/startup id if a
915                                 desktop is not specified */
916     client_get_shaped(self);
917
918     client_get_layer(self); /* if layer hasn't been specified, get it from
919                                other sources if possible */
920
921     {
922         /* a couple type-based defaults for new windows */
923
924         /* this makes sure that these windows appear on all desktops */
925         if (self->type == OB_CLIENT_TYPE_DESKTOP)
926             self->desktop = DESKTOP_ALL;
927     }
928
929     client_update_protocols(self);
930
931     client_get_gravity(self); /* get the attribute gravity */
932     client_update_normal_hints(self); /* this may override the attribute
933                                          gravity */
934
935     /* got the type, the mwmhints, the protocols, and the normal hints
936        (min/max sizes), so we're ready to set up the decorations/functions */
937     client_setup_decor_and_functions(self);
938   
939     client_update_title(self);
940     client_update_class(self);
941     client_update_sm_client_id(self);
942     client_update_strut(self);
943     client_update_icons(self);
944     client_update_user_time(self, FALSE);
945 }
946
947 static void client_get_startup_id(ObClient *self)
948 {
949     if (!(PROP_GETS(self->window, net_startup_id, utf8, &self->startup_id)))
950         if (self->group)
951             PROP_GETS(self->group->leader,
952                       net_startup_id, utf8, &self->startup_id);
953 }
954
955 static void client_get_area(ObClient *self)
956 {
957     XWindowAttributes wattrib;
958     Status ret;
959   
960     ret = XGetWindowAttributes(ob_display, self->window, &wattrib);
961     g_assert(ret != BadWindow);
962
963     RECT_SET(self->area, wattrib.x, wattrib.y, wattrib.width, wattrib.height);
964     self->border_width = wattrib.border_width;
965
966     ob_debug("client area: %d %d  %d %d\n", wattrib.x, wattrib.y,
967              wattrib.width, wattrib.height);
968 }
969
970 static void client_get_desktop(ObClient *self)
971 {
972     guint32 d = screen_num_desktops; /* an always-invalid value */
973
974     if (PROP_GET32(self->window, net_wm_desktop, cardinal, &d)) {
975         if (d >= screen_num_desktops && d != DESKTOP_ALL)
976             self->desktop = screen_num_desktops - 1;
977         else
978             self->desktop = d;
979     } else {
980         gboolean trdesk = FALSE;
981
982         if (self->transient_for) {
983             if (self->transient_for != OB_TRAN_GROUP) {
984                 self->desktop = self->transient_for->desktop;
985                 trdesk = TRUE;
986             } else {
987                 GSList *it;
988
989                 for (it = self->group->members; it; it = g_slist_next(it))
990                     if (it->data != self &&
991                         !((ObClient*)it->data)->transient_for) {
992                         self->desktop = ((ObClient*)it->data)->desktop;
993                         trdesk = TRUE;
994                         break;
995                     }
996             }
997         }
998         if (!trdesk) {
999             /* try get from the startup-notification protocol */
1000             if (sn_get_desktop(self->startup_id, &self->desktop)) {
1001                 if (self->desktop >= screen_num_desktops &&
1002                     self->desktop != DESKTOP_ALL)
1003                     self->desktop = screen_num_desktops - 1;
1004             } else
1005                 /* defaults to the current desktop */
1006                 self->desktop = screen_desktop;
1007         }
1008     }
1009     if (self->desktop != d) {
1010         /* set the desktop hint, to make sure that it always exists */
1011         PROP_SET32(self->window, net_wm_desktop, cardinal, self->desktop);
1012     }
1013 }
1014
1015 static void client_get_layer(ObClient *self)
1016 {
1017     if (!(self->above || self->below)) {
1018         if (self->group) {
1019             /* apply stuff from the group */
1020             GSList *it;
1021             gint layer = -2;
1022
1023             for (it = self->group->members; it; it = g_slist_next(it)) {
1024                 ObClient *c = it->data;
1025                 if (c != self && !client_search_transient(self, c) &&
1026                     client_normal(self) && client_normal(c))
1027                 {
1028                     layer = MAX(layer,
1029                                 (c->above ? 1 : (c->below ? -1 : 0)));
1030                 }
1031             }
1032             switch (layer) {
1033             case -1:
1034                 self->below = TRUE;
1035                 break;
1036             case -2:
1037             case 0:
1038                 break;
1039             case 1:
1040                 self->above = TRUE;
1041                 break;
1042             default:
1043                 g_assert_not_reached();
1044                 break;
1045             }
1046         }
1047     }
1048 }
1049
1050 static void client_get_state(ObClient *self)
1051 {
1052     guint32 *state;
1053     guint num;
1054   
1055     if (PROP_GETA32(self->window, net_wm_state, atom, &state, &num)) {
1056         gulong i;
1057         for (i = 0; i < num; ++i) {
1058             if (state[i] == prop_atoms.net_wm_state_modal)
1059                 self->modal = TRUE;
1060             else if (state[i] == prop_atoms.net_wm_state_shaded)
1061                 self->shaded = TRUE;
1062             else if (state[i] == prop_atoms.net_wm_state_hidden)
1063                 self->iconic = TRUE;
1064             else if (state[i] == prop_atoms.net_wm_state_skip_taskbar)
1065                 self->skip_taskbar = TRUE;
1066             else if (state[i] == prop_atoms.net_wm_state_skip_pager)
1067                 self->skip_pager = TRUE;
1068             else if (state[i] == prop_atoms.net_wm_state_fullscreen)
1069                 self->fullscreen = TRUE;
1070             else if (state[i] == prop_atoms.net_wm_state_maximized_vert)
1071                 self->max_vert = TRUE;
1072             else if (state[i] == prop_atoms.net_wm_state_maximized_horz)
1073                 self->max_horz = TRUE;
1074             else if (state[i] == prop_atoms.net_wm_state_above)
1075                 self->above = TRUE;
1076             else if (state[i] == prop_atoms.net_wm_state_below)
1077                 self->below = TRUE;
1078             else if (state[i] == prop_atoms.net_wm_state_demands_attention)
1079                 self->demands_attention = TRUE;
1080             else if (state[i] == prop_atoms.ob_wm_state_undecorated)
1081                 self->undecorated = TRUE;
1082         }
1083
1084         g_free(state);
1085     }
1086 }
1087
1088 static void client_get_shaped(ObClient *self)
1089 {
1090     self->shaped = FALSE;
1091 #ifdef   SHAPE
1092     if (extensions_shape) {
1093         gint foo;
1094         guint ufoo;
1095         gint s;
1096
1097         XShapeSelectInput(ob_display, self->window, ShapeNotifyMask);
1098
1099         XShapeQueryExtents(ob_display, self->window, &s, &foo,
1100                            &foo, &ufoo, &ufoo, &foo, &foo, &foo, &ufoo,
1101                            &ufoo);
1102         self->shaped = (s != 0);
1103     }
1104 #endif
1105 }
1106
1107 void client_update_transient_for(ObClient *self)
1108 {
1109     Window t = None;
1110     ObClient *target = NULL;
1111
1112     if (XGetTransientForHint(ob_display, self->window, &t)) {
1113         self->transient = TRUE;
1114         if (t != self->window) { /* cant be transient to itself! */
1115             target = g_hash_table_lookup(window_map, &t);
1116             /* if this happens then we need to check for it*/
1117             g_assert(target != self);
1118             if (target && !WINDOW_IS_CLIENT(target)) {
1119                 /* this can happen when a dialog is a child of
1120                    a dockapp, for example */
1121                 target = NULL;
1122             }
1123
1124             /* THIS IS SO ANNOYING ! ! ! ! Let me explain.... have a seat..
1125
1126                Setting the transient_for to Root is actually illegal, however
1127                applications from time have done this to specify transient for
1128                their group.
1129
1130                Now you can do that by being a TYPE_DIALOG and not setting
1131                the transient_for hint at all on your window. But people still
1132                use Root, and Kwin is very strange in this regard.
1133
1134                KWin 3.0 will not consider windows with transient_for set to
1135                Root as transient for their group *UNLESS* they are also modal.
1136                In that case, it will make them transient for the group. This
1137                leads to all sorts of weird behavior from KDE apps which are
1138                only tested in KWin. I'd like to follow their behavior just to
1139                make this work right with KDE stuff, but that seems wrong.
1140             */
1141             if (!target && self->group) {
1142                 /* not transient to a client, see if it is transient for a
1143                    group */
1144                 if (t == RootWindow(ob_display, ob_screen)) {
1145                     /* window is a transient for its group! */
1146                     target = OB_TRAN_GROUP;
1147                 }
1148             }
1149         }
1150     } else if (self->group) {
1151         if (self->type == OB_CLIENT_TYPE_DIALOG ||
1152             self->type == OB_CLIENT_TYPE_TOOLBAR ||
1153             self->type == OB_CLIENT_TYPE_MENU ||
1154             self->type == OB_CLIENT_TYPE_UTILITY)
1155         {
1156             self->transient = TRUE;
1157             target = OB_TRAN_GROUP;
1158         }
1159     } else
1160         self->transient = FALSE;
1161
1162     /* if anything has changed... */
1163     if (target != self->transient_for) {
1164         if (self->transient_for == OB_TRAN_GROUP) { /* transient of group */
1165             GSList *it;
1166
1167             /* remove from old parents */
1168             for (it = self->group->members; it; it = g_slist_next(it)) {
1169                 ObClient *c = it->data;
1170                 if (c != self && !c->transient_for)
1171                     c->transients = g_slist_remove(c->transients, self);
1172             }
1173         } else if (self->transient_for != NULL) { /* transient of window */
1174             /* remove from old parent */
1175             self->transient_for->transients =
1176                 g_slist_remove(self->transient_for->transients, self);
1177         }
1178         self->transient_for = target;
1179         if (self->transient_for == OB_TRAN_GROUP) { /* transient of group */
1180             GSList *it;
1181
1182             /* add to new parents */
1183             for (it = self->group->members; it; it = g_slist_next(it)) {
1184                 ObClient *c = it->data;
1185                 if (c != self && !c->transient_for)
1186                     c->transients = g_slist_append(c->transients, self);
1187             }
1188
1189             /* remove all transients which are in the group, that causes
1190                circlular pointer hell of doom */
1191             for (it = self->group->members; it; it = g_slist_next(it)) {
1192                 GSList *sit, *next;
1193                 for (sit = self->transients; sit; sit = next) {
1194                     next = g_slist_next(sit);
1195                     if (sit->data == it->data)
1196                         self->transients =
1197                             g_slist_delete_link(self->transients, sit);
1198                 }
1199             }
1200         } else if (self->transient_for != NULL) { /* transient of window */
1201             /* add to new parent */
1202             self->transient_for->transients =
1203                 g_slist_append(self->transient_for->transients, self);
1204         }
1205     }
1206 }
1207
1208 static void client_get_mwm_hints(ObClient *self)
1209 {
1210     guint num;
1211     guint32 *hints;
1212
1213     self->mwmhints.flags = 0; /* default to none */
1214
1215     if (PROP_GETA32(self->window, motif_wm_hints, motif_wm_hints,
1216                     &hints, &num)) {
1217         if (num >= OB_MWM_ELEMENTS) {
1218             self->mwmhints.flags = hints[0];
1219             self->mwmhints.functions = hints[1];
1220             self->mwmhints.decorations = hints[2];
1221         }
1222         g_free(hints);
1223     }
1224 }
1225
1226 void client_get_type(ObClient *self)
1227 {
1228     guint num, i;
1229     guint32 *val;
1230
1231     self->type = -1;
1232   
1233     if (PROP_GETA32(self->window, net_wm_window_type, atom, &val, &num)) {
1234         /* use the first value that we know about in the array */
1235         for (i = 0; i < num; ++i) {
1236             if (val[i] == prop_atoms.net_wm_window_type_desktop)
1237                 self->type = OB_CLIENT_TYPE_DESKTOP;
1238             else if (val[i] == prop_atoms.net_wm_window_type_dock)
1239                 self->type = OB_CLIENT_TYPE_DOCK;
1240             else if (val[i] == prop_atoms.net_wm_window_type_toolbar)
1241                 self->type = OB_CLIENT_TYPE_TOOLBAR;
1242             else if (val[i] == prop_atoms.net_wm_window_type_menu)
1243                 self->type = OB_CLIENT_TYPE_MENU;
1244             else if (val[i] == prop_atoms.net_wm_window_type_utility)
1245                 self->type = OB_CLIENT_TYPE_UTILITY;
1246             else if (val[i] == prop_atoms.net_wm_window_type_splash)
1247                 self->type = OB_CLIENT_TYPE_SPLASH;
1248             else if (val[i] == prop_atoms.net_wm_window_type_dialog)
1249                 self->type = OB_CLIENT_TYPE_DIALOG;
1250             else if (val[i] == prop_atoms.net_wm_window_type_normal)
1251                 self->type = OB_CLIENT_TYPE_NORMAL;
1252             else if (val[i] == prop_atoms.kde_net_wm_window_type_override) {
1253                 /* prevent this window from getting any decor or
1254                    functionality */
1255                 self->mwmhints.flags &= (OB_MWM_FLAG_FUNCTIONS |
1256                                          OB_MWM_FLAG_DECORATIONS);
1257                 self->mwmhints.decorations = 0;
1258                 self->mwmhints.functions = 0;
1259             }
1260             if (self->type != (ObClientType) -1)
1261                 break; /* grab the first legit type */
1262         }
1263         g_free(val);
1264     }
1265     
1266     if (self->type == (ObClientType) -1) {
1267         /*the window type hint was not set, which means we either classify
1268           ourself as a normal window or a dialog, depending on if we are a
1269           transient. */
1270         if (self->transient)
1271             self->type = OB_CLIENT_TYPE_DIALOG;
1272         else
1273             self->type = OB_CLIENT_TYPE_NORMAL;
1274     }
1275 }
1276
1277 void client_update_protocols(ObClient *self)
1278 {
1279     guint32 *proto;
1280     guint num_return, i;
1281
1282     self->focus_notify = FALSE;
1283     self->delete_window = FALSE;
1284
1285     if (PROP_GETA32(self->window, wm_protocols, atom, &proto, &num_return)) {
1286         for (i = 0; i < num_return; ++i) {
1287             if (proto[i] == prop_atoms.wm_delete_window) {
1288                 /* this means we can request the window to close */
1289                 self->delete_window = TRUE;
1290             } else if (proto[i] == prop_atoms.wm_take_focus)
1291                 /* if this protocol is requested, then the window will be
1292                    notified whenever we want it to receive focus */
1293                 self->focus_notify = TRUE;
1294         }
1295         g_free(proto);
1296     }
1297 }
1298
1299 static void client_get_gravity(ObClient *self)
1300 {
1301     XWindowAttributes wattrib;
1302     Status ret;
1303
1304     ret = XGetWindowAttributes(ob_display, self->window, &wattrib);
1305     g_assert(ret != BadWindow);
1306     self->gravity = wattrib.win_gravity;
1307 }
1308
1309 void client_update_normal_hints(ObClient *self)
1310 {
1311     XSizeHints size;
1312     glong ret;
1313     gint oldgravity = self->gravity;
1314
1315     /* defaults */
1316     self->min_ratio = 0.0f;
1317     self->max_ratio = 0.0f;
1318     SIZE_SET(self->size_inc, 1, 1);
1319     SIZE_SET(self->base_size, 0, 0);
1320     SIZE_SET(self->min_size, 0, 0);
1321     SIZE_SET(self->max_size, G_MAXINT, G_MAXINT);
1322
1323     /* get the hints from the window */
1324     if (XGetWMNormalHints(ob_display, self->window, &size, &ret)) {
1325         /* normal windows can't request placement! har har
1326         if (!client_normal(self))
1327         */
1328         self->positioned = (size.flags & (PPosition|USPosition));
1329
1330         if (size.flags & PWinGravity) {
1331             self->gravity = size.win_gravity;
1332       
1333             /* if the client has a frame, i.e. has already been mapped and
1334                is changing its gravity */
1335             if (self->frame && self->gravity != oldgravity) {
1336                 /* move our idea of the client's position based on its new
1337                    gravity */
1338                 self->area.x = self->frame->area.x;
1339                 self->area.y = self->frame->area.y;
1340                 frame_frame_gravity(self->frame, &self->area.x, &self->area.y);
1341             }
1342         }
1343
1344         if (size.flags & PAspect) {
1345             if (size.min_aspect.y)
1346                 self->min_ratio =
1347                     (gfloat) size.min_aspect.x / size.min_aspect.y;
1348             if (size.max_aspect.y)
1349                 self->max_ratio =
1350                     (gfloat) size.max_aspect.x / size.max_aspect.y;
1351         }
1352
1353         if (size.flags & PMinSize)
1354             SIZE_SET(self->min_size, size.min_width, size.min_height);
1355     
1356         if (size.flags & PMaxSize)
1357             SIZE_SET(self->max_size, size.max_width, size.max_height);
1358     
1359         if (size.flags & PBaseSize)
1360             SIZE_SET(self->base_size, size.base_width, size.base_height);
1361     
1362         if (size.flags & PResizeInc && size.width_inc && size.height_inc)
1363             SIZE_SET(self->size_inc, size.width_inc, size.height_inc);
1364     }
1365 }
1366
1367 void client_setup_decor_and_functions(ObClient *self)
1368 {
1369     /* start with everything (cept fullscreen) */
1370     self->decorations =
1371         (OB_FRAME_DECOR_TITLEBAR |
1372          OB_FRAME_DECOR_HANDLE |
1373          OB_FRAME_DECOR_GRIPS |
1374          OB_FRAME_DECOR_BORDER |
1375          OB_FRAME_DECOR_ICON |
1376          OB_FRAME_DECOR_ALLDESKTOPS |
1377          OB_FRAME_DECOR_ICONIFY |
1378          OB_FRAME_DECOR_MAXIMIZE |
1379          OB_FRAME_DECOR_SHADE |
1380          OB_FRAME_DECOR_CLOSE);
1381     self->functions =
1382         (OB_CLIENT_FUNC_RESIZE |
1383          OB_CLIENT_FUNC_MOVE |
1384          OB_CLIENT_FUNC_ICONIFY |
1385          OB_CLIENT_FUNC_MAXIMIZE |
1386          OB_CLIENT_FUNC_SHADE |
1387          OB_CLIENT_FUNC_CLOSE);
1388
1389     if (!(self->min_size.width < self->max_size.width ||
1390           self->min_size.height < self->max_size.height))
1391         self->functions &= ~OB_CLIENT_FUNC_RESIZE;
1392
1393     switch (self->type) {
1394     case OB_CLIENT_TYPE_NORMAL:
1395         /* normal windows retain all of the possible decorations and
1396            functionality, and are the only windows that you can fullscreen */
1397         self->functions |= OB_CLIENT_FUNC_FULLSCREEN;
1398         break;
1399
1400     case OB_CLIENT_TYPE_DIALOG:
1401     case OB_CLIENT_TYPE_UTILITY:
1402         /* these windows cannot be maximized */
1403         self->functions &= ~OB_CLIENT_FUNC_MAXIMIZE;
1404         break;
1405
1406     case OB_CLIENT_TYPE_MENU:
1407     case OB_CLIENT_TYPE_TOOLBAR:
1408         /* these windows get less functionality */
1409         self->functions &= ~(OB_CLIENT_FUNC_ICONIFY | OB_CLIENT_FUNC_RESIZE);
1410         break;
1411
1412     case OB_CLIENT_TYPE_DESKTOP:
1413     case OB_CLIENT_TYPE_DOCK:
1414     case OB_CLIENT_TYPE_SPLASH:
1415         /* none of these windows are manipulated by the window manager */
1416         self->decorations = 0;
1417         self->functions = 0;
1418         break;
1419     }
1420
1421     /* Mwm Hints are applied subtractively to what has already been chosen for
1422        decor and functionality */
1423     if (self->mwmhints.flags & OB_MWM_FLAG_DECORATIONS) {
1424         if (! (self->mwmhints.decorations & OB_MWM_DECOR_ALL)) {
1425             if (! ((self->mwmhints.decorations & OB_MWM_DECOR_HANDLE) ||
1426                    (self->mwmhints.decorations & OB_MWM_DECOR_TITLE)))
1427             {
1428                 /* if the mwm hints request no handle or title, then all
1429                    decorations are disabled, but keep the border if that's
1430                    specified */
1431                 if (self->mwmhints.decorations & OB_MWM_DECOR_BORDER)
1432                     self->decorations = OB_FRAME_DECOR_BORDER;
1433                 else
1434                     self->decorations = 0;
1435             }
1436         }
1437     }
1438
1439     if (self->mwmhints.flags & OB_MWM_FLAG_FUNCTIONS) {
1440         if (! (self->mwmhints.functions & OB_MWM_FUNC_ALL)) {
1441             if (! (self->mwmhints.functions & OB_MWM_FUNC_RESIZE))
1442                 self->functions &= ~OB_CLIENT_FUNC_RESIZE;
1443             if (! (self->mwmhints.functions & OB_MWM_FUNC_MOVE))
1444                 self->functions &= ~OB_CLIENT_FUNC_MOVE;
1445             /* dont let mwm hints kill any buttons
1446                if (! (self->mwmhints.functions & OB_MWM_FUNC_ICONIFY))
1447                self->functions &= ~OB_CLIENT_FUNC_ICONIFY;
1448                if (! (self->mwmhints.functions & OB_MWM_FUNC_MAXIMIZE))
1449                self->functions &= ~OB_CLIENT_FUNC_MAXIMIZE;
1450             */
1451             /* dont let mwm hints kill the close button
1452                if (! (self->mwmhints.functions & MwmFunc_Close))
1453                self->functions &= ~OB_CLIENT_FUNC_CLOSE; */
1454         }
1455     }
1456
1457     if (!(self->functions & OB_CLIENT_FUNC_SHADE))
1458         self->decorations &= ~OB_FRAME_DECOR_SHADE;
1459     if (!(self->functions & OB_CLIENT_FUNC_ICONIFY))
1460         self->decorations &= ~OB_FRAME_DECOR_ICONIFY;
1461     if (!(self->functions & OB_CLIENT_FUNC_RESIZE))
1462         self->decorations &= ~OB_FRAME_DECOR_GRIPS;
1463
1464     /* can't maximize without moving/resizing */
1465     if (!((self->functions & OB_CLIENT_FUNC_MAXIMIZE) &&
1466           (self->functions & OB_CLIENT_FUNC_MOVE) &&
1467           (self->functions & OB_CLIENT_FUNC_RESIZE))) {
1468         self->functions &= ~OB_CLIENT_FUNC_MAXIMIZE;
1469         self->decorations &= ~OB_FRAME_DECOR_MAXIMIZE;
1470     }
1471
1472     /* kill the handle on fully maxed windows */
1473     if (self->max_vert && self->max_horz)
1474         self->decorations &= ~OB_FRAME_DECOR_HANDLE;
1475
1476     /* finally, the user can have requested no decorations, which overrides
1477        everything (but doesnt give it a border if it doesnt have one) */
1478     if (self->undecorated) {
1479         if (config_theme_keepborder)
1480             self->decorations &= OB_FRAME_DECOR_BORDER;
1481         else
1482             self->decorations = 0;
1483     }
1484
1485     /* if we don't have a titlebar, then we cannot shade! */
1486     if (!(self->decorations & OB_FRAME_DECOR_TITLEBAR))
1487         self->functions &= ~OB_CLIENT_FUNC_SHADE;
1488
1489     /* now we need to check against rules for the client's current state */
1490     if (self->fullscreen) {
1491         self->functions &= (OB_CLIENT_FUNC_CLOSE |
1492                             OB_CLIENT_FUNC_FULLSCREEN |
1493                             OB_CLIENT_FUNC_ICONIFY);
1494         self->decorations = 0;
1495     }
1496
1497     client_change_allowed_actions(self);
1498
1499     if (self->frame) {
1500         /* adjust the client's decorations, etc. */
1501         client_reconfigure(self);
1502     }
1503 }
1504
1505 static void client_change_allowed_actions(ObClient *self)
1506 {
1507     gulong actions[9];
1508     gint num = 0;
1509
1510     /* desktop windows are kept on all desktops */
1511     if (self->type != OB_CLIENT_TYPE_DESKTOP)
1512         actions[num++] = prop_atoms.net_wm_action_change_desktop;
1513
1514     if (self->functions & OB_CLIENT_FUNC_SHADE)
1515         actions[num++] = prop_atoms.net_wm_action_shade;
1516     if (self->functions & OB_CLIENT_FUNC_CLOSE)
1517         actions[num++] = prop_atoms.net_wm_action_close;
1518     if (self->functions & OB_CLIENT_FUNC_MOVE)
1519         actions[num++] = prop_atoms.net_wm_action_move;
1520     if (self->functions & OB_CLIENT_FUNC_ICONIFY)
1521         actions[num++] = prop_atoms.net_wm_action_minimize;
1522     if (self->functions & OB_CLIENT_FUNC_RESIZE)
1523         actions[num++] = prop_atoms.net_wm_action_resize;
1524     if (self->functions & OB_CLIENT_FUNC_FULLSCREEN)
1525         actions[num++] = prop_atoms.net_wm_action_fullscreen;
1526     if (self->functions & OB_CLIENT_FUNC_MAXIMIZE) {
1527         actions[num++] = prop_atoms.net_wm_action_maximize_horz;
1528         actions[num++] = prop_atoms.net_wm_action_maximize_vert;
1529     }
1530
1531     PROP_SETA32(self->window, net_wm_allowed_actions, atom, actions, num);
1532
1533     /* make sure the window isn't breaking any rules now */
1534
1535     if (!(self->functions & OB_CLIENT_FUNC_SHADE) && self->shaded) {
1536         if (self->frame) client_shade(self, FALSE);
1537         else self->shaded = FALSE;
1538     }
1539     if (!(self->functions & OB_CLIENT_FUNC_ICONIFY) && self->iconic) {
1540         if (self->frame) client_iconify(self, FALSE, TRUE);
1541         else self->iconic = FALSE;
1542     }
1543     if (!(self->functions & OB_CLIENT_FUNC_FULLSCREEN) && self->fullscreen) {
1544         if (self->frame) client_fullscreen(self, FALSE);
1545         else self->fullscreen = FALSE;
1546     }
1547     if (!(self->functions & OB_CLIENT_FUNC_MAXIMIZE) && (self->max_horz ||
1548                                                          self->max_vert)) {
1549         if (self->frame) client_maximize(self, FALSE, 0);
1550         else self->max_vert = self->max_horz = FALSE;
1551     }
1552 }
1553
1554 void client_reconfigure(ObClient *self)
1555 {
1556     /* by making this pass FALSE for user, we avoid the emacs event storm where
1557        every configurenotify causes an update in its normal hints, i think this
1558        is generally what we want anyways... */
1559     client_configure(self, OB_CORNER_TOPLEFT, self->area.x, self->area.y,
1560                      self->area.width, self->area.height, FALSE, TRUE);
1561 }
1562
1563 void client_update_wmhints(ObClient *self)
1564 {
1565     XWMHints *hints;
1566     GSList *it;
1567
1568     /* assume a window takes input if it doesnt specify */
1569     self->can_focus = TRUE;
1570   
1571     if ((hints = XGetWMHints(ob_display, self->window)) != NULL) {
1572         if (hints->flags & InputHint)
1573             self->can_focus = hints->input;
1574
1575         /* only do this when first managing the window *AND* when we aren't
1576            starting up! */
1577         if (ob_state() != OB_STATE_STARTING && self->frame == NULL)
1578             if (hints->flags & StateHint)
1579                 self->iconic = hints->initial_state == IconicState;
1580
1581         if (!(hints->flags & WindowGroupHint))
1582             hints->window_group = None;
1583
1584         /* did the group state change? */
1585         if (hints->window_group !=
1586             (self->group ? self->group->leader : None)) {
1587             /* remove from the old group if there was one */
1588             if (self->group != NULL) {
1589                 /* remove transients of the group */
1590                 for (it = self->group->members; it; it = g_slist_next(it))
1591                     self->transients = g_slist_remove(self->transients,
1592                                                       it->data);
1593
1594                 /* remove myself from parents in the group */
1595                 if (self->transient_for == OB_TRAN_GROUP) {
1596                     for (it = self->group->members; it;
1597                          it = g_slist_next(it))
1598                     {
1599                         ObClient *c = it->data;
1600
1601                         if (c != self && !c->transient_for)
1602                             c->transients = g_slist_remove(c->transients,
1603                                                            self);
1604                     }
1605                 }
1606
1607                 group_remove(self->group, self);
1608                 self->group = NULL;
1609             }
1610             if (hints->window_group != None) {
1611                 self->group = group_add(hints->window_group, self);
1612
1613                 /* i can only have transients from the group if i am not
1614                    transient myself */
1615                 if (!self->transient_for) {
1616                     /* add other transients of the group that are already
1617                        set up */
1618                     for (it = self->group->members; it;
1619                          it = g_slist_next(it))
1620                     {
1621                         ObClient *c = it->data;
1622                         if (c != self && c->transient_for == OB_TRAN_GROUP)
1623                             self->transients =
1624                                 g_slist_append(self->transients, c);
1625                     }
1626                 }
1627             }
1628
1629             /* because the self->transient flag wont change from this call,
1630                we don't need to update the window's type and such, only its
1631                transient_for, and the transients lists of other windows in
1632                the group may be affected */
1633             client_update_transient_for(self);
1634         }
1635
1636         /* the WM_HINTS can contain an icon */
1637         client_update_icons(self);
1638
1639         XFree(hints);
1640     }
1641 }
1642
1643 void client_update_title(ObClient *self)
1644 {
1645     GList *it;
1646     guint32 nums;
1647     guint i;
1648     gchar *data = NULL;
1649     gboolean read_title;
1650     gchar *old_title;
1651
1652     old_title = self->title;
1653      
1654     /* try netwm */
1655     if (!PROP_GETS(self->window, net_wm_name, utf8, &data)) {
1656         /* try old x stuff */
1657         if (!(PROP_GETS(self->window, wm_name, locale, &data)
1658               || PROP_GETS(self->window, wm_name, utf8, &data))) {
1659             // http://developer.gnome.org/projects/gup/hig/draft_hig_new/windows-alert.html
1660             if (self->transient) {
1661                 data = g_strdup("");
1662                 goto no_number;
1663             } else
1664                 data = g_strdup("Unnamed Window");
1665         }
1666     }
1667
1668     if (config_title_number) {
1669
1670         /* did the title change? then reset the title_count */
1671         if (old_title && 0 != strncmp(old_title, data, strlen(data)))
1672             self->title_count = 1;
1673
1674         /* look for duplicates and append a number */
1675         nums = 0;
1676         for (it = client_list; it; it = g_list_next(it))
1677             if (it->data != self) {
1678                 ObClient *c = it->data;
1679
1680                 if (c->title_count == 1) {
1681                     if (!strcmp(c->title, data))
1682                         nums |= 1 << c->title_count;
1683                 } else {
1684                     size_t len;
1685                     gchar *end;
1686
1687                     /* find the beginning of our " - [%u]", this relies on
1688                      that syntax being used */
1689                     end = strrchr(c->title, '-') - 1; 
1690                     len = end - c->title;
1691                     if (!strncmp(c->title, data, len))
1692                         nums |= 1 << c->title_count;
1693                 }
1694             }
1695         /* find first free number */
1696         for (i = 1; i <= 32; ++i)
1697             if (!(nums & (1 << i))) {
1698                 if (self->title_count == 1 || i == 1)
1699                     self->title_count = i;
1700                 break;
1701             }
1702         /* dont display the number for the first window */
1703         if (self->title_count > 1) {
1704             gchar *ndata;
1705             ndata = g_strdup_printf("%s - [%u]", data, self->title_count);
1706             g_free(data);
1707             data = ndata;
1708         }
1709     } else
1710         self->title_count = 1;
1711
1712 no_number:
1713     PROP_SETS(self->window, net_wm_visible_name, data);
1714     self->title = data;
1715
1716     if (self->frame)
1717         frame_adjust_title(self->frame);
1718
1719     g_free(old_title);
1720
1721     /* update the icon title */
1722     data = NULL;
1723     g_free(self->icon_title);
1724
1725     read_title = TRUE;
1726     /* try netwm */
1727     if (!PROP_GETS(self->window, net_wm_icon_name, utf8, &data))
1728         /* try old x stuff */
1729         if (!(PROP_GETS(self->window, wm_icon_name, locale, &data)
1730               || PROP_GETS(self->window, wm_icon_name, utf8, &data))) {
1731             data = g_strdup(self->title);
1732             read_title = FALSE;
1733         }
1734
1735     /* append the title count, dont display the number for the first window.
1736      * We don't need to check for config_title_number here since title_count
1737      * is not set above 1 then. */
1738     if (read_title && self->title_count > 1) {
1739         gchar *newdata;
1740         newdata = g_strdup_printf("%s - [%u]", data, self->title_count);
1741         g_free(data);
1742         data = newdata;
1743     }
1744
1745     PROP_SETS(self->window, net_wm_visible_icon_name, data);
1746
1747     self->icon_title = data;
1748 }
1749
1750 void client_update_class(ObClient *self)
1751 {
1752     gchar **data;
1753     gchar *s;
1754
1755     if (self->name) g_free(self->name);
1756     if (self->class) g_free(self->class);
1757     if (self->role) g_free(self->role);
1758
1759     self->name = self->class = self->role = NULL;
1760
1761     if (PROP_GETSS(self->window, wm_class, locale, &data)) {
1762         if (data[0]) {
1763             self->name = g_strdup(data[0]);
1764             if (data[1])
1765                 self->class = g_strdup(data[1]);
1766         }
1767         g_strfreev(data);     
1768     }
1769
1770     if (PROP_GETS(self->window, wm_window_role, locale, &s))
1771         self->role = s;
1772
1773     if (self->name == NULL) self->name = g_strdup("");
1774     if (self->class == NULL) self->class = g_strdup("");
1775     if (self->role == NULL) self->role = g_strdup("");
1776 }
1777
1778 void client_update_strut(ObClient *self)
1779 {
1780     guint num;
1781     guint32 *data;
1782     gboolean got = FALSE;
1783     StrutPartial strut;
1784
1785     if (PROP_GETA32(self->window, net_wm_strut_partial, cardinal,
1786                     &data, &num)) {
1787         if (num == 12) {
1788             got = TRUE;
1789             STRUT_PARTIAL_SET(strut,
1790                               data[0], data[2], data[1], data[3],
1791                               data[4], data[5], data[8], data[9],
1792                               data[6], data[7], data[10], data[11]);
1793         }
1794         g_free(data);
1795     }
1796
1797     if (!got &&
1798         PROP_GETA32(self->window, net_wm_strut, cardinal, &data, &num)) {
1799         if (num == 4) {
1800             const Rect *a;
1801
1802             got = TRUE;
1803
1804             /* use the screen's width/height */
1805             a = screen_physical_area();
1806
1807             STRUT_PARTIAL_SET(strut,
1808                               data[0], data[2], data[1], data[3],
1809                               a->y, a->y + a->height - 1,
1810                               a->x, a->x + a->width - 1,
1811                               a->y, a->y + a->height - 1,
1812                               a->x, a->x + a->width - 1);
1813         }
1814         g_free(data);
1815     }
1816
1817     if (!got)
1818         STRUT_PARTIAL_SET(strut, 0, 0, 0, 0,
1819                           0, 0, 0, 0, 0, 0, 0, 0);
1820
1821     if (!STRUT_EQUAL(strut, self->strut)) {
1822         self->strut = strut;
1823
1824         /* updating here is pointless while we're being mapped cuz we're not in
1825            the client list yet */
1826         if (self->frame)
1827             screen_update_areas();
1828     }
1829 }
1830
1831 void client_update_icons(ObClient *self)
1832 {
1833     guint num;
1834     guint32 *data;
1835     guint w, h, i, j;
1836
1837     for (i = 0; i < self->nicons; ++i)
1838         g_free(self->icons[i].data);
1839     if (self->nicons > 0)
1840         g_free(self->icons);
1841     self->nicons = 0;
1842
1843     if (PROP_GETA32(self->window, net_wm_icon, cardinal, &data, &num)) {
1844         /* figure out how many valid icons are in here */
1845         i = 0;
1846         while (num - i > 2) {
1847             w = data[i++];
1848             h = data[i++];
1849             i += w * h;
1850             if (i > num || w*h == 0) break;
1851             ++self->nicons;
1852         }
1853
1854         self->icons = g_new(ObClientIcon, self->nicons);
1855     
1856         /* store the icons */
1857         i = 0;
1858         for (j = 0; j < self->nicons; ++j) {
1859             guint x, y, t;
1860
1861             w = self->icons[j].width = data[i++];
1862             h = self->icons[j].height = data[i++];
1863
1864             if (w*h == 0) continue;
1865
1866             self->icons[j].data = g_new(RrPixel32, w * h);
1867             for (x = 0, y = 0, t = 0; t < w * h; ++t, ++x, ++i) {
1868                 if (x >= w) {
1869                     x = 0;
1870                     ++y;
1871                 }
1872                 self->icons[j].data[t] =
1873                     (((data[i] >> 24) & 0xff) << RrDefaultAlphaOffset) +
1874                     (((data[i] >> 16) & 0xff) << RrDefaultRedOffset) +
1875                     (((data[i] >> 8) & 0xff) << RrDefaultGreenOffset) +
1876                     (((data[i] >> 0) & 0xff) << RrDefaultBlueOffset);
1877             }
1878             g_assert(i <= num);
1879         }
1880
1881         g_free(data);
1882     } else {
1883         XWMHints *hints;
1884
1885         if ((hints = XGetWMHints(ob_display, self->window))) {
1886             if (hints->flags & IconPixmapHint) {
1887                 self->nicons++;
1888                 self->icons = g_new(ObClientIcon, self->nicons);
1889                 xerror_set_ignore(TRUE);
1890                 if (!RrPixmapToRGBA(ob_rr_inst,
1891                                     hints->icon_pixmap,
1892                                     (hints->flags & IconMaskHint ?
1893                                      hints->icon_mask : None),
1894                                     &self->icons[self->nicons-1].width,
1895                                     &self->icons[self->nicons-1].height,
1896                                     &self->icons[self->nicons-1].data)){
1897                     g_free(&self->icons[self->nicons-1]);
1898                     self->nicons--;
1899                 }
1900                 xerror_set_ignore(FALSE);
1901             }
1902             XFree(hints);
1903         }
1904     }
1905
1906     if (self->frame)
1907         frame_adjust_icon(self->frame);
1908 }
1909
1910 void client_update_user_time(ObClient *self, gboolean new_event)
1911 {
1912     guint32 time;
1913
1914     if (PROP_GET32(self->window, net_wm_user_time, cardinal, &time)) {
1915         self->user_time = time;
1916         /* we set this every time, not just when it grows, because in practice
1917            sometimes time goes backwards! (ntpdate.. yay....) so.. if it goes
1918            backward we don't want all windows to stop focusing. we'll just
1919            assume noone is setting times older than the last one, cuz that
1920            would be pretty stupid anyways
1921            However! This is called when a window is mapped to get its user time
1922            but it's an old number, it's not changing it from new user
1923            interaction, so in that case, don't change the last user time.
1924         */
1925         if (new_event)
1926             client_last_user_time = time;
1927
1928         /*ob_debug("window 0x%x user time %u\n", self->window, time);*/
1929     }
1930 }
1931
1932 static void client_change_wm_state(ObClient *self)
1933 {
1934     gulong state[2];
1935     glong old;
1936
1937     old = self->wmstate;
1938
1939     if (self->shaded || self->iconic || !self->frame->visible)
1940         self->wmstate = IconicState;
1941     else
1942         self->wmstate = NormalState;
1943
1944     if (old != self->wmstate) {
1945         PROP_MSG(self->window, kde_wm_change_state,
1946                  self->wmstate, 1, 0, 0);
1947
1948         state[0] = self->wmstate;
1949         state[1] = None;
1950         PROP_SETA32(self->window, wm_state, wm_state, state, 2);
1951     }
1952 }
1953
1954 static void client_change_state(ObClient *self)
1955 {
1956     gulong netstate[11];
1957     guint num;
1958
1959     num = 0;
1960     if (self->modal)
1961         netstate[num++] = prop_atoms.net_wm_state_modal;
1962     if (self->shaded)
1963         netstate[num++] = prop_atoms.net_wm_state_shaded;
1964     if (self->iconic)
1965         netstate[num++] = prop_atoms.net_wm_state_hidden;
1966     if (self->skip_taskbar)
1967         netstate[num++] = prop_atoms.net_wm_state_skip_taskbar;
1968     if (self->skip_pager)
1969         netstate[num++] = prop_atoms.net_wm_state_skip_pager;
1970     if (self->fullscreen)
1971         netstate[num++] = prop_atoms.net_wm_state_fullscreen;
1972     if (self->max_vert)
1973         netstate[num++] = prop_atoms.net_wm_state_maximized_vert;
1974     if (self->max_horz)
1975         netstate[num++] = prop_atoms.net_wm_state_maximized_horz;
1976     if (self->above)
1977         netstate[num++] = prop_atoms.net_wm_state_above;
1978     if (self->below)
1979         netstate[num++] = prop_atoms.net_wm_state_below;
1980     if (self->demands_attention)
1981         netstate[num++] = prop_atoms.net_wm_state_demands_attention;
1982     if (self->undecorated)
1983         netstate[num++] = prop_atoms.ob_wm_state_undecorated;
1984     PROP_SETA32(self->window, net_wm_state, atom, netstate, num);
1985
1986     if (self->frame)
1987         frame_adjust_state(self->frame);
1988 }
1989
1990 ObClient *client_search_focus_tree(ObClient *self)
1991 {
1992     GSList *it;
1993     ObClient *ret;
1994
1995     for (it = self->transients; it; it = g_slist_next(it)) {
1996         if (client_focused(it->data)) return it->data;
1997         if ((ret = client_search_focus_tree(it->data))) return ret;
1998     }
1999     return NULL;
2000 }
2001
2002 ObClient *client_search_focus_tree_full(ObClient *self)
2003 {
2004     if (self->transient_for) {
2005         if (self->transient_for != OB_TRAN_GROUP) {
2006             return client_search_focus_tree_full(self->transient_for);
2007         } else {
2008             GSList *it;
2009             gboolean recursed = FALSE;
2010         
2011             for (it = self->group->members; it; it = g_slist_next(it))
2012                 if (!((ObClient*)it->data)->transient_for) {
2013                     ObClient *c;
2014                     if ((c = client_search_focus_tree_full(it->data)))
2015                         return c;
2016                     recursed = TRUE;
2017                 }
2018             if (recursed)
2019                 return NULL;
2020         }
2021     }
2022
2023     /* this function checks the whole tree, the client_search_focus_tree~
2024        does not, so we need to check this window */
2025     if (client_focused(self))
2026         return self;
2027     return client_search_focus_tree(self);
2028 }
2029
2030 static ObStackingLayer calc_layer(ObClient *self)
2031 {
2032     ObStackingLayer l;
2033
2034     if (self->fullscreen &&
2035         (client_focused(self) || client_search_focus_tree(self)))
2036         l = OB_STACKING_LAYER_FULLSCREEN;
2037     else if (self->type == OB_CLIENT_TYPE_DESKTOP)
2038         l = OB_STACKING_LAYER_DESKTOP;
2039     else if (self->type == OB_CLIENT_TYPE_DOCK) {
2040         if (self->below) l = OB_STACKING_LAYER_NORMAL;
2041         else l = OB_STACKING_LAYER_ABOVE;
2042     }
2043     else if (self->above) l = OB_STACKING_LAYER_ABOVE;
2044     else if (self->below) l = OB_STACKING_LAYER_BELOW;
2045     else l = OB_STACKING_LAYER_NORMAL;
2046
2047     return l;
2048 }
2049
2050 static void client_calc_layer_recursive(ObClient *self, ObClient *orig,
2051                                         ObStackingLayer min, gboolean raised)
2052 {
2053     ObStackingLayer old, own;
2054     GSList *it;
2055
2056     old = self->layer;
2057     own = calc_layer(self);
2058     self->layer = MAX(own, min);
2059
2060     for (it = self->transients; it; it = g_slist_next(it))
2061         client_calc_layer_recursive(it->data, orig,
2062                                     self->layer,
2063                                     raised ? raised : self->layer != old);
2064
2065     if (!raised && self->layer != old)
2066         if (orig->frame) { /* only restack if the original window is managed */
2067             stacking_remove(CLIENT_AS_WINDOW(self));
2068             stacking_add(CLIENT_AS_WINDOW(self));
2069         }
2070 }
2071
2072 void client_calc_layer(ObClient *self)
2073 {
2074     ObClient *orig;
2075     GSList *it;
2076
2077     orig = self;
2078
2079     /* transients take on the layer of their parents */
2080     it = client_search_all_top_parents(self);
2081
2082     for (; it; it = g_slist_next(it))
2083         client_calc_layer_recursive(it->data, orig, 0, FALSE);
2084 }
2085
2086 gboolean client_should_show(ObClient *self)
2087 {
2088     if (self->iconic)
2089         return FALSE;
2090     if (client_normal(self) && screen_showing_desktop)
2091         return FALSE;
2092     /*
2093     if (self->transient_for) {
2094         if (self->transient_for != OB_TRAN_GROUP)
2095             return client_should_show(self->transient_for);
2096         else {
2097             GSList *it;
2098
2099             for (it = self->group->members; it; it = g_slist_next(it)) {
2100                 ObClient *c = it->data;
2101                 if (c != self && !c->transient_for) {
2102                     if (client_should_show(c))
2103                         return TRUE;
2104                 }
2105             }
2106         }
2107     }
2108     */
2109     if (self->desktop == screen_desktop || self->desktop == DESKTOP_ALL)
2110         return TRUE;
2111     
2112     return FALSE;
2113 }
2114
2115 void client_showhide(ObClient *self)
2116 {
2117
2118     if (client_should_show(self)) {
2119         frame_show(self->frame);
2120     }
2121     else {
2122         frame_hide(self->frame);
2123
2124         /* Fall back focus since we're disappearing */
2125         if (focus_client == self)
2126             client_unfocus(self);
2127     }
2128
2129     /* According to the ICCCM (sec 4.1.3.1) when a window is not visible, it
2130        needs to be in IconicState. This includes when it is on another
2131        desktop!
2132     */
2133     client_change_wm_state(self);
2134 }
2135
2136 gboolean client_normal(ObClient *self) {
2137     return ! (self->type == OB_CLIENT_TYPE_DESKTOP ||
2138               self->type == OB_CLIENT_TYPE_DOCK ||
2139               self->type == OB_CLIENT_TYPE_SPLASH);
2140 }
2141
2142 static void client_apply_startup_state(ObClient *self, gint x, gint y)
2143 {
2144     gboolean pos = FALSE; /* has the window's position been configured? */
2145     gint ox, oy;
2146
2147     /* save the position, and set self->area for these to use */
2148     ox = self->area.x;
2149     oy = self->area.y;
2150     self->area.x = x;
2151     self->area.y = y;
2152
2153     /* these are in a carefully crafted order.. */
2154
2155     if (self->iconic) {
2156         self->iconic = FALSE;
2157         client_iconify(self, TRUE, FALSE);
2158     }
2159     if (self->fullscreen) {
2160         self->fullscreen = FALSE;
2161         client_fullscreen(self, TRUE);
2162         pos = TRUE;
2163     }
2164     if (self->undecorated) {
2165         self->undecorated = FALSE;
2166         client_set_undecorated(self, TRUE);
2167     }
2168     if (self->shaded) {
2169         self->shaded = FALSE;
2170         client_shade(self, TRUE);
2171     }
2172     if (self->demands_attention) {
2173         self->demands_attention = FALSE;
2174         client_hilite(self, TRUE);
2175     }
2176   
2177     if (self->max_vert && self->max_horz) {
2178         self->max_vert = self->max_horz = FALSE;
2179         client_maximize(self, TRUE, 0);
2180         pos = TRUE;
2181     } else if (self->max_vert) {
2182         self->max_vert = FALSE;
2183         client_maximize(self, TRUE, 2);
2184         pos = TRUE;
2185     } else if (self->max_horz) {
2186         self->max_horz = FALSE;
2187         client_maximize(self, TRUE, 1);
2188         pos = TRUE;
2189     }
2190
2191     /* if the client didn't get positioned yet, then do so now */
2192     if (!pos && (ox != x || oy != y)) {
2193         /* use the saved position */
2194         self->area.x = ox;
2195         self->area.y = oy;
2196         client_move(self, x, y);
2197     }
2198
2199     /* nothing to do for the other states:
2200        skip_taskbar
2201        skip_pager
2202        modal
2203        above
2204        below
2205     */
2206 }
2207
2208 void client_try_configure(ObClient *self, ObCorner anchor,
2209                           gint *x, gint *y, gint *w, gint *h,
2210                           gint *logicalw, gint *logicalh,
2211                           gboolean user)
2212 {
2213     Rect desired_area = {*x, *y, *w, *h};
2214
2215     /* make the frame recalculate its dimentions n shit without changing
2216        anything visible for real, this way the constraints below can work with
2217        the updated frame dimensions. */
2218     frame_adjust_area(self->frame, TRUE, TRUE, TRUE);
2219
2220     /* gets the frame's position */
2221     frame_client_gravity(self->frame, x, y);
2222
2223     /* these positions are frame positions, not client positions */
2224
2225     /* set the size and position if fullscreen */
2226     if (self->fullscreen) {
2227         Rect *a;
2228         guint i;
2229
2230         i = screen_find_monitor(&desired_area);
2231         a = screen_physical_area_monitor(i);
2232
2233         *x = a->x;
2234         *y = a->y;
2235         *w = a->width;
2236         *h = a->height;
2237
2238         user = FALSE; /* ignore that increment etc shit when in fullscreen */
2239     } else {
2240         Rect *a;
2241         guint i;
2242
2243         i = screen_find_monitor(&desired_area);
2244         a = screen_area_monitor(self->desktop, i);
2245
2246         /* set the size and position if maximized */
2247         if (self->max_horz) {
2248             *x = a->x;
2249             *w = a->width - self->frame->size.left - self->frame->size.right;
2250         }
2251         if (self->max_vert) {
2252             *y = a->y;
2253             *h = a->height - self->frame->size.top - self->frame->size.bottom;
2254         }
2255     }
2256
2257     /* gets the client's position */
2258     frame_frame_gravity(self->frame, x, y);
2259
2260     /* these override the above states! if you cant move you can't move! */
2261     if (user) {
2262         if (!(self->functions & OB_CLIENT_FUNC_MOVE)) {
2263             *x = self->area.x;
2264             *y = self->area.y;
2265         }
2266         if (!(self->functions & OB_CLIENT_FUNC_RESIZE)) {
2267             *w = self->area.width;
2268             *h = self->area.height;
2269         }
2270     }
2271
2272     if (!(*w == self->area.width && *h == self->area.height)) {
2273         gint basew, baseh, minw, minh;
2274
2275         /* base size is substituted with min size if not specified */
2276         if (self->base_size.width || self->base_size.height) {
2277             basew = self->base_size.width;
2278             baseh = self->base_size.height;
2279         } else {
2280             basew = self->min_size.width;
2281             baseh = self->min_size.height;
2282         }
2283         /* min size is substituted with base size if not specified */
2284         if (self->min_size.width || self->min_size.height) {
2285             minw = self->min_size.width;
2286             minh = self->min_size.height;
2287         } else {
2288             minw = self->base_size.width;
2289             minh = self->base_size.height;
2290         }
2291
2292         /* if this is a user-requested resize, then check against min/max
2293            sizes */
2294
2295         /* smaller than min size or bigger than max size? */
2296         if (*w > self->max_size.width) *w = self->max_size.width;
2297         if (*w < minw) *w = minw;
2298         if (*h > self->max_size.height) *h = self->max_size.height;
2299         if (*h < minh) *h = minh;
2300
2301         *w -= basew;
2302         *h -= baseh;
2303
2304         /* keep to the increments */
2305         *w /= self->size_inc.width;
2306         *h /= self->size_inc.height;
2307
2308         /* you cannot resize to nothing */
2309         if (basew + *w < 1) *w = 1 - basew;
2310         if (baseh + *h < 1) *h = 1 - baseh;
2311   
2312         /* save the logical size */
2313         *logicalw = self->size_inc.width > 1 ? *w : *w + basew;
2314         *logicalh = self->size_inc.height > 1 ? *h : *h + baseh;
2315
2316         *w *= self->size_inc.width;
2317         *h *= self->size_inc.height;
2318
2319         *w += basew;
2320         *h += baseh;
2321
2322         /* adjust the height to match the width for the aspect ratios.
2323            for this, min size is not substituted for base size ever. */
2324         *w -= self->base_size.width;
2325         *h -= self->base_size.height;
2326
2327         if (!self->fullscreen) {
2328             if (self->min_ratio)
2329                 if (*h * self->min_ratio > *w) {
2330                     *h = (gint)(*w / self->min_ratio);
2331
2332                     /* you cannot resize to nothing */
2333                     if (*h < 1) {
2334                         *h = 1;
2335                         *w = (gint)(*h * self->min_ratio);
2336                     }
2337                 }
2338             if (self->max_ratio)
2339                 if (*h * self->max_ratio < *w) {
2340                     *h = (gint)(*w / self->max_ratio);
2341
2342                     /* you cannot resize to nothing */
2343                     if (*h < 1) {
2344                         *h = 1;
2345                         *w = (gint)(*h * self->min_ratio);
2346                     }
2347                 }
2348         }
2349
2350         *w += self->base_size.width;
2351         *h += self->base_size.height;
2352     }
2353
2354     g_assert(*w > 0);
2355     g_assert(*h > 0);
2356
2357     switch (anchor) {
2358     case OB_CORNER_TOPLEFT:
2359         break;
2360     case OB_CORNER_TOPRIGHT:
2361         *x -= *w - self->area.width;
2362         break;
2363     case OB_CORNER_BOTTOMLEFT:
2364         *y -= *h - self->area.height;
2365         break;
2366     case OB_CORNER_BOTTOMRIGHT:
2367         *x -= *w - self->area.width;
2368         *y -= *h - self->area.height;
2369         break;
2370     }
2371 }
2372
2373
2374 void client_configure_full(ObClient *self, ObCorner anchor,
2375                            gint x, gint y, gint w, gint h,
2376                            gboolean user, gboolean final,
2377                            gboolean force_reply)
2378 {
2379     gint oldw, oldh;
2380     gboolean send_resize_client;
2381     gboolean moved = FALSE, resized = FALSE;
2382     guint fdecor = self->frame->decorations;
2383     gboolean fhorz = self->frame->max_horz;
2384     gint logicalw, logicalh;
2385
2386     /* find the new x, y, width, and height (and logical size) */
2387     client_try_configure(self, anchor, &x, &y, &w, &h,
2388                          &logicalw, &logicalh, user);
2389
2390     /* set the logical size */
2391     SIZE_SET(self->logical_size, logicalw, logicalh);
2392
2393     /* figure out if we moved or resized or what */
2394     moved = x != self->area.x || y != self->area.y;
2395     resized = w != self->area.width || h != self->area.height;
2396
2397     oldw = self->area.width;
2398     oldh = self->area.height;
2399     RECT_SET(self->area, x, y, w, h);
2400
2401     /* for app-requested resizes, always resize if 'resized' is true.
2402        for user-requested ones, only resize if final is true, or when
2403        resizing in redraw mode */
2404     send_resize_client = ((!user && resized) ||
2405                           (user && (final ||
2406                                     (resized && config_resize_redraw))));
2407
2408     /* if the client is enlarging, then resize the client before the frame */
2409     if (send_resize_client && user && (w > oldw || h > oldh))
2410         XResizeWindow(ob_display, self->window, MAX(w, oldw), MAX(h, oldh));
2411
2412     /* move/resize the frame to match the request */
2413     if (self->frame) {
2414         if (self->decorations != fdecor || self->max_horz != fhorz)
2415             moved = resized = TRUE;
2416
2417         if (moved || resized)
2418             frame_adjust_area(self->frame, moved, resized, FALSE);
2419
2420         if (!resized && (force_reply || ((!user && moved) || (user && final))))
2421         {
2422             XEvent event;
2423             event.type = ConfigureNotify;
2424             event.xconfigure.display = ob_display;
2425             event.xconfigure.event = self->window;
2426             event.xconfigure.window = self->window;
2427
2428             /* root window real coords */
2429             event.xconfigure.x = self->frame->area.x + self->frame->size.left -
2430                 self->border_width;
2431             event.xconfigure.y = self->frame->area.y + self->frame->size.top -
2432                 self->border_width;
2433             event.xconfigure.width = w;
2434             event.xconfigure.height = h;
2435             event.xconfigure.border_width = 0;
2436             event.xconfigure.above = self->frame->plate;
2437             event.xconfigure.override_redirect = FALSE;
2438             XSendEvent(event.xconfigure.display, event.xconfigure.window,
2439                        FALSE, StructureNotifyMask, &event);
2440         }
2441     }
2442
2443     /* if the client is shrinking, then resize the frame before the client */
2444     if (send_resize_client && (!user || (w <= oldw || h <= oldh)))
2445         XResizeWindow(ob_display, self->window, w, h);
2446
2447     XFlush(ob_display);
2448 }
2449
2450 void client_fullscreen(ObClient *self, gboolean fs)
2451 {
2452     gint x, y, w, h;
2453
2454     if (!(self->functions & OB_CLIENT_FUNC_FULLSCREEN) || /* can't */
2455         self->fullscreen == fs) return;                   /* already done */
2456
2457     self->fullscreen = fs;
2458     client_change_state(self); /* change the state hints on the client */
2459     client_calc_layer(self);   /* and adjust out layer/stacking */
2460
2461     if (fs) {
2462         self->pre_fullscreen_area = self->area;
2463         /* if the window is maximized, its area isn't all that meaningful.
2464            save it's premax area instead. */
2465         if (self->max_horz) {
2466             self->pre_fullscreen_area.x = self->pre_max_area.x;
2467             self->pre_fullscreen_area.width = self->pre_max_area.width;
2468         }
2469         if (self->max_vert) {
2470             self->pre_fullscreen_area.y = self->pre_max_area.y;
2471             self->pre_fullscreen_area.height = self->pre_max_area.height;
2472         }
2473
2474         /* these are not actually used cuz client_configure will set them
2475            as appropriate when the window is fullscreened */
2476         x = y = w = h = 0;
2477     } else {
2478         Rect *a;
2479
2480         if (self->pre_fullscreen_area.width > 0 &&
2481             self->pre_fullscreen_area.height > 0)
2482         {
2483             x = self->pre_fullscreen_area.x;
2484             y = self->pre_fullscreen_area.y;
2485             w = self->pre_fullscreen_area.width;
2486             h = self->pre_fullscreen_area.height;
2487             RECT_SET(self->pre_fullscreen_area, 0, 0, 0, 0);
2488         } else {
2489             /* pick some fallbacks... */
2490             a = screen_area_monitor(self->desktop, 0);
2491             x = a->x + a->width / 4;
2492             y = a->y + a->height / 4;
2493             w = a->width / 2;
2494             h = a->height / 2;
2495         }
2496     }
2497
2498     client_setup_decor_and_functions(self);
2499
2500     client_move_resize(self, x, y, w, h);
2501
2502     /* try focus us when we go into fullscreen mode */
2503     client_focus(self);
2504 }
2505
2506 static void client_iconify_recursive(ObClient *self,
2507                                      gboolean iconic, gboolean curdesk)
2508 {
2509     GSList *it;
2510     gboolean changed = FALSE;
2511
2512
2513     if (self->iconic != iconic) {
2514         ob_debug("%sconifying window: 0x%lx\n", (iconic ? "I" : "Uni"),
2515                  self->window);
2516
2517         self->iconic = iconic;
2518
2519         if (iconic) {
2520             if (self->functions & OB_CLIENT_FUNC_ICONIFY) {
2521                 /* update the focus lists.. iconic windows go to the bottom of
2522                    the list, put the new iconic window at the 'top of the
2523                    bottom'. */
2524                 focus_order_to_top(self);
2525
2526                 changed = TRUE;
2527             }
2528         } else {
2529             if (curdesk)
2530                 client_set_desktop(self, screen_desktop, FALSE);
2531
2532             /* this puts it after the current focused window */
2533             focus_order_remove(self);
2534             focus_order_add_new(self);
2535
2536             changed = TRUE;
2537         }
2538     }
2539
2540     if (changed) {
2541         client_change_state(self);
2542         client_showhide(self);
2543         if (STRUT_EXISTS(self->strut))
2544             screen_update_areas();
2545     }
2546
2547     /* iconify all direct transients */
2548     for (it = self->transients; it; it = g_slist_next(it))
2549         if (it->data != self)
2550             if (client_is_direct_child(self, it->data))
2551                 client_iconify_recursive(it->data, iconic, curdesk);
2552 }
2553
2554 void client_iconify(ObClient *self, gboolean iconic, gboolean curdesk)
2555 {
2556     /* move up the transient chain as far as possible first */
2557     self = client_search_top_parent(self);
2558     client_iconify_recursive(self, iconic, curdesk);
2559 }
2560
2561 void client_maximize(ObClient *self, gboolean max, gint dir)
2562 {
2563     gint x, y, w, h;
2564      
2565     g_assert(dir == 0 || dir == 1 || dir == 2);
2566     if (!(self->functions & OB_CLIENT_FUNC_MAXIMIZE)) return; /* can't */
2567
2568     /* check if already done */
2569     if (max) {
2570         if (dir == 0 && self->max_horz && self->max_vert) return;
2571         if (dir == 1 && self->max_horz) return;
2572         if (dir == 2 && self->max_vert) return;
2573     } else {
2574         if (dir == 0 && !self->max_horz && !self->max_vert) return;
2575         if (dir == 1 && !self->max_horz) return;
2576         if (dir == 2 && !self->max_vert) return;
2577     }
2578
2579     /* we just tell it to configure in the same place and client_configure
2580        worries about filling the screen with the window */
2581     x = self->area.x;
2582     y = self->area.y;
2583     w = self->area.width;
2584     h = self->area.height;
2585
2586     if (max) {
2587         if ((dir == 0 || dir == 1) && !self->max_horz) { /* horz */
2588             RECT_SET(self->pre_max_area,
2589                      self->area.x, self->pre_max_area.y,
2590                      self->area.width, self->pre_max_area.height);
2591         }
2592         if ((dir == 0 || dir == 2) && !self->max_vert) { /* vert */
2593             RECT_SET(self->pre_max_area,
2594                      self->pre_max_area.x, self->area.y,
2595                      self->pre_max_area.width, self->area.height);
2596         }
2597     } else {
2598         Rect *a;
2599
2600         a = screen_area_monitor(self->desktop, 0);
2601         if ((dir == 0 || dir == 1) && self->max_horz) { /* horz */
2602             if (self->pre_max_area.width > 0) {
2603                 x = self->pre_max_area.x;
2604                 w = self->pre_max_area.width;
2605
2606                 RECT_SET(self->pre_max_area, 0, self->pre_max_area.y,
2607                          0, self->pre_max_area.height);
2608             } else {
2609                 /* pick some fallbacks... */
2610                 x = a->x + a->width / 4;
2611                 w = a->width / 2;
2612             }
2613         }
2614         if ((dir == 0 || dir == 2) && self->max_vert) { /* vert */
2615             if (self->pre_max_area.height > 0) {
2616                 y = self->pre_max_area.y;
2617                 h = self->pre_max_area.height;
2618
2619                 RECT_SET(self->pre_max_area, self->pre_max_area.x, 0,
2620                          self->pre_max_area.width, 0);
2621             } else {
2622                 /* pick some fallbacks... */
2623                 y = a->y + a->height / 4;
2624                 h = a->height / 2;
2625             }
2626         }
2627     }
2628
2629     if (dir == 0 || dir == 1) /* horz */
2630         self->max_horz = max;
2631     if (dir == 0 || dir == 2) /* vert */
2632         self->max_vert = max;
2633
2634     client_change_state(self); /* change the state hints on the client */
2635
2636     client_setup_decor_and_functions(self);
2637
2638     client_move_resize(self, x, y, w, h);
2639 }
2640
2641 void client_shade(ObClient *self, gboolean shade)
2642 {
2643     if ((!(self->functions & OB_CLIENT_FUNC_SHADE) &&
2644          shade) ||                         /* can't shade */
2645         self->shaded == shade) return;     /* already done */
2646
2647     self->shaded = shade;
2648     client_change_state(self);
2649     client_change_wm_state(self); /* the window is being hidden/shown */
2650     /* resize the frame to just the titlebar */
2651     frame_adjust_area(self->frame, FALSE, FALSE, FALSE);
2652 }
2653
2654 void client_close(ObClient *self)
2655 {
2656     XEvent ce;
2657
2658     if (!(self->functions & OB_CLIENT_FUNC_CLOSE)) return;
2659
2660     /* in the case that the client provides no means to requesting that it
2661        close, we just kill it */
2662     if (!self->delete_window)
2663         client_kill(self);
2664     
2665     /*
2666       XXX: itd be cool to do timeouts and shit here for killing the client's
2667       process off
2668       like... if the window is around after 5 seconds, then the close button
2669       turns a nice red, and if this function is called again, the client is
2670       explicitly killed.
2671     */
2672
2673     ce.xclient.type = ClientMessage;
2674     ce.xclient.message_type =  prop_atoms.wm_protocols;
2675     ce.xclient.display = ob_display;
2676     ce.xclient.window = self->window;
2677     ce.xclient.format = 32;
2678     ce.xclient.data.l[0] = prop_atoms.wm_delete_window;
2679     ce.xclient.data.l[1] = event_curtime;
2680     ce.xclient.data.l[2] = 0l;
2681     ce.xclient.data.l[3] = 0l;
2682     ce.xclient.data.l[4] = 0l;
2683     XSendEvent(ob_display, self->window, FALSE, NoEventMask, &ce);
2684 }
2685
2686 void client_kill(ObClient *self)
2687 {
2688     XKillClient(ob_display, self->window);
2689 }
2690
2691 void client_hilite(ObClient *self, gboolean hilite)
2692 {
2693     if (self->demands_attention == hilite)
2694         return; /* no change */
2695
2696     /* don't allow focused windows to hilite */
2697     self->demands_attention = hilite && !client_focused(self);
2698     if (self->demands_attention)
2699         frame_flash_start(self->frame);
2700     else
2701         frame_flash_stop(self->frame);
2702     client_change_state(self);
2703 }
2704
2705 void client_set_desktop_recursive(ObClient *self,
2706                                   guint target, gboolean donthide)
2707 {
2708     guint old;
2709     GSList *it;
2710
2711     if (target != self->desktop) {
2712
2713         ob_debug("Setting desktop %u\n", target+1);
2714
2715         g_assert(target < screen_num_desktops || target == DESKTOP_ALL);
2716
2717         /* remove from the old desktop(s) */
2718         focus_order_remove(self);
2719
2720         old = self->desktop;
2721         self->desktop = target;
2722         PROP_SET32(self->window, net_wm_desktop, cardinal, target);
2723         /* the frame can display the current desktop state */
2724         frame_adjust_state(self->frame);
2725         /* 'move' the window to the new desktop */
2726         if (!donthide)
2727             client_showhide(self);
2728         /* raise if it was not already on the desktop */
2729         if (old != DESKTOP_ALL)
2730             client_raise(self);
2731         if (STRUT_EXISTS(self->strut))
2732             screen_update_areas();
2733
2734         /* add to the new desktop(s) */
2735         if (config_focus_new)
2736             focus_order_to_top(self);
2737         else
2738             focus_order_to_bottom(self);
2739     }
2740
2741     /* move all transients */
2742     for (it = self->transients; it; it = g_slist_next(it))
2743         if (it->data != self)
2744             if (client_is_direct_child(self, it->data))
2745                 client_set_desktop_recursive(it->data, target, donthide);
2746 }
2747
2748 void client_set_desktop(ObClient *self, guint target, gboolean donthide)
2749 {
2750     self = client_search_top_parent(self);
2751     client_set_desktop_recursive(self, target, donthide);
2752 }
2753
2754 gboolean client_is_direct_child(ObClient *parent, ObClient *child)
2755 {
2756     while (child != parent &&
2757            child->transient_for && child->transient_for != OB_TRAN_GROUP)
2758         child = child->transient_for;
2759     return child == parent;
2760 }
2761
2762 ObClient *client_search_modal_child(ObClient *self)
2763 {
2764     GSList *it;
2765     ObClient *ret;
2766   
2767     for (it = self->transients; it; it = g_slist_next(it)) {
2768         ObClient *c = it->data;
2769         if ((ret = client_search_modal_child(c))) return ret;
2770         if (c->modal) return c;
2771     }
2772     return NULL;
2773 }
2774
2775 gboolean client_validate(ObClient *self)
2776 {
2777     XEvent e; 
2778
2779     XSync(ob_display, FALSE); /* get all events on the server */
2780
2781     if (XCheckTypedWindowEvent(ob_display, self->window, DestroyNotify, &e) ||
2782         XCheckTypedWindowEvent(ob_display, self->window, UnmapNotify, &e)) {
2783         XPutBackEvent(ob_display, &e);
2784         return FALSE;
2785     }
2786
2787     return TRUE;
2788 }
2789
2790 void client_set_wm_state(ObClient *self, glong state)
2791 {
2792     if (state == self->wmstate) return; /* no change */
2793   
2794     switch (state) {
2795     case IconicState:
2796         client_iconify(self, TRUE, TRUE);
2797         break;
2798     case NormalState:
2799         client_iconify(self, FALSE, TRUE);
2800         break;
2801     }
2802 }
2803
2804 void client_set_state(ObClient *self, Atom action, glong data1, glong data2)
2805 {
2806     gboolean shaded = self->shaded;
2807     gboolean fullscreen = self->fullscreen;
2808     gboolean undecorated = self->undecorated;
2809     gboolean max_horz = self->max_horz;
2810     gboolean max_vert = self->max_vert;
2811     gboolean modal = self->modal;
2812     gboolean iconic = self->iconic;
2813     gboolean demands_attention = self->demands_attention;
2814     gint i;
2815
2816     if (!(action == prop_atoms.net_wm_state_add ||
2817           action == prop_atoms.net_wm_state_remove ||
2818           action == prop_atoms.net_wm_state_toggle))
2819         /* an invalid action was passed to the client message, ignore it */
2820         return; 
2821
2822     for (i = 0; i < 2; ++i) {
2823         Atom state = i == 0 ? data1 : data2;
2824     
2825         if (!state) continue;
2826
2827         /* if toggling, then pick whether we're adding or removing */
2828         if (action == prop_atoms.net_wm_state_toggle) {
2829             if (state == prop_atoms.net_wm_state_modal)
2830                 action = modal ? prop_atoms.net_wm_state_remove :
2831                     prop_atoms.net_wm_state_add;
2832             else if (state == prop_atoms.net_wm_state_maximized_vert)
2833                 action = self->max_vert ? prop_atoms.net_wm_state_remove :
2834                     prop_atoms.net_wm_state_add;
2835             else if (state == prop_atoms.net_wm_state_maximized_horz)
2836                 action = self->max_horz ? prop_atoms.net_wm_state_remove :
2837                     prop_atoms.net_wm_state_add;
2838             else if (state == prop_atoms.net_wm_state_shaded)
2839                 action = shaded ? prop_atoms.net_wm_state_remove :
2840                     prop_atoms.net_wm_state_add;
2841             else if (state == prop_atoms.net_wm_state_skip_taskbar)
2842                 action = self->skip_taskbar ?
2843                     prop_atoms.net_wm_state_remove :
2844                     prop_atoms.net_wm_state_add;
2845             else if (state == prop_atoms.net_wm_state_skip_pager)
2846                 action = self->skip_pager ?
2847                     prop_atoms.net_wm_state_remove :
2848                     prop_atoms.net_wm_state_add;
2849             else if (state == prop_atoms.net_wm_state_hidden)
2850                 action = self->iconic ?
2851                     prop_atoms.net_wm_state_remove :
2852                     prop_atoms.net_wm_state_add;
2853             else if (state == prop_atoms.net_wm_state_fullscreen)
2854                 action = fullscreen ?
2855                     prop_atoms.net_wm_state_remove :
2856                     prop_atoms.net_wm_state_add;
2857             else if (state == prop_atoms.net_wm_state_above)
2858                 action = self->above ? prop_atoms.net_wm_state_remove :
2859                     prop_atoms.net_wm_state_add;
2860             else if (state == prop_atoms.net_wm_state_below)
2861                 action = self->below ? prop_atoms.net_wm_state_remove :
2862                     prop_atoms.net_wm_state_add;
2863             else if (state == prop_atoms.net_wm_state_demands_attention)
2864                 action = self->demands_attention ?
2865                     prop_atoms.net_wm_state_remove :
2866                     prop_atoms.net_wm_state_add;
2867             else if (state == prop_atoms.ob_wm_state_undecorated)
2868                 action = undecorated ? prop_atoms.net_wm_state_remove :
2869                     prop_atoms.net_wm_state_add;
2870         }
2871     
2872         if (action == prop_atoms.net_wm_state_add) {
2873             if (state == prop_atoms.net_wm_state_modal) {
2874                 modal = TRUE;
2875             } else if (state == prop_atoms.net_wm_state_maximized_vert) {
2876                 max_vert = TRUE;
2877             } else if (state == prop_atoms.net_wm_state_maximized_horz) {
2878                 max_horz = TRUE;
2879             } else if (state == prop_atoms.net_wm_state_shaded) {
2880                 shaded = TRUE;
2881             } else if (state == prop_atoms.net_wm_state_skip_taskbar) {
2882                 self->skip_taskbar = TRUE;
2883             } else if (state == prop_atoms.net_wm_state_skip_pager) {
2884                 self->skip_pager = TRUE;
2885             } else if (state == prop_atoms.net_wm_state_hidden) {
2886                 iconic = TRUE;
2887             } else if (state == prop_atoms.net_wm_state_fullscreen) {
2888                 fullscreen = TRUE;
2889             } else if (state == prop_atoms.net_wm_state_above) {
2890                 self->above = TRUE;
2891                 self->below = FALSE;
2892             } else if (state == prop_atoms.net_wm_state_below) {
2893                 self->above = FALSE;
2894                 self->below = TRUE;
2895             } else if (state == prop_atoms.net_wm_state_demands_attention) {
2896                 demands_attention = TRUE;
2897             } else if (state == prop_atoms.ob_wm_state_undecorated) {
2898                 undecorated = TRUE;
2899             }
2900
2901         } else { /* action == prop_atoms.net_wm_state_remove */
2902             if (state == prop_atoms.net_wm_state_modal) {
2903                 modal = FALSE;
2904             } else if (state == prop_atoms.net_wm_state_maximized_vert) {
2905                 max_vert = FALSE;
2906             } else if (state == prop_atoms.net_wm_state_maximized_horz) {
2907                 max_horz = FALSE;
2908             } else if (state == prop_atoms.net_wm_state_shaded) {
2909                 shaded = FALSE;
2910             } else if (state == prop_atoms.net_wm_state_skip_taskbar) {
2911                 self->skip_taskbar = FALSE;
2912             } else if (state == prop_atoms.net_wm_state_skip_pager) {
2913                 self->skip_pager = FALSE;
2914             } else if (state == prop_atoms.net_wm_state_hidden) {
2915                 iconic = FALSE;
2916             } else if (state == prop_atoms.net_wm_state_fullscreen) {
2917                 fullscreen = FALSE;
2918             } else if (state == prop_atoms.net_wm_state_above) {
2919                 self->above = FALSE;
2920             } else if (state == prop_atoms.net_wm_state_below) {
2921                 self->below = FALSE;
2922             } else if (state == prop_atoms.net_wm_state_demands_attention) {
2923                 demands_attention = FALSE;
2924             } else if (state == prop_atoms.ob_wm_state_undecorated) {
2925                 undecorated = FALSE;
2926             }
2927         }
2928     }
2929     if (max_horz != self->max_horz || max_vert != self->max_vert) {
2930         if (max_horz != self->max_horz && max_vert != self->max_vert) {
2931             /* toggling both */
2932             if (max_horz == max_vert) { /* both going the same way */
2933                 client_maximize(self, max_horz, 0);
2934             } else {
2935                 client_maximize(self, max_horz, 1);
2936                 client_maximize(self, max_vert, 2);
2937             }
2938         } else {
2939             /* toggling one */
2940             if (max_horz != self->max_horz)
2941                 client_maximize(self, max_horz, 1);
2942             else
2943                 client_maximize(self, max_vert, 2);
2944         }
2945     }
2946     /* change fullscreen state before shading, as it will affect if the window
2947        can shade or not */
2948     if (fullscreen != self->fullscreen)
2949         client_fullscreen(self, fullscreen);
2950     if (shaded != self->shaded)
2951         client_shade(self, shaded);
2952     if (undecorated != self->undecorated)
2953         client_set_undecorated(self, undecorated);
2954     if (modal != self->modal) {
2955         self->modal = modal;
2956         /* when a window changes modality, then its stacking order with its
2957            transients needs to change */
2958         client_raise(self);
2959     }
2960     if (iconic != self->iconic)
2961         client_iconify(self, iconic, FALSE);
2962
2963     if (demands_attention != self->demands_attention)
2964         client_hilite(self, demands_attention);
2965
2966     client_change_state(self); /* change the hint to reflect these changes */
2967 }
2968
2969 ObClient *client_focus_target(ObClient *self)
2970 {
2971     ObClient *child = NULL;
2972
2973     child = client_search_modal_child(self);
2974     if (child) return child;
2975     return self;
2976 }
2977
2978 gboolean client_can_focus(ObClient *self)
2979 {
2980     XEvent ev;
2981
2982     /* choose the correct target */
2983     self = client_focus_target(self);
2984
2985     if (!self->frame->visible)
2986         return FALSE;
2987
2988     if (!(self->can_focus || self->focus_notify))
2989         return FALSE;
2990
2991     /* do a check to see if the window has already been unmapped or destroyed
2992        do this intelligently while watching out for unmaps we've generated
2993        (ignore_unmaps > 0) */
2994     if (XCheckTypedWindowEvent(ob_display, self->window,
2995                                DestroyNotify, &ev)) {
2996         XPutBackEvent(ob_display, &ev);
2997         return FALSE;
2998     }
2999     while (XCheckTypedWindowEvent(ob_display, self->window,
3000                                   UnmapNotify, &ev)) {
3001         if (self->ignore_unmaps) {
3002             self->ignore_unmaps--;
3003         } else {
3004             XPutBackEvent(ob_display, &ev);
3005             return FALSE;
3006         }
3007     }
3008
3009     return TRUE;
3010 }
3011
3012 gboolean client_focus(ObClient *self)
3013 {
3014     /* choose the correct target */
3015     self = client_focus_target(self);
3016
3017 #if 0
3018     if (!client_validate(self))
3019         return FALSE;
3020 #endif
3021
3022     if (!client_can_focus(self)) {
3023         if (!self->frame->visible) {
3024             /* update the focus lists */
3025             focus_order_to_top(self);
3026         }
3027         return FALSE;
3028     }
3029
3030     ob_debug("Focusing client \"%s\" at time %u\n", self->title, event_curtime);
3031
3032     if (self->can_focus) {
3033         /* RevertToPointerRoot causes much more headache than RevertToNone, so
3034            I choose to use it always, hopefully to find errors quicker, if any
3035            are left. (I hate X. I hate focus events.)
3036            
3037            Update: Changing this to RevertToNone fixed a bug with mozilla (bug
3038            #799. So now it is RevertToNone again.
3039         */
3040         XSetInputFocus(ob_display, self->window, RevertToNone,
3041                        event_curtime);
3042     }
3043
3044     if (self->focus_notify) {
3045         XEvent ce;
3046         ce.xclient.type = ClientMessage;
3047         ce.xclient.message_type = prop_atoms.wm_protocols;
3048         ce.xclient.display = ob_display;
3049         ce.xclient.window = self->window;
3050         ce.xclient.format = 32;
3051         ce.xclient.data.l[0] = prop_atoms.wm_take_focus;
3052         ce.xclient.data.l[1] = event_curtime;
3053         ce.xclient.data.l[2] = 0l;
3054         ce.xclient.data.l[3] = 0l;
3055         ce.xclient.data.l[4] = 0l;
3056         XSendEvent(ob_display, self->window, FALSE, NoEventMask, &ce);
3057     }
3058
3059 #ifdef DEBUG_FOCUS
3060     ob_debug("%sively focusing %lx at %d\n",
3061              (self->can_focus ? "act" : "pass"),
3062              self->window, (gint) event_curtime);
3063 #endif
3064
3065     /* Cause the FocusIn to come back to us. Important for desktop switches,
3066        since otherwise we'll have no FocusIn on the queue and send it off to
3067        the focus_backup. */
3068     XSync(ob_display, FALSE);
3069     return TRUE;
3070 }
3071
3072 /* Used when the current client is closed or otherwise hidden, focus_last will
3073    then prevent focus from going to the mouse pointer
3074 */
3075 void client_unfocus(ObClient *self)
3076 {
3077     if (focus_client == self) {
3078 #ifdef DEBUG_FOCUS
3079         ob_debug("client_unfocus for %lx\n", self->window);
3080 #endif
3081         focus_fallback(OB_FOCUS_FALLBACK_CLOSED);
3082     }
3083 }
3084
3085 void client_activate(ObClient *self, gboolean here, gboolean user, Time time)
3086 {
3087     /* XXX do some stuff here if user is false to determine if we really want
3088        to activate it or not (a parent or group member is currently
3089        active)?
3090     */
3091     ob_debug("Want to activate window 0x%x with time %u (last time %u), "
3092              "source=%s\n",
3093              self->window, time, client_last_user_time,
3094              (user ? "user" : "application"));
3095     if (!user && time && time < client_last_user_time)
3096         client_hilite(self, TRUE);
3097     else {
3098         if (client_normal(self) && screen_showing_desktop)
3099             screen_show_desktop(FALSE);
3100         if (self->iconic)
3101             client_iconify(self, FALSE, here);
3102         if (self->desktop != DESKTOP_ALL &&
3103             self->desktop != screen_desktop) {
3104             if (here)
3105                 client_set_desktop(self, screen_desktop, FALSE);
3106             else
3107                 screen_set_desktop(self->desktop);
3108         } else if (!self->frame->visible)
3109             /* if its not visible for other reasons, then don't mess
3110                with it */
3111             return;
3112         if (self->shaded)
3113             client_shade(self, FALSE);
3114
3115         client_focus(self);
3116
3117         /* we do this an action here. this is rather important. this is because
3118            we want the results from the focus change to take place BEFORE we go
3119            about raising the window. when a fullscreen window loses focus, we
3120            need this or else the raise wont be able to raise above the
3121            to-lose-focus fullscreen window. */
3122         client_raise(self);
3123     }
3124 }
3125
3126 void client_raise(ObClient *self)
3127 {
3128     action_run_string("Raise", self, CurrentTime);
3129 }
3130
3131 void client_lower(ObClient *self)
3132 {
3133     action_run_string("Lower", self, CurrentTime);
3134 }
3135
3136 gboolean client_focused(ObClient *self)
3137 {
3138     return self == focus_client;
3139 }
3140
3141 static ObClientIcon* client_icon_recursive(ObClient *self, gint w, gint h)
3142 {
3143     guint i;
3144     /* si is the smallest image >= req */
3145     /* li is the largest image < req */
3146     gulong size, smallest = 0xffffffff, largest = 0, si = 0, li = 0;
3147
3148     if (!self->nicons) {
3149         ObClientIcon *parent = NULL;
3150
3151         if (self->transient_for) {
3152             if (self->transient_for != OB_TRAN_GROUP)
3153                 parent = client_icon_recursive(self->transient_for, w, h);
3154             else {
3155                 GSList *it;
3156                 for (it = self->group->members; it; it = g_slist_next(it)) {
3157                     ObClient *c = it->data;
3158                     if (c != self && !c->transient_for) {
3159                         if ((parent = client_icon_recursive(c, w, h)))
3160                             break;
3161                     }
3162                 }
3163             }
3164         }
3165         
3166         return parent;
3167     }
3168
3169     for (i = 0; i < self->nicons; ++i) {
3170         size = self->icons[i].width * self->icons[i].height;
3171         if (size < smallest && size >= (unsigned)(w * h)) {
3172             smallest = size;
3173             si = i;
3174         }
3175         if (size > largest && size <= (unsigned)(w * h)) {
3176             largest = size;
3177             li = i;
3178         }
3179     }
3180     if (largest == 0) /* didnt find one smaller than the requested size */
3181         return &self->icons[si];
3182     return &self->icons[li];
3183 }
3184
3185 const ObClientIcon* client_icon(ObClient *self, gint w, gint h)
3186 {
3187     ObClientIcon *ret;
3188     static ObClientIcon deficon;
3189
3190     if (!(ret = client_icon_recursive(self, w, h))) {
3191         deficon.width = deficon.height = 48;
3192         deficon.data = ob_rr_theme->def_win_icon;
3193         ret = &deficon;
3194     }
3195     return ret;
3196 }
3197
3198 /* this be mostly ripped from fvwm */
3199 ObClient *client_find_directional(ObClient *c, ObDirection dir) 
3200 {
3201     gint my_cx, my_cy, his_cx, his_cy;
3202     gint offset = 0;
3203     gint distance = 0;
3204     gint score, best_score;
3205     ObClient *best_client, *cur;
3206     GList *it;
3207
3208     if(!client_list)
3209         return NULL;
3210
3211     /* first, find the centre coords of the currently focused window */
3212     my_cx = c->frame->area.x + c->frame->area.width / 2;
3213     my_cy = c->frame->area.y + c->frame->area.height / 2;
3214
3215     best_score = -1;
3216     best_client = NULL;
3217
3218     for(it = g_list_first(client_list); it; it = g_list_next(it)) {
3219         cur = it->data;
3220
3221         /* the currently selected window isn't interesting */
3222         if(cur == c)
3223             continue;
3224         if (!client_normal(cur))
3225             continue;
3226         /* using c->desktop instead of screen_desktop doesn't work if the
3227          * current window was omnipresent, hope this doesn't have any other
3228          * side effects */
3229         if(screen_desktop != cur->desktop && cur->desktop != DESKTOP_ALL)
3230             continue;
3231         if(cur->iconic)
3232             continue;
3233         if(!(client_focus_target(cur) == cur &&
3234              client_can_focus(cur)))
3235             continue;
3236
3237         /* find the centre coords of this window, from the
3238          * currently focused window's point of view */
3239         his_cx = (cur->frame->area.x - my_cx)
3240             + cur->frame->area.width / 2;
3241         his_cy = (cur->frame->area.y - my_cy)
3242             + cur->frame->area.height / 2;
3243
3244         if(dir == OB_DIRECTION_NORTHEAST || dir == OB_DIRECTION_SOUTHEAST ||
3245            dir == OB_DIRECTION_SOUTHWEST || dir == OB_DIRECTION_NORTHWEST) {
3246             gint tx;
3247             /* Rotate the diagonals 45 degrees counterclockwise.
3248              * To do this, multiply the matrix /+h +h\ with the
3249              * vector (x y).                   \-h +h/
3250              * h = sqrt(0.5). We can set h := 1 since absolute
3251              * distance doesn't matter here. */
3252             tx = his_cx + his_cy;
3253             his_cy = -his_cx + his_cy;
3254             his_cx = tx;
3255         }
3256
3257         switch(dir) {
3258         case OB_DIRECTION_NORTH:
3259         case OB_DIRECTION_SOUTH:
3260         case OB_DIRECTION_NORTHEAST:
3261         case OB_DIRECTION_SOUTHWEST:
3262             offset = (his_cx < 0) ? -his_cx : his_cx;
3263             distance = ((dir == OB_DIRECTION_NORTH ||
3264                          dir == OB_DIRECTION_NORTHEAST) ?
3265                         -his_cy : his_cy);
3266             break;
3267         case OB_DIRECTION_EAST:
3268         case OB_DIRECTION_WEST:
3269         case OB_DIRECTION_SOUTHEAST:
3270         case OB_DIRECTION_NORTHWEST:
3271             offset = (his_cy < 0) ? -his_cy : his_cy;
3272             distance = ((dir == OB_DIRECTION_WEST ||
3273                          dir == OB_DIRECTION_NORTHWEST) ?
3274                         -his_cx : his_cx);
3275             break;
3276         }
3277
3278         /* the target must be in the requested direction */
3279         if(distance <= 0)
3280             continue;
3281
3282         /* Calculate score for this window.  The smaller the better. */
3283         score = distance + offset;
3284
3285         /* windows more than 45 degrees off the direction are
3286          * heavily penalized and will only be chosen if nothing
3287          * else within a million pixels */
3288         if(offset > distance)
3289             score += 1000000;
3290
3291         if(best_score == -1 || score < best_score)
3292             best_client = cur,
3293                 best_score = score;
3294     }
3295
3296     return best_client;
3297 }
3298
3299 void client_set_layer(ObClient *self, gint layer)
3300 {
3301     if (layer < 0) {
3302         self->below = TRUE;
3303         self->above = FALSE;
3304     } else if (layer == 0) {
3305         self->below = self->above = FALSE;
3306     } else {
3307         self->below = FALSE;
3308         self->above = TRUE;
3309     }
3310     client_calc_layer(self);
3311     client_change_state(self); /* reflect this in the state hints */
3312 }
3313
3314 void client_set_undecorated(ObClient *self, gboolean undecorated)
3315 {
3316     if (self->undecorated != undecorated) {
3317         self->undecorated = undecorated;
3318         client_setup_decor_and_functions(self);
3319         /* Make sure the client knows it might have moved. Maybe there is a
3320          * better way of doing this so only one client_configure is sent, but
3321          * since 125 of these are sent per second when moving the window (with
3322          * user = FALSE) i doubt it matters much.
3323          */
3324         client_configure(self, OB_CORNER_TOPLEFT, self->area.x, self->area.y,
3325                          self->area.width, self->area.height, TRUE, TRUE);
3326         client_change_state(self); /* reflect this in the state hints */
3327     }
3328 }
3329
3330 guint client_monitor(ObClient *self)
3331 {
3332     return screen_find_monitor(&self->frame->area);
3333 }
3334
3335 ObClient *client_search_top_parent(ObClient *self)
3336 {
3337     while (self->transient_for && self->transient_for != OB_TRAN_GROUP)
3338         self = self->transient_for;
3339     return self;
3340 }
3341
3342 GSList *client_search_all_top_parents(ObClient *self)
3343 {
3344     GSList *ret = NULL;
3345
3346     /* move up the direct transient chain as far as possible */
3347     while (self->transient_for && self->transient_for != OB_TRAN_GROUP)
3348         self = self->transient_for;
3349
3350     if (!self->transient_for)
3351         ret = g_slist_prepend(ret, self);
3352     else {
3353             GSList *it;
3354
3355             g_assert(self->group);
3356
3357             for (it = self->group->members; it; it = g_slist_next(it)) {
3358                 ObClient *c = it->data;
3359
3360                 if (!c->transient_for)
3361                     ret = g_slist_prepend(ret, c);
3362             }
3363
3364             if (ret == NULL) /* no group parents */
3365                 ret = g_slist_prepend(ret, self);
3366     }
3367
3368     return ret;
3369 }
3370
3371 ObClient *client_search_focus_parent(ObClient *self)
3372 {
3373     if (self->transient_for) {
3374         if (self->transient_for != OB_TRAN_GROUP) {
3375             if (client_focused(self->transient_for))
3376                 return self->transient_for;
3377         } else {
3378             GSList *it;
3379
3380             for (it = self->group->members; it; it = g_slist_next(it)) {
3381                 ObClient *c = it->data;
3382
3383                 /* checking transient_for prevents infinate loops! */
3384                 if (c != self && !c->transient_for)
3385                     if (client_focused(c))
3386                         return c;
3387             }
3388         }
3389     }
3390
3391     return NULL;
3392 }
3393
3394 ObClient *client_search_parent(ObClient *self, ObClient *search)
3395 {
3396     if (self->transient_for) {
3397         if (self->transient_for != OB_TRAN_GROUP) {
3398             if (self->transient_for == search)
3399                 return search;
3400         } else {
3401             GSList *it;
3402
3403             for (it = self->group->members; it; it = g_slist_next(it)) {
3404                 ObClient *c = it->data;
3405
3406                 /* checking transient_for prevents infinate loops! */
3407                 if (c != self && !c->transient_for)
3408                     if (c == search)
3409                         return search;
3410             }
3411         }
3412     }
3413
3414     return NULL;
3415 }
3416
3417 ObClient *client_search_transient(ObClient *self, ObClient *search)
3418 {
3419     GSList *sit;
3420
3421     for (sit = self->transients; sit; sit = g_slist_next(sit)) {
3422         if (sit->data == search)
3423             return search;
3424         if (client_search_transient(sit->data, search))
3425             return search;
3426     }
3427     return NULL;
3428 }
3429
3430 void client_update_sm_client_id(ObClient *self)
3431 {
3432     g_free(self->sm_client_id);
3433     self->sm_client_id = NULL;
3434
3435     if (!PROP_GETS(self->window, sm_client_id, locale, &self->sm_client_id) &&
3436         self->group)
3437         PROP_GETS(self->group->leader, sm_client_id, locale,
3438                   &self->sm_client_id);
3439 }
3440
3441 #define WANT_EDGE(cur, c) \
3442             if(cur == c)                                                      \
3443                 continue;                                                     \
3444             if(!client_normal(cur))                                   \
3445                 continue;                                                     \
3446             if(screen_desktop != cur->desktop && cur->desktop != DESKTOP_ALL) \
3447                 continue;                                                     \
3448             if(cur->iconic)                                                   \
3449                 continue;                                                     \
3450             if(cur->layer < c->layer && !config_resist_layers_below)          \
3451                 continue;
3452
3453 #define HIT_EDGE(my_edge_start, my_edge_end, his_edge_start, his_edge_end) \
3454             if ((his_edge_start >= my_edge_start && \
3455                  his_edge_start <= my_edge_end) ||  \
3456                 (my_edge_start >= his_edge_start && \
3457                  my_edge_start <= his_edge_end))    \
3458                 dest = his_offset;
3459
3460 /* finds the nearest edge in the given direction from the current client
3461  * note to self: the edge is the -frame- edge (the actual one), not the
3462  * client edge.
3463  */
3464 gint client_directional_edge_search(ObClient *c, ObDirection dir, gboolean hang)
3465 {
3466     gint dest, monitor_dest;
3467     gint my_edge_start, my_edge_end, my_offset;
3468     GList *it;
3469     Rect *a, *monitor;
3470     
3471     if(!client_list)
3472         return -1;
3473
3474     a = screen_area(c->desktop);
3475     monitor = screen_area_monitor(c->desktop, client_monitor(c));
3476
3477     switch(dir) {
3478     case OB_DIRECTION_NORTH:
3479         my_edge_start = c->frame->area.x;
3480         my_edge_end = c->frame->area.x + c->frame->area.width;
3481         my_offset = c->frame->area.y + (hang ? c->frame->area.height : 0);
3482         
3483         /* default: top of screen */
3484         dest = a->y + (hang ? c->frame->area.height : 0);
3485         monitor_dest = monitor->y + (hang ? c->frame->area.height : 0);
3486         /* if the monitor edge comes before the screen edge, */
3487         /* use that as the destination instead. (For xinerama) */
3488         if (monitor_dest != dest && my_offset > monitor_dest)
3489             dest = monitor_dest; 
3490
3491         for(it = client_list; it && my_offset != dest; it = g_list_next(it)) {
3492             gint his_edge_start, his_edge_end, his_offset;
3493             ObClient *cur = it->data;
3494
3495             WANT_EDGE(cur, c)
3496
3497             his_edge_start = cur->frame->area.x;
3498             his_edge_end = cur->frame->area.x + cur->frame->area.width;
3499             his_offset = cur->frame->area.y + 
3500                          (hang ? 0 : cur->frame->area.height);
3501
3502             if(his_offset + 1 > my_offset)
3503                 continue;
3504
3505             if(his_offset < dest)
3506                 continue;
3507
3508             HIT_EDGE(my_edge_start, my_edge_end, his_edge_start, his_edge_end)
3509         }
3510         break;
3511     case OB_DIRECTION_SOUTH:
3512         my_edge_start = c->frame->area.x;
3513         my_edge_end = c->frame->area.x + c->frame->area.width;
3514         my_offset = c->frame->area.y + (hang ? 0 : c->frame->area.height);
3515
3516         /* default: bottom of screen */
3517         dest = a->y + a->height - (hang ? c->frame->area.height : 0);
3518         monitor_dest = monitor->y + monitor->height -
3519                        (hang ? c->frame->area.height : 0);
3520         /* if the monitor edge comes before the screen edge, */
3521         /* use that as the destination instead. (For xinerama) */
3522         if (monitor_dest != dest && my_offset < monitor_dest)
3523             dest = monitor_dest; 
3524
3525         for(it = client_list; it && my_offset != dest; it = g_list_next(it)) {
3526             gint his_edge_start, his_edge_end, his_offset;
3527             ObClient *cur = it->data;
3528
3529             WANT_EDGE(cur, c)
3530
3531             his_edge_start = cur->frame->area.x;
3532             his_edge_end = cur->frame->area.x + cur->frame->area.width;
3533             his_offset = cur->frame->area.y +
3534                          (hang ? cur->frame->area.height : 0);
3535
3536
3537             if(his_offset - 1 < my_offset)
3538                 continue;
3539             
3540             if(his_offset > dest)
3541                 continue;
3542
3543             HIT_EDGE(my_edge_start, my_edge_end, his_edge_start, his_edge_end)
3544         }
3545         break;
3546     case OB_DIRECTION_WEST:
3547         my_edge_start = c->frame->area.y;
3548         my_edge_end = c->frame->area.y + c->frame->area.height;
3549         my_offset = c->frame->area.x + (hang ? c->frame->area.width : 0);
3550
3551         /* default: leftmost egde of screen */
3552         dest = a->x + (hang ? c->frame->area.width : 0);
3553         monitor_dest = monitor->x + (hang ? c->frame->area.width : 0);
3554         /* if the monitor edge comes before the screen edge, */
3555         /* use that as the destination instead. (For xinerama) */
3556         if (monitor_dest != dest && my_offset > monitor_dest)
3557             dest = monitor_dest;            
3558
3559         for(it = client_list; it && my_offset != dest; it = g_list_next(it)) {
3560             gint his_edge_start, his_edge_end, his_offset;
3561             ObClient *cur = it->data;
3562
3563             WANT_EDGE(cur, c)
3564
3565             his_edge_start = cur->frame->area.y;
3566             his_edge_end = cur->frame->area.y + cur->frame->area.height;
3567             his_offset = cur->frame->area.x +
3568                          (hang ? 0 : cur->frame->area.width);
3569
3570             if(his_offset + 1 > my_offset)
3571                 continue;
3572
3573             if(his_offset < dest)
3574                 continue;
3575
3576             HIT_EDGE(my_edge_start, my_edge_end, his_edge_start, his_edge_end)
3577         }
3578        break;
3579     case OB_DIRECTION_EAST:
3580         my_edge_start = c->frame->area.y;
3581         my_edge_end = c->frame->area.y + c->frame->area.height;
3582         my_offset = c->frame->area.x + (hang ? 0 : c->frame->area.width);
3583         
3584         /* default: rightmost edge of screen */
3585         dest = a->x + a->width - (hang ? c->frame->area.width : 0);
3586         monitor_dest = monitor->x + monitor->width -
3587                        (hang ? c->frame->area.width : 0);
3588         /* if the monitor edge comes before the screen edge, */
3589         /* use that as the destination instead. (For xinerama) */
3590         if (monitor_dest != dest && my_offset < monitor_dest)
3591             dest = monitor_dest;            
3592
3593         for(it = client_list; it && my_offset != dest; it = g_list_next(it)) {
3594             gint his_edge_start, his_edge_end, his_offset;
3595             ObClient *cur = it->data;
3596
3597             WANT_EDGE(cur, c)
3598
3599             his_edge_start = cur->frame->area.y;
3600             his_edge_end = cur->frame->area.y + cur->frame->area.height;
3601             his_offset = cur->frame->area.x +
3602                          (hang ? cur->frame->area.width : 0);
3603
3604             if(his_offset - 1 < my_offset)
3605                 continue;
3606             
3607             if(his_offset > dest)
3608                 continue;
3609
3610             HIT_EDGE(my_edge_start, my_edge_end, his_edge_start, his_edge_end)
3611         }
3612         break;
3613     case OB_DIRECTION_NORTHEAST:
3614     case OB_DIRECTION_SOUTHEAST:
3615     case OB_DIRECTION_NORTHWEST:
3616     case OB_DIRECTION_SOUTHWEST:
3617         /* not implemented */
3618     default:
3619         g_assert_not_reached();
3620         dest = 0; /* suppress warning */
3621     }
3622     return dest;
3623 }
3624
3625 ObClient* client_under_pointer()
3626 {
3627     gint x, y;
3628     GList *it;
3629     ObClient *ret = NULL;
3630
3631     if (screen_pointer_pos(&x, &y)) {
3632         for (it = stacking_list; it; it = g_list_next(it)) {
3633             if (WINDOW_IS_CLIENT(it->data)) {
3634                 ObClient *c = WINDOW_AS_CLIENT(it->data);
3635                 if (c->frame->visible &&
3636                     RECT_CONTAINS(c->frame->area, x, y)) {
3637                     ret = c;
3638                     break;
3639                 }
3640             }
3641         }
3642     }
3643     return ret;
3644 }
3645
3646 gboolean client_has_group_siblings(ObClient *self)
3647 {
3648     return self->group && self->group->members->next;
3649 }