]> icculus.org git repositories - mikachu/openbox.git/blob - openbox/client.c
set the desktop hint when the window already has a hint but its out of range
[mikachu/openbox.git] / openbox / client.c
1 #include "client.h"
2 #include "dock.h"
3 #include "xerror.h"
4 #include "startup.h"
5 #include "screen.h"
6 #include "moveresize.h"
7 #include "prop.h"
8 #include "extensions.h"
9 #include "frame.h"
10 #include "event.h"
11 #include "grab.h"
12 #include "focus.h"
13 #include "stacking.h"
14 #include "dispatch.h"
15 #include "openbox.h"
16 #include "group.h"
17 #include "config.h"
18 #include "menu.h"
19 #include "render/render.h"
20
21 #include <glib.h>
22 #include <X11/Xutil.h>
23
24 /*! The event mask to grab on client windows */
25 #define CLIENT_EVENTMASK (PropertyChangeMask | FocusChangeMask | \
26                           StructureNotifyMask)
27
28 #define CLIENT_NOPROPAGATEMASK (ButtonPressMask | ButtonReleaseMask | \
29                                 ButtonMotionMask)
30
31 GList      *client_list      = NULL;
32
33 static void client_get_all(Client *self);
34 static void client_toggle_border(Client *self, gboolean show);
35 static void client_get_area(Client *self);
36 static void client_get_desktop(Client *self);
37 static void client_get_state(Client *self);
38 static void client_get_shaped(Client *self);
39 static void client_get_mwm_hints(Client *self);
40 static void client_get_gravity(Client *self);
41 static void client_showhide(Client *self);
42 static void client_change_allowed_actions(Client *self);
43 static void client_change_state(Client *self);
44 static void client_apply_startup_state(Client *self);
45
46 void client_startup()
47 {
48     client_set_list();
49 }
50
51 void client_shutdown()
52 {
53 }
54
55 void client_set_list()
56 {
57     Window *windows, *win_it;
58     GList *it;
59     guint size = g_list_length(client_list);
60
61     /* create an array of the window ids */
62     if (size > 0) {
63         windows = g_new(Window, size);
64         win_it = windows;
65         for (it = client_list; it != NULL; it = it->next, ++win_it)
66             *win_it = ((Client*)it->data)->window;
67     } else
68         windows = NULL;
69
70     PROP_SETA32(ob_root, net_client_list, window, (guint32*)windows, size);
71
72     if (windows)
73         g_free(windows);
74
75     stacking_set_list();
76 }
77
78 /*
79 void client_foreach_transient(Client *self, ClientForeachFunc func, void *data)
80 {
81     GSList *it;
82
83     for (it = self->transients; it; it = it->next) {
84         if (!func(it->data, data)) return;
85         client_foreach_transient(it->data, func, data);
86     }
87 }
88
89 void client_foreach_ancestor(Client *self, ClientForeachFunc func, void *data)
90 {
91     if (self->transient_for) {
92         if (self->transient_for != TRAN_GROUP) {
93             if (!func(self->transient_for, data)) return;
94             client_foreach_ancestor(self->transient_for, func, data);
95         } else {
96             GSList *it;
97
98             for (it = self->group->members; it; it = it->next)
99                 if (it->data != self &&
100                     !((Client*)it->data)->transient_for) {
101                     if (!func(it->data, data)) return;
102                     client_foreach_ancestor(it->data, func, data);
103                 }
104         }
105     }
106 }
107 */
108
109 void client_manage_all()
110 {
111     unsigned int i, j, nchild;
112     Window w, *children;
113     XWMHints *wmhints;
114     XWindowAttributes attrib;
115
116     XQueryTree(ob_display, ob_root, &w, &w, &children, &nchild);
117
118     /* remove all icon windows from the list */
119     for (i = 0; i < nchild; i++) {
120         if (children[i] == None) continue;
121         wmhints = XGetWMHints(ob_display, children[i]);
122         if (wmhints) {
123             if ((wmhints->flags & IconWindowHint) &&
124                 (wmhints->icon_window != children[i]))
125                 for (j = 0; j < nchild; j++)
126                     if (children[j] == wmhints->icon_window) {
127                         children[j] = None;
128                         break;
129                     }
130             XFree(wmhints);
131         }
132     }
133
134     for (i = 0; i < nchild; ++i) {
135         if (children[i] == None)
136             continue;
137         if (XGetWindowAttributes(ob_display, children[i], &attrib)) {
138             if (attrib.override_redirect) continue;
139
140             if (attrib.map_state != IsUnmapped)
141                 client_manage(children[i]);
142         }
143     }
144     XFree(children);
145
146     /* stack them as they were on startup!
147        why with stacking_lower? Why, because then windows who aren't in the
148        stacking list are on the top where you can see them instead of buried
149        at the bottom! */
150     for (i = startup_stack_size; i > 0; --i) {
151         ObWindow *obw;
152
153         w = startup_stack_order[i-1];
154         obw = g_hash_table_lookup(window_map, &w);
155         if (obw) {
156             g_assert(WINDOW_IS_CLIENT(obw));
157             stacking_lower(CLIENT_AS_WINDOW(obw));
158         }
159     }
160     g_free(startup_stack_order);
161     startup_stack_order = NULL;
162     startup_stack_size = 0;
163
164     if (config_focus_new) {
165         ObWindow *active;
166
167         active = g_hash_table_lookup(window_map, &startup_active);
168         if (active) {
169             g_assert(WINDOW_IS_CLIENT(active));
170             if (!client_focus(WINDOW_AS_CLIENT(active)))
171                 focus_fallback(Fallback_NoFocus);
172         } else
173             focus_fallback(Fallback_NoFocus);
174     }
175 }
176
177 void client_manage(Window window)
178 {
179     Client *self;
180     XEvent e;
181     XWindowAttributes attrib;
182     XSetWindowAttributes attrib_set;
183     XWMHints *wmhint;
184     gboolean activate = FALSE;
185
186     grab_server(TRUE);
187
188     /* check if it has already been unmapped by the time we started mapping
189        the grab does a sync so we don't have to here */
190     if (XCheckTypedWindowEvent(ob_display, window, DestroyNotify, &e) ||
191         XCheckTypedWindowEvent(ob_display, window, UnmapNotify, &e)) {
192         XPutBackEvent(ob_display, &e);
193
194         grab_server(FALSE);
195         return; /* don't manage it */
196     }
197
198     /* make sure it isn't an override-redirect window */
199     if (!XGetWindowAttributes(ob_display, window, &attrib) ||
200         attrib.override_redirect) {
201         grab_server(FALSE);
202         return; /* don't manage it */
203     }
204   
205     /* is the window a docking app */
206     if ((wmhint = XGetWMHints(ob_display, window))) {
207         if ((wmhint->flags & StateHint) &&
208             wmhint->initial_state == WithdrawnState) {
209             dock_add(window, wmhint);
210             grab_server(FALSE);
211             XFree(wmhint);
212             return;
213         }
214         XFree(wmhint);
215     }
216
217     g_message("Managing window: %lx", window);
218
219     /* choose the events we want to receive on the CLIENT window */
220     attrib_set.event_mask = CLIENT_EVENTMASK;
221     attrib_set.do_not_propagate_mask = CLIENT_NOPROPAGATEMASK;
222     XChangeWindowAttributes(ob_display, window,
223                             CWEventMask|CWDontPropagate, &attrib_set);
224
225
226     /* create the Client struct, and populate it from the hints on the
227        window */
228     self = g_new(Client, 1);
229     self->obwin.type = Window_Client;
230     self->window = window;
231     client_get_all(self);
232
233     /* remove the client's border (and adjust re gravity) */
234     client_toggle_border(self, FALSE);
235      
236     /* specify that if we exit, the window should not be destroyed and should
237        be reparented back to root automatically */
238     XChangeSaveSet(ob_display, window, SetModeInsert);
239
240     /* create the decoration frame for the client window */
241     self->frame = frame_new();
242
243     frame_grab_client(self->frame, self);
244
245     client_apply_startup_state(self);
246
247     grab_server(FALSE);
248
249     /* add to client list/map */
250     client_list = g_list_append(client_list, self);
251     g_hash_table_insert(window_map, &self->window, self);
252
253     /* update the focus lists */
254     focus_order_add_new(self);
255
256     /* focus the new window? */
257     if (ob_state != State_Starting && config_focus_new &&
258         (self->type == Type_Normal || self->type == Type_Dialog)) {
259         gboolean group_foc = FALSE;
260         
261         if (self->group) {
262             GSList *it;
263
264             for (it = self->group->members; it; it = it->next) {
265                 if (client_focused(it->data)) {
266                     group_foc = TRUE;
267                     break;
268                 }
269             }
270         }
271         /* note the check against Type_Normal/Dialog, not client_normal(self),
272            which would also include other types. in this case we want more
273            strict rules for focus */
274         if ((group_foc ||
275              (!self->transient_for && (!self->group ||
276                                        !self->group->members->next))) ||
277             client_search_focus_tree_full(self) ||
278             !focus_client ||
279             !client_normal(focus_client)) {
280             /* activate the window */
281             stacking_add(CLIENT_AS_WINDOW(self));
282             activate = TRUE;
283         } else {
284             /* try to not get in the way */
285             stacking_add_nonintrusive(CLIENT_AS_WINDOW(self));
286         }
287     } else {
288         stacking_add(CLIENT_AS_WINDOW(self));
289     }
290
291     screen_update_struts();
292
293     dispatch_client(Event_Client_New, self, 0, 0);
294
295     /* make sure the window is visible */
296     client_move_onscreen(self);
297
298     client_showhide(self);
299
300     if (activate) client_activate(self);
301
302     /* update the list hints */
303     client_set_list();
304
305     dispatch_client(Event_Client_Mapped, self, 0, 0);
306
307     g_message("Managed window 0x%lx (%s)", window, self->class);
308 }
309
310 void client_unmanage_all()
311 {
312     while (client_list != NULL)
313         client_unmanage(client_list->data);
314 }
315
316 /* called by client_unmanage() to close any menus referencing this client */
317 void client_close_menus(gpointer key, gpointer value, gpointer self)
318 {
319     if (((Menu *)value)->client == (Client *)self)
320         menu_hide((Menu *)value);
321 }
322
323 void client_unmanage(Client *self)
324 {
325     int j;
326     GSList *it;
327
328     g_message("Unmanaging window: %lx (%s)", self->window, self->class);
329
330     dispatch_client(Event_Client_Destroy, self, 0, 0);
331     g_assert(self != NULL);
332
333     /* remove the window from our save set */
334     XChangeSaveSet(ob_display, self->window, SetModeDelete);
335
336     /* we dont want events no more */
337     XSelectInput(ob_display, self->window, NoEventMask);
338
339     frame_hide(self->frame);
340
341     client_list = g_list_remove(client_list, self);
342     stacking_remove(self);
343     g_hash_table_remove(window_map, &self->window);
344
345     /* update the focus lists */
346     focus_order_remove(self);
347
348     /* once the client is out of the list, update the struts to remove it's
349        influence */
350     screen_update_struts();
351
352     /* tell our parent(s) that we're gone */
353     if (self->transient_for == TRAN_GROUP) { /* transient of group */
354         GSList *it;
355
356         for (it = self->group->members; it; it = it->next)
357             if (it->data != self)
358                 ((Client*)it->data)->transients =
359                     g_slist_remove(((Client*)it->data)->transients, self);
360     } else if (self->transient_for) {        /* transient of window */
361         self->transient_for->transients =
362             g_slist_remove(self->transient_for->transients, self);
363     }
364
365     /* tell our transients that we're gone */
366     for (it = self->transients; it != NULL; it = it->next) {
367         if (((Client*)it->data)->transient_for != TRAN_GROUP) {
368             ((Client*)it->data)->transient_for = NULL;
369             client_calc_layer(it->data);
370         }
371     }
372
373     if (moveresize_client == self)
374         moveresize_end(TRUE);
375
376     /* close any windows that are attached to this window */
377     g_hash_table_foreach(menu_hash, client_close_menus, self);
378
379     
380     if (focus_client == self) {
381         XEvent e;
382
383         /* focus the last focused window on the desktop, and ignore enter
384            events from the unmap so it doesnt mess with the focus */
385         while (XCheckTypedEvent(ob_display, EnterNotify, &e));
386         client_unfocus(self);
387     }
388
389     /* remove from its group */
390     if (self->group) {
391         group_remove(self->group, self);
392         self->group = NULL;
393     }
394
395     /* dispatch the unmapped event */
396     dispatch_client(Event_Client_Unmapped, self, 0, 0);
397     g_assert(self != NULL);
398
399     /* give the client its border back */
400     client_toggle_border(self, TRUE);
401
402     /* reparent the window out of the frame, and free the frame */
403     frame_release_client(self->frame, self);
404     self->frame = NULL;
405      
406     if (ob_state != State_Exiting) {
407         /* these values should not be persisted across a window
408            unmapping/mapping */
409         prop_erase(self->window, prop_atoms.net_wm_desktop);
410         prop_erase(self->window, prop_atoms.net_wm_state);
411     } else {
412         /* if we're left in an iconic state, the client wont be mapped. this is
413            bad, since we will no longer be managing the window on restart */
414         if (self->iconic)
415             XMapWindow(ob_display, self->window);
416     }
417
418
419     g_message("Unmanaged window 0x%lx", self->window);
420
421     /* free all data allocated in the client struct */
422     g_slist_free(self->transients);
423     for (j = 0; j < self->nicons; ++j)
424         g_free(self->icons[j].data);
425     if (self->nicons > 0)
426         g_free(self->icons);
427     g_free(self->title);
428     g_free(self->icon_title);
429     g_free(self->name);
430     g_free(self->class);
431     g_free(self->role);
432     g_free(self);
433      
434     /* update the list hints */
435     client_set_list();
436 }
437
438 void client_move_onscreen(Client *self)
439 {
440     Rect *a;
441     int x = self->frame->area.x, y = self->frame->area.y;
442
443     a = screen_area(self->desktop);
444     if (x >= a->x + a->width - 1)
445         x = a->x + a->width - self->frame->area.width;
446     if (y >= a->y + a->height - 1)
447         y = a->y + a->height - self->frame->area.height;
448     if (x + self->frame->area.width - 1 < a->x)
449         x = a->x;
450     if (y + self->frame->area.height - 1< a->y)
451         y = a->y;
452
453     frame_frame_gravity(self->frame, &x, &y); /* get where the client
454                                                  should be */
455     client_configure(self , Corner_TopLeft, x, y,
456                      self->area.width, self->area.height,
457                      TRUE, TRUE);
458 }
459
460 static void client_toggle_border(Client *self, gboolean show)
461 {
462     /* adjust our idea of where the client is, based on its border. When the
463        border is removed, the client should now be considered to be in a
464        different position.
465        when re-adding the border to the client, the same operation needs to be
466        reversed. */
467     int oldx = self->area.x, oldy = self->area.y;
468     int x = oldx, y = oldy;
469     switch(self->gravity) {
470     default:
471     case NorthWestGravity:
472     case WestGravity:
473     case SouthWestGravity:
474         break;
475     case NorthEastGravity:
476     case EastGravity:
477     case SouthEastGravity:
478         if (show) x -= self->border_width * 2;
479         else      x += self->border_width * 2;
480         break;
481     case NorthGravity:
482     case SouthGravity:
483     case CenterGravity:
484     case ForgetGravity:
485     case StaticGravity:
486         if (show) x -= self->border_width;
487         else      x += self->border_width;
488         break;
489     }
490     switch(self->gravity) {
491     default:
492     case NorthWestGravity:
493     case NorthGravity:
494     case NorthEastGravity:
495         break;
496     case SouthWestGravity:
497     case SouthGravity:
498     case SouthEastGravity:
499         if (show) y -= self->border_width * 2;
500         else      y += self->border_width * 2;
501         break;
502     case WestGravity:
503     case EastGravity:
504     case CenterGravity:
505     case ForgetGravity:
506     case StaticGravity:
507         if (show) y -= self->border_width;
508         else      y += self->border_width;
509         break;
510     }
511     self->area.x = x;
512     self->area.y = y;
513
514     if (show) {
515         XSetWindowBorderWidth(ob_display, self->window, self->border_width);
516
517         /* move the client so it is back it the right spot _with_ its
518            border! */
519         if (x != oldx || y != oldy)
520             XMoveWindow(ob_display, self->window, x, y);
521     } else
522         XSetWindowBorderWidth(ob_display, self->window, 0);
523 }
524
525
526 static void client_get_all(Client *self)
527 {
528     /* update EVERYTHING!! */
529
530     self->ignore_unmaps = 0;
531   
532     /* defaults */
533     self->frame = NULL;
534     self->title = self->icon_title = NULL;
535     self->title_count = 1;
536     self->name = self->class = self->role = NULL;
537     self->wmstate = NormalState;
538     self->transient = FALSE;
539     self->transients = NULL;
540     self->transient_for = NULL;
541     self->layer = -1;
542     self->urgent = FALSE;
543     self->positioned = FALSE;
544     self->disabled_decorations = 0;
545     self->group = NULL;
546     self->nicons = 0;
547
548     client_get_area(self);
549     client_update_transient_for(self);
550     client_update_wmhints(self);
551     client_get_desktop(self);
552     client_get_state(self);
553     client_get_shaped(self);
554
555     client_get_mwm_hints(self);
556     client_get_type(self);/* this can change the mwmhints for special cases */
557
558     client_update_protocols(self);
559
560     client_get_gravity(self); /* get the attribute gravity */
561     client_update_normal_hints(self); /* this may override the attribute
562                                          gravity */
563
564     /* got the type, the mwmhints, the protocols, and the normal hints
565        (min/max sizes), so we're ready to set up the decorations/functions */
566     client_setup_decor_and_functions(self);
567   
568     client_update_title(self);
569     client_update_class(self);
570     client_update_strut(self);
571     client_update_icons(self);
572
573     client_change_state(self);
574 }
575
576 static void client_get_area(Client *self)
577 {
578     XWindowAttributes wattrib;
579     Status ret;
580   
581     ret = XGetWindowAttributes(ob_display, self->window, &wattrib);
582     g_assert(ret != BadWindow);
583
584     RECT_SET(self->area, wattrib.x, wattrib.y, wattrib.width, wattrib.height);
585     self->border_width = wattrib.border_width;
586 }
587
588 static void client_get_desktop(Client *self)
589 {
590     guint32 d = screen_num_desktops; /* an always-invalid value */
591
592     if (PROP_GET32(self->window, net_wm_desktop, cardinal, &d)) {
593         if (d >= screen_num_desktops && d != DESKTOP_ALL)
594             self->desktop = screen_num_desktops - 1;
595         else
596             self->desktop = d;
597     } else { 
598         gboolean trdesk = FALSE;
599
600        if (self->transient_for) {
601            if (self->transient_for != TRAN_GROUP) {
602                 self->desktop = self->transient_for->desktop;
603                 trdesk = TRUE;
604             } else {
605                 GSList *it;
606
607                 for (it = self->group->members; it; it = it->next)
608                     if (it->data != self &&
609                         !((Client*)it->data)->transient_for) {
610                         self->desktop = ((Client*)it->data)->desktop;
611                         trdesk = TRUE;
612                         break;
613                     }
614             }
615        }
616        if (!trdesk)
617            /* defaults to the current desktop */
618            self->desktop = screen_desktop;
619
620     }
621     if (self->desktop != d) {
622         /* set the desktop hint, to make sure that it always exists */
623         PROP_SET32(self->window, net_wm_desktop, cardinal, self->desktop);
624     }
625 }
626
627 static void client_get_state(Client *self)
628 {
629     guint32 *state;
630     guint num;
631   
632     self->modal = self->shaded = self->max_horz = self->max_vert =
633         self->fullscreen = self->above = self->below = self->iconic =
634         self->skip_taskbar = self->skip_pager = FALSE;
635
636     if (PROP_GETA32(self->window, net_wm_state, atom, &state, &num)) {
637         gulong i;
638         for (i = 0; i < num; ++i) {
639             if (state[i] == prop_atoms.net_wm_state_modal)
640                 self->modal = TRUE;
641             else if (state[i] == prop_atoms.net_wm_state_shaded)
642                 self->shaded = TRUE;
643             else if (state[i] == prop_atoms.net_wm_state_hidden)
644                 self->iconic = TRUE;
645             else if (state[i] == prop_atoms.net_wm_state_skip_taskbar)
646                 self->skip_taskbar = TRUE;
647             else if (state[i] == prop_atoms.net_wm_state_skip_pager)
648                 self->skip_pager = TRUE;
649             else if (state[i] == prop_atoms.net_wm_state_fullscreen)
650                 self->fullscreen = TRUE;
651             else if (state[i] == prop_atoms.net_wm_state_maximized_vert)
652                 self->max_vert = TRUE;
653             else if (state[i] == prop_atoms.net_wm_state_maximized_horz)
654                 self->max_horz = TRUE;
655             else if (state[i] == prop_atoms.net_wm_state_above)
656                 self->above = TRUE;
657             else if (state[i] == prop_atoms.net_wm_state_below)
658                 self->below = TRUE;
659         }
660
661         g_free(state);
662     }
663 }
664
665 static void client_get_shaped(Client *self)
666 {
667     self->shaped = FALSE;
668 #ifdef   SHAPE
669     if (extensions_shape) {
670         int foo;
671         guint ufoo;
672         int s;
673
674         XShapeSelectInput(ob_display, self->window, ShapeNotifyMask);
675
676         XShapeQueryExtents(ob_display, self->window, &s, &foo,
677                            &foo, &ufoo, &ufoo, &foo, &foo, &foo, &ufoo,
678                            &ufoo);
679         self->shaped = (s != 0);
680     }
681 #endif
682 }
683
684 void client_update_transient_for(Client *self)
685 {
686     Window t = None;
687     Client *c = NULL;
688
689     if (XGetTransientForHint(ob_display, self->window, &t)) {
690         self->transient = TRUE;
691         if (t != self->window) { /* cant be transient to itself! */
692             c = g_hash_table_lookup(window_map, &t);
693             /* if this happens then we need to check for it*/
694             g_assert(c != self);
695             g_assert(!c || WINDOW_IS_CLIENT(c));
696             
697             if (!c && self->group) {
698                 /* not transient to a client, see if it is transient for a
699                    group */
700                 if (t == self->group->leader ||
701                     t == None ||
702                     t == ob_root) {
703                     /* window is a transient for its group! */
704                     c = TRAN_GROUP;
705                 }
706             }
707         }
708     } else
709         self->transient = FALSE;
710
711     /* if anything has changed... */
712     if (c != self->transient_for) {
713         if (self->transient_for == TRAN_GROUP) { /* transient of group */
714             GSList *it;
715
716             /* remove from old parents */
717             for (it = self->group->members; it; it = it->next)
718                 if (it->data != self &&
719                     !((Client*)it->data)->transient_for)
720                     ((Client*)it->data)->transients =
721                         g_slist_remove(((Client*)it->data)->transients, self);
722         } else if (self->transient_for != NULL) { /* transient of window */
723             /* remove from old parent */
724             self->transient_for->transients =
725                 g_slist_remove(self->transient_for->transients, self);
726         }
727         self->transient_for = c;
728         if (self->transient_for == TRAN_GROUP) { /* transient of group */
729             GSList *it;
730
731             /* add to new parents */
732             for (it = self->group->members; it; it = it->next)
733                 if (it->data != self &&
734                     !((Client*)it->data)->transient_for)
735                     ((Client*)it->data)->transients =
736                         g_slist_append(((Client*)it->data)->transients, self);
737
738             /* remove all transients which are in the group, that causes
739                circlular pointer hell of doom */
740             for (it = self->group->members; it; it = it->next) {
741                 GSList *sit, *next;
742                 for (sit = self->transients; sit; sit = next) {
743                     next = sit->next;
744                     if (sit->data == it->data)
745                         self->transients = g_slist_remove(self->transients,
746                                                           sit->data);
747                 }
748             }
749         } else if (self->transient_for != NULL) { /* transient of window */
750             /* add to new parent */
751             self->transient_for->transients =
752                 g_slist_append(self->transient_for->transients, self);
753         }
754     }
755 }
756
757 static void client_get_mwm_hints(Client *self)
758 {
759     guint num;
760     guint32 *hints;
761
762     self->mwmhints.flags = 0; /* default to none */
763
764     if (PROP_GETA32(self->window, motif_wm_hints, motif_wm_hints,
765                     &hints, &num)) {
766         if (num >= MWM_ELEMENTS) {
767             self->mwmhints.flags = hints[0];
768             self->mwmhints.functions = hints[1];
769             self->mwmhints.decorations = hints[2];
770         }
771         g_free(hints);
772     }
773 }
774
775 void client_get_type(Client *self)
776 {
777     guint num, i;
778     guint32 *val;
779
780     self->type = -1;
781   
782     if (PROP_GETA32(self->window, net_wm_window_type, atom, &val, &num)) {
783         /* use the first value that we know about in the array */
784         for (i = 0; i < num; ++i) {
785             if (val[i] == prop_atoms.net_wm_window_type_desktop)
786                 self->type = Type_Desktop;
787             else if (val[i] == prop_atoms.net_wm_window_type_dock)
788                 self->type = Type_Dock;
789             else if (val[i] == prop_atoms.net_wm_window_type_toolbar)
790                 self->type = Type_Toolbar;
791             else if (val[i] == prop_atoms.net_wm_window_type_menu)
792                 self->type = Type_Menu;
793             else if (val[i] == prop_atoms.net_wm_window_type_utility)
794                 self->type = Type_Utility;
795             else if (val[i] == prop_atoms.net_wm_window_type_splash)
796                 self->type = Type_Splash;
797             else if (val[i] == prop_atoms.net_wm_window_type_dialog)
798                 self->type = Type_Dialog;
799             else if (val[i] == prop_atoms.net_wm_window_type_normal)
800                 self->type = Type_Normal;
801             else if (val[i] == prop_atoms.kde_net_wm_window_type_override) {
802                 /* prevent this window from getting any decor or
803                    functionality */
804                 self->mwmhints.flags &= (MwmFlag_Functions |
805                                          MwmFlag_Decorations);
806                 self->mwmhints.decorations = 0;
807                 self->mwmhints.functions = 0;
808             }
809             if (self->type != (WindowType) -1)
810                 break; /* grab the first legit type */
811         }
812         g_free(val);
813     }
814     
815     if (self->type == (WindowType) -1) {
816         /*the window type hint was not set, which means we either classify
817           ourself as a normal window or a dialog, depending on if we are a
818           transient. */
819         if (self->transient)
820             self->type = Type_Dialog;
821         else
822             self->type = Type_Normal;
823     }
824 }
825
826 void client_update_protocols(Client *self)
827 {
828     guint32 *proto;
829     guint num_return, i;
830
831     self->focus_notify = FALSE;
832     self->delete_window = FALSE;
833
834     if (PROP_GETA32(self->window, wm_protocols, atom, &proto, &num_return)) {
835         for (i = 0; i < num_return; ++i) {
836             if (proto[i] == prop_atoms.wm_delete_window) {
837                 /* this means we can request the window to close */
838                 self->delete_window = TRUE;
839             } else if (proto[i] == prop_atoms.wm_take_focus)
840                 /* if this protocol is requested, then the window will be
841                    notified whenever we want it to receive focus */
842                 self->focus_notify = TRUE;
843         }
844         g_free(proto);
845     }
846 }
847
848 static void client_get_gravity(Client *self)
849 {
850     XWindowAttributes wattrib;
851     Status ret;
852
853     ret = XGetWindowAttributes(ob_display, self->window, &wattrib);
854     g_assert(ret != BadWindow);
855     self->gravity = wattrib.win_gravity;
856 }
857
858 void client_update_normal_hints(Client *self)
859 {
860     XSizeHints size;
861     long ret;
862     int oldgravity = self->gravity;
863
864     /* defaults */
865     self->min_ratio = 0.0f;
866     self->max_ratio = 0.0f;
867     SIZE_SET(self->size_inc, 1, 1);
868     SIZE_SET(self->base_size, 0, 0);
869     SIZE_SET(self->min_size, 0, 0);
870     SIZE_SET(self->max_size, G_MAXINT, G_MAXINT);
871
872     /* get the hints from the window */
873     if (XGetWMNormalHints(ob_display, self->window, &size, &ret)) {
874         self->positioned = !!(size.flags & (PPosition|USPosition));
875
876         if (size.flags & PWinGravity) {
877             self->gravity = size.win_gravity;
878       
879             /* if the client has a frame, i.e. has already been mapped and
880                is changing its gravity */
881             if (self->frame && self->gravity != oldgravity) {
882                 /* move our idea of the client's position based on its new
883                    gravity */
884                 self->area.x = self->frame->area.x;
885                 self->area.y = self->frame->area.y;
886                 frame_frame_gravity(self->frame, &self->area.x, &self->area.y);
887             }
888         }
889
890         if (size.flags & PAspect) {
891             if (size.min_aspect.y)
892                 self->min_ratio = (float)size.min_aspect.x / size.min_aspect.y;
893             if (size.max_aspect.y)
894                 self->max_ratio = (float)size.max_aspect.x / size.max_aspect.y;
895         }
896
897         if (size.flags & PMinSize)
898             SIZE_SET(self->min_size, size.min_width, size.min_height);
899     
900         if (size.flags & PMaxSize)
901             SIZE_SET(self->max_size, size.max_width, size.max_height);
902     
903         if (size.flags & PBaseSize)
904             SIZE_SET(self->base_size, size.base_width, size.base_height);
905     
906         if (size.flags & PResizeInc)
907             SIZE_SET(self->size_inc, size.width_inc, size.height_inc);
908     }
909 }
910
911 void client_setup_decor_and_functions(Client *self)
912 {
913     /* start with everything (cept fullscreen) */
914     self->decorations = Decor_Titlebar | Decor_Handle | Decor_Border |
915         Decor_Icon | Decor_AllDesktops | Decor_Iconify | Decor_Maximize |
916         Decor_Shade;
917     self->functions = Func_Resize | Func_Move | Func_Iconify | Func_Maximize |
918         Func_Shade;
919     if (self->delete_window) {
920         self->decorations |= Decor_Close;
921         self->functions |= Func_Close;
922     }
923
924     if (!(self->min_size.width < self->max_size.width ||
925           self->min_size.height < self->max_size.height)) {
926         self->decorations &= ~(Decor_Maximize | Decor_Handle);
927         self->functions &= ~(Func_Resize | Func_Maximize);
928     }
929
930     switch (self->type) {
931     case Type_Normal:
932         /* normal windows retain all of the possible decorations and
933            functionality, and are the only windows that you can fullscreen */
934         self->functions |= Func_Fullscreen;
935         break;
936
937     case Type_Dialog:
938     case Type_Utility:
939         /* these windows cannot be maximized */
940         self->decorations &= ~Decor_Maximize;
941         self->functions &= ~Func_Maximize;
942         break;
943
944     case Type_Menu:
945     case Type_Toolbar:
946         /* these windows get less functionality */
947         self->decorations &= ~(Decor_Iconify | Decor_Handle);
948         self->functions &= ~(Func_Iconify | Func_Resize);
949         break;
950
951     case Type_Desktop:
952     case Type_Dock:
953     case Type_Splash:
954         /* none of these windows are manipulated by the window manager */
955         self->decorations = 0;
956         self->functions = 0;
957         break;
958     }
959
960     /* Mwm Hints are applied subtractively to what has already been chosen for
961        decor and functionality */
962     if (self->mwmhints.flags & MwmFlag_Decorations) {
963         if (! (self->mwmhints.decorations & MwmDecor_All)) {
964             if (! (self->mwmhints.decorations & MwmDecor_Border))
965                 self->decorations &= ~Decor_Border;
966             if (! (self->mwmhints.decorations & MwmDecor_Handle))
967                 self->decorations &= ~Decor_Handle;
968             if (! (self->mwmhints.decorations & MwmDecor_Title))
969                 self->decorations &= ~Decor_Titlebar;
970             if (! (self->mwmhints.decorations & MwmDecor_Iconify))
971                 self->decorations &= ~Decor_Iconify;
972             if (! (self->mwmhints.decorations & MwmDecor_Maximize))
973                 self->decorations &= ~Decor_Maximize;
974         }
975     }
976
977     if (self->mwmhints.flags & MwmFlag_Functions) {
978         if (! (self->mwmhints.functions & MwmFunc_All)) {
979             if (! (self->mwmhints.functions & MwmFunc_Resize))
980                 self->functions &= ~Func_Resize;
981             if (! (self->mwmhints.functions & MwmFunc_Move))
982                 self->functions &= ~Func_Move;
983             if (! (self->mwmhints.functions & MwmFunc_Iconify))
984                 self->functions &= ~Func_Iconify;
985             if (! (self->mwmhints.functions & MwmFunc_Maximize))
986                 self->functions &= ~Func_Maximize;
987             /* dont let mwm hints kill the close button
988                if (! (self->mwmhints.functions & MwmFunc_Close))
989                self->functions &= ~Func_Close; */
990         }
991     }
992
993     /* can't maximize without moving/resizing */
994     if (!((self->functions & Func_Move) && (self->functions & Func_Resize)))
995         self->functions &= ~(Func_Maximize | Func_Fullscreen);
996
997     /* finally, user specified disabled decorations are applied to subtract
998        decorations */
999     if (self->disabled_decorations & Decor_Titlebar)
1000         self->decorations &= ~Decor_Titlebar;
1001     if (self->disabled_decorations & Decor_Handle)
1002         self->decorations &= ~Decor_Handle;
1003     if (self->disabled_decorations & Decor_Border)
1004         self->decorations &= ~Decor_Border;
1005     if (self->disabled_decorations & Decor_Iconify)
1006         self->decorations &= ~Decor_Iconify;
1007     if (self->disabled_decorations & Decor_Maximize)
1008         self->decorations &= ~Decor_Maximize;
1009     if (self->disabled_decorations & Decor_AllDesktops)
1010         self->decorations &= ~Decor_AllDesktops;
1011     if (self->disabled_decorations & Decor_Shade)
1012         self->decorations &= ~Decor_Shade;
1013     if (self->disabled_decorations & Decor_Close)
1014         self->decorations &= ~Decor_Close;
1015
1016     /* if we don't have a titlebar, then we cannot shade! */
1017     if (!(self->decorations & Decor_Titlebar))
1018         self->functions &= ~Func_Shade;
1019
1020     /* now we need to check against rules for the client's current state */
1021     if (self->fullscreen) {
1022         self->functions &= (Func_Close | Func_Fullscreen | Func_Iconify);
1023         self->decorations = 0;
1024     }
1025
1026     client_change_allowed_actions(self);
1027
1028     if (self->frame) {
1029         /* this makes sure that these windows appear on all desktops */
1030         if (self->type == Type_Desktop && self->desktop != DESKTOP_ALL)
1031             client_set_desktop(self, DESKTOP_ALL, FALSE);
1032
1033         /* adjust the client's decorations, etc. */
1034         client_reconfigure(self);
1035     } else {
1036         /* this makes sure that these windows appear on all desktops */
1037         if (self->type == Type_Desktop && self->desktop != DESKTOP_ALL)
1038             self->desktop = DESKTOP_ALL;
1039     }
1040 }
1041
1042 static void client_change_allowed_actions(Client *self)
1043 {
1044     guint32 actions[9];
1045     int num = 0;
1046
1047     /* desktop windows are kept on all desktops */
1048     if (self->type != Type_Desktop)
1049         actions[num++] = prop_atoms.net_wm_action_change_desktop;
1050
1051     if (self->functions & Func_Shade)
1052         actions[num++] = prop_atoms.net_wm_action_shade;
1053     if (self->functions & Func_Close)
1054         actions[num++] = prop_atoms.net_wm_action_close;
1055     if (self->functions & Func_Move)
1056         actions[num++] = prop_atoms.net_wm_action_move;
1057     if (self->functions & Func_Iconify)
1058         actions[num++] = prop_atoms.net_wm_action_minimize;
1059     if (self->functions & Func_Resize)
1060         actions[num++] = prop_atoms.net_wm_action_resize;
1061     if (self->functions & Func_Fullscreen)
1062         actions[num++] = prop_atoms.net_wm_action_fullscreen;
1063     if (self->functions & Func_Maximize) {
1064         actions[num++] = prop_atoms.net_wm_action_maximize_horz;
1065         actions[num++] = prop_atoms.net_wm_action_maximize_vert;
1066     }
1067
1068     PROP_SETA32(self->window, net_wm_allowed_actions, atom, actions, num);
1069
1070     /* make sure the window isn't breaking any rules now */
1071
1072     if (!(self->functions & Func_Shade) && self->shaded) {
1073         if (self->frame) client_shade(self, FALSE);
1074         else self->shaded = FALSE;
1075     }
1076     if (!(self->functions & Func_Iconify) && self->iconic) {
1077         g_message("UNSETTING ICONIC");
1078         if (self->frame) client_iconify(self, FALSE, TRUE);
1079         else self->iconic = FALSE;
1080     }
1081     if (!(self->functions & Func_Fullscreen) && self->fullscreen) {
1082         if (self->frame) client_fullscreen(self, FALSE, TRUE);
1083         else self->fullscreen = FALSE;
1084     }
1085     if (!(self->functions & Func_Maximize) && (self->max_horz ||
1086                                                self->max_vert)) {
1087         if (self->frame) client_maximize(self, FALSE, 0, TRUE);
1088         else self->max_vert = self->max_horz = FALSE;
1089     }
1090 }
1091
1092 void client_reconfigure(Client *self)
1093 {
1094     /* by making this pass FALSE for user, we avoid the emacs event storm where
1095        every configurenotify causes an update in its normal hints, i think this
1096        is generally what we want anyways... */
1097     client_configure(self, Corner_TopLeft, self->area.x, self->area.y,
1098                      self->area.width, self->area.height, FALSE, TRUE);
1099 }
1100
1101 void client_update_wmhints(Client *self)
1102 {
1103     XWMHints *hints;
1104     gboolean ur = FALSE;
1105     GSList *it;
1106
1107     /* assume a window takes input if it doesnt specify */
1108     self->can_focus = TRUE;
1109   
1110     if ((hints = XGetWMHints(ob_display, self->window)) != NULL) {
1111         if (hints->flags & InputHint)
1112             self->can_focus = hints->input;
1113
1114         /* only do this when first managing the window *AND* when we aren't
1115            starting up! */
1116         if (ob_state != State_Starting && self->frame == NULL)
1117             if (hints->flags & StateHint)
1118                 self->iconic = hints->initial_state == IconicState;
1119
1120         if (hints->flags & XUrgencyHint)
1121             ur = TRUE;
1122
1123         if (!(hints->flags & WindowGroupHint))
1124             hints->window_group = None;
1125
1126         /* did the group state change? */
1127         if (hints->window_group !=
1128             (self->group ? self->group->leader : None)) {
1129             /* remove from the old group if there was one */
1130             if (self->group != NULL) {
1131                 /* remove transients of the group */
1132                 for (it = self->group->members; it; it = it->next)
1133                     self->transients = g_slist_remove(self->transients,
1134                                                       it->data);
1135                 group_remove(self->group, self);
1136                 self->group = NULL;
1137             }
1138             if (hints->window_group != None) {
1139                 self->group = group_add(hints->window_group, self);
1140
1141                 /* i can only have transients from the group if i am not
1142                    transient myself */
1143                 if (!self->transient_for) {
1144                     /* add other transients of the group that are already
1145                        set up */
1146                     for (it = self->group->members; it; it = it->next)
1147                         if (it->data != self &&
1148                             ((Client*)it->data)->transient_for == TRAN_GROUP)
1149                             self->transients = g_slist_append(self->transients,
1150                                                               it->data);
1151                 }
1152             }
1153
1154             /* the WM_HINTS can contain an icon */
1155             client_update_icons(self);
1156
1157             /* because the self->transient flag wont change from this call,
1158                we don't need to update the window's type and such, only its
1159                transient_for, and the transients lists of other windows in
1160                the group may be affected */
1161             client_update_transient_for(self);
1162         }
1163
1164         XFree(hints);
1165     }
1166
1167     if (ur != self->urgent) {
1168         self->urgent = ur;
1169         g_message("Urgent Hint for 0x%lx: %s", self->window,
1170                   ur ? "ON" : "OFF");
1171         /* fire the urgent callback if we're mapped, otherwise, wait until
1172            after we're mapped */
1173         if (self->frame)
1174             dispatch_client(Event_Client_Urgent, self, self->urgent, 0);
1175     }
1176 }
1177
1178 void client_update_title(Client *self)
1179 {
1180     GList *it;
1181     guint32 nums;
1182     guint i;
1183     char *data = NULL;
1184     gboolean read_title;
1185
1186     g_free(self->title);
1187      
1188     /* try netwm */
1189     if (!PROP_GETS(self->window, net_wm_name, utf8, &data))
1190         /* try old x stuff */
1191         if (!PROP_GETS(self->window, wm_name, locale, &data))
1192             data = g_strdup("Unnamed Window");
1193
1194     /* look for duplicates and append a number */
1195     nums = 0;
1196     for (it = client_list; it; it = it->next)
1197         if (it->data != self) {
1198             Client *c = it->data;
1199             if (0 == strncmp(c->title, data, strlen(data)))
1200                 nums |= 1 << c->title_count;
1201         }
1202     /* find first free number */
1203     for (i = 1; i <= 32; ++i)
1204         if (!(nums & (1 << i))) {
1205             if (self->title_count == 1 || i == 1)
1206                 self->title_count = i;
1207             break;
1208         }
1209     /* dont display the number for the first window */
1210     if (self->title_count > 1) {
1211         char *vdata, *ndata;
1212         ndata = g_strdup_printf(" - [%u]", self->title_count);
1213         vdata = g_strconcat(data, ndata, NULL);
1214         g_free(ndata);
1215         g_free(data);
1216         data = vdata;
1217     }
1218
1219     PROP_SETS(self->window, net_wm_visible_name, data);
1220
1221     self->title = data;
1222
1223     if (self->frame)
1224         frame_adjust_title(self->frame);
1225
1226     /* update the icon title */
1227     data = NULL;
1228     g_free(self->icon_title);
1229
1230     read_title = TRUE;
1231     /* try netwm */
1232     if (!PROP_GETS(self->window, net_wm_icon_name, utf8, &data))
1233         /* try old x stuff */
1234         if (!PROP_GETS(self->window, wm_icon_name, locale, &data)) {
1235             data = g_strdup(self->title);
1236             read_title = FALSE;
1237         }
1238
1239     /* append the title count, dont display the number for the first window */
1240     if (read_title && self->title_count > 1) {
1241         char *vdata, *ndata;
1242         ndata = g_strdup_printf(" - [%u]", self->title_count);
1243         vdata = g_strconcat(data, ndata, NULL);
1244         g_free(ndata);
1245         g_free(data);
1246         data = vdata;
1247     }
1248
1249     PROP_SETS(self->window, net_wm_visible_icon_name, data);
1250
1251     self->icon_title = data;
1252 }
1253
1254 void client_update_class(Client *self)
1255 {
1256     char **data;
1257     char *s;
1258
1259     if (self->name) g_free(self->name);
1260     if (self->class) g_free(self->class);
1261     if (self->role) g_free(self->role);
1262
1263     self->name = self->class = self->role = NULL;
1264
1265     if (PROP_GETSS(self->window, wm_class, locale, &data)) {
1266         if (data[0]) {
1267             self->name = g_strdup(data[0]);
1268             if (data[1])
1269                 self->class = g_strdup(data[1]);
1270         }
1271         g_strfreev(data);     
1272     }
1273
1274     if (PROP_GETS(self->window, wm_window_role, locale, &s))
1275         self->role = g_strdup(s);
1276
1277     if (self->name == NULL) self->name = g_strdup("");
1278     if (self->class == NULL) self->class = g_strdup("");
1279     if (self->role == NULL) self->role = g_strdup("");
1280 }
1281
1282 void client_update_strut(Client *self)
1283 {
1284     guint num;
1285     guint32 *data;
1286
1287     if (!PROP_GETA32(self->window, net_wm_strut, cardinal, &data, &num)) {
1288         STRUT_SET(self->strut, 0, 0, 0, 0);
1289     } else {
1290         if (num == 4)
1291             STRUT_SET(self->strut, data[0], data[2], data[1], data[3]);
1292         else
1293             STRUT_SET(self->strut, 0, 0, 0, 0);
1294         g_free(data);
1295     }
1296
1297     /* updating here is pointless while we're being mapped cuz we're not in
1298        the client list yet */
1299     if (self->frame)
1300         screen_update_struts();
1301 }
1302
1303 void client_update_icons(Client *self)
1304 {
1305     guint num;
1306     guint32 *data;
1307     guint w, h, i;
1308     int j;
1309
1310     for (j = 0; j < self->nicons; ++j)
1311         g_free(self->icons[j].data);
1312     if (self->nicons > 0)
1313         g_free(self->icons);
1314     self->nicons = 0;
1315
1316     if (PROP_GETA32(self->window, net_wm_icon, cardinal, &data, &num)) {
1317         /* figure out how many valid icons are in here */
1318         i = 0;
1319         while (num - i > 2) {
1320             w = data[i++];
1321             h = data[i++];
1322             i += w * h;
1323             if (i > num || w*h == 0) break;
1324             ++self->nicons;
1325         }
1326
1327         self->icons = g_new(Icon, self->nicons);
1328     
1329         /* store the icons */
1330         i = 0;
1331         for (j = 0; j < self->nicons; ++j) {
1332             guint x, y, t;
1333
1334             w = self->icons[j].width = data[i++];
1335             h = self->icons[j].height = data[i++];
1336
1337             if (w*h == 0) continue;
1338
1339             self->icons[j].data = g_new(RrPixel32, w * h);
1340             for (x = 0, y = 0, t = 0; t < w * h; ++t, ++x, ++i) {
1341                 if (x >= w) {
1342                     x = 0;
1343                     ++y;
1344                 }
1345                 self->icons[j].data[t] =
1346                     (((data[i] >> 24) & 0xff) << RrDefaultAlphaOffset) +
1347                     (((data[i] >> 16) & 0xff) << RrDefaultRedOffset) +
1348                     (((data[i] >> 8) & 0xff) << RrDefaultGreenOffset) +
1349                     (((data[i] >> 0) & 0xff) << RrDefaultBlueOffset);
1350             }
1351             g_assert(i <= num);
1352         }
1353
1354         g_free(data);
1355     } else if (PROP_GETA32(self->window, kwm_win_icon,
1356                            kwm_win_icon, &data, &num)) {
1357         if (num == 2) {
1358             self->nicons++;
1359             self->icons = g_new(Icon, self->nicons);
1360             xerror_set_ignore(TRUE);
1361             if (!RrPixmapToRGBA(ob_rr_inst,
1362                                 data[0], data[1],
1363                                 &self->icons[self->nicons-1].width,
1364                                 &self->icons[self->nicons-1].height,
1365                                 &self->icons[self->nicons-1].data)) {
1366                 g_free(&self->icons[self->nicons-1]);
1367                 self->nicons--;
1368             }
1369             xerror_set_ignore(FALSE);
1370         }
1371         g_free(data);
1372     } else {
1373         XWMHints *hints;
1374
1375         if ((hints = XGetWMHints(ob_display, self->window))) {
1376             if (hints->flags & IconPixmapHint) {
1377                 self->nicons++;
1378                 self->icons = g_new(Icon, self->nicons);
1379                 xerror_set_ignore(TRUE);
1380                 if (!RrPixmapToRGBA(ob_rr_inst,
1381                                     hints->icon_pixmap,
1382                                     (hints->flags & IconMaskHint ?
1383                                      hints->icon_mask : None),
1384                                     &self->icons[self->nicons-1].width,
1385                                     &self->icons[self->nicons-1].height,
1386                                     &self->icons[self->nicons-1].data)){
1387                     g_free(&self->icons[self->nicons-1]);
1388                     self->nicons--;
1389                 }
1390                 xerror_set_ignore(FALSE);
1391             }
1392             XFree(hints);
1393         }
1394     }
1395
1396     if (self->frame)
1397         frame_adjust_icon(self->frame);
1398 }
1399
1400 static void client_change_state(Client *self)
1401 {
1402     guint32 state[2];
1403     guint32 netstate[10];
1404     guint num;
1405
1406     state[0] = self->wmstate;
1407     state[1] = None;
1408     PROP_SETA32(self->window, wm_state, wm_state, state, 2);
1409
1410     num = 0;
1411     if (self->modal)
1412         netstate[num++] = prop_atoms.net_wm_state_modal;
1413     if (self->shaded)
1414         netstate[num++] = prop_atoms.net_wm_state_shaded;
1415     if (self->iconic)
1416         netstate[num++] = prop_atoms.net_wm_state_hidden;
1417     if (self->skip_taskbar)
1418         netstate[num++] = prop_atoms.net_wm_state_skip_taskbar;
1419     if (self->skip_pager)
1420         netstate[num++] = prop_atoms.net_wm_state_skip_pager;
1421     if (self->fullscreen)
1422         netstate[num++] = prop_atoms.net_wm_state_fullscreen;
1423     if (self->max_vert)
1424         netstate[num++] = prop_atoms.net_wm_state_maximized_vert;
1425     if (self->max_horz)
1426         netstate[num++] = prop_atoms.net_wm_state_maximized_horz;
1427     if (self->above)
1428         netstate[num++] = prop_atoms.net_wm_state_above;
1429     if (self->below)
1430         netstate[num++] = prop_atoms.net_wm_state_below;
1431     PROP_SETA32(self->window, net_wm_state, atom, netstate, num);
1432
1433     client_calc_layer(self);
1434
1435     if (self->frame)
1436         frame_adjust_state(self->frame);
1437 }
1438
1439 Client *client_search_focus_tree(Client *self)
1440 {
1441     GSList *it;
1442     Client *ret;
1443
1444     for (it = self->transients; it != NULL; it = it->next) {
1445         if (client_focused(it->data)) return it->data;
1446         if ((ret = client_search_focus_tree(it->data))) return ret;
1447     }
1448     return NULL;
1449 }
1450
1451 Client *client_search_focus_tree_full(Client *self)
1452 {
1453     if (self->transient_for) {
1454         if (self->transient_for != TRAN_GROUP) {
1455             return client_search_focus_tree_full(self->transient_for);
1456         } else {
1457             GSList *it;
1458             gboolean recursed = FALSE;
1459         
1460             for (it = self->group->members; it; it = it->next)
1461                 if (!((Client*)it->data)->transient_for) {
1462                     Client *c;
1463                     if ((c = client_search_focus_tree_full(it->data)))
1464                         return c;
1465                     recursed = TRUE;
1466                 }
1467             if (recursed)
1468               return NULL;
1469         }
1470     }
1471
1472     /* this function checks the whole tree, the client_search_focus_tree~
1473        does not, so we need to check this window */
1474     if (client_focused(self))
1475       return self;
1476     return client_search_focus_tree(self);
1477 }
1478
1479 static StackLayer calc_layer(Client *self)
1480 {
1481     StackLayer l;
1482
1483     if (self->fullscreen) l = Layer_Fullscreen;
1484     else if (self->type == Type_Desktop) l = Layer_Desktop;
1485     else if (self->type == Type_Dock) {
1486         if (!self->below) l = Layer_Top;
1487         else l = Layer_Normal;
1488     }
1489     else if (self->above) l = Layer_Above;
1490     else if (self->below) l = Layer_Below;
1491     else l = Layer_Normal;
1492
1493     return l;
1494 }
1495
1496 static void calc_recursive(Client *self, Client *orig, StackLayer l,
1497                            gboolean raised)
1498 {
1499     StackLayer old, own;
1500     GSList *it;
1501
1502     old = self->layer;
1503     own = calc_layer(self);
1504     self->layer = l > own ? l : own;
1505
1506     for (it = self->transients; it; it = it->next)
1507         calc_recursive(it->data, orig, l, raised ? raised : l != old);
1508
1509     if (!raised && l != old)
1510         if (orig->frame) { /* only restack if the original window is managed */
1511             /* XXX add_non_intrusive ever? */
1512             stacking_remove(CLIENT_AS_WINDOW(self));
1513             stacking_add(CLIENT_AS_WINDOW(self));
1514         }
1515 }
1516
1517 void client_calc_layer(Client *self)
1518 {
1519     StackLayer l;
1520     Client *orig;
1521
1522     orig = self;
1523
1524     /* transients take on the layer of their parents */
1525     if (self->transient_for) {
1526         if (self->transient_for != TRAN_GROUP) {
1527             self = self->transient_for;
1528         } else {
1529             GSList *it;
1530
1531             for (it = self->group->members; it; it = it->next)
1532                 if (it->data != self &&
1533                     !((Client*)it->data)->transient_for) {
1534                     self = it->data;
1535                     break;
1536                 }
1537         }
1538     }
1539
1540     l = calc_layer(self);
1541
1542     calc_recursive(self, orig, l, FALSE);
1543 }
1544
1545 gboolean client_should_show(Client *self)
1546 {
1547     if (self->iconic) return FALSE;
1548     else if (!(self->desktop == screen_desktop ||
1549                self->desktop == DESKTOP_ALL)) return FALSE;
1550     else if (client_normal(self) && screen_showing_desktop) return FALSE;
1551     
1552     return TRUE;
1553 }
1554
1555 static void client_showhide(Client *self)
1556 {
1557
1558     if (client_should_show(self))
1559         frame_show(self->frame);
1560     else
1561         frame_hide(self->frame);
1562 }
1563
1564 gboolean client_normal(Client *self) {
1565     return ! (self->type == Type_Desktop || self->type == Type_Dock ||
1566               self->type == Type_Splash);
1567 }
1568
1569 static void client_apply_startup_state(Client *self)
1570 {
1571     /* these are in a carefully crafted order.. */
1572
1573     if (self->iconic) {
1574         self->iconic = FALSE;
1575         client_iconify(self, TRUE, FALSE);
1576     }
1577     if (self->fullscreen) {
1578         self->fullscreen = FALSE;
1579         client_fullscreen(self, TRUE, FALSE);
1580     }
1581     if (self->shaded) {
1582         self->shaded = FALSE;
1583         client_shade(self, TRUE);
1584     }
1585     if (self->urgent)
1586         dispatch_client(Event_Client_Urgent, self, self->urgent, 0);
1587   
1588     if (self->max_vert && self->max_horz) {
1589         self->max_vert = self->max_horz = FALSE;
1590         client_maximize(self, TRUE, 0, FALSE);
1591     } else if (self->max_vert) {
1592         self->max_vert = FALSE;
1593         client_maximize(self, TRUE, 2, FALSE);
1594     } else if (self->max_horz) {
1595         self->max_horz = FALSE;
1596         client_maximize(self, TRUE, 1, FALSE);
1597     }
1598
1599     /* nothing to do for the other states:
1600        skip_taskbar
1601        skip_pager
1602        modal
1603        above
1604        below
1605     */
1606 }
1607
1608 void client_configure(Client *self, Corner anchor, int x, int y, int w, int h,
1609                       gboolean user, gboolean final)
1610 {
1611     gboolean moved = FALSE, resized = FALSE;
1612
1613     /* gets the frame's position */
1614     frame_client_gravity(self->frame, &x, &y);
1615
1616     /* these positions are frame positions, not client positions */
1617
1618     /* set the size and position if fullscreen */
1619     if (self->fullscreen) {
1620 #ifdef VIDMODE
1621         int dot;
1622         XF86VidModeModeLine mode;
1623
1624         if (XF86VidModeGetModeLine(ob_display, ob_screen, &dot, &mode)) {
1625             w = mode.hdisplay;
1626             h = mode.vdisplay;
1627             if (mode.privsize) XFree(mode.private);
1628         } else {
1629 #else
1630             w = screen_physical_size.width;
1631             h = screen_physical_size.height;
1632 #endif
1633 #ifdef VIDMODE
1634         }
1635         if (!XF86VidModeGetViewPort(ob_display, ob_screen, &x, &y)) {
1636             x = y = 0;
1637 #endif
1638         }
1639         user = FALSE; /* ignore that increment etc shit when in fullscreen */
1640     } else {
1641         /* set the size and position if maximized */
1642         if (self->max_horz) {
1643             x = screen_area(self->desktop)->x - self->frame->size.left;
1644             w = screen_area(self->desktop)->width;
1645         }
1646         if (self->max_vert) {
1647             y = screen_area(self->desktop)->y;
1648             h = screen_area(self->desktop)->height -
1649                 self->frame->size.top - self->frame->size.bottom;
1650         }
1651     }
1652
1653     /* gets the client's position */
1654     frame_frame_gravity(self->frame, &x, &y);
1655
1656     /* these override the above states! if you cant move you can't move! */
1657     if (user) {
1658         if (!(self->functions & Func_Move)) {
1659             x = self->area.x;
1660             y = self->area.y;
1661         }
1662         if (!(self->functions & Func_Resize)) {
1663             w = self->area.width;
1664             h = self->area.height;
1665         }
1666     }
1667
1668     if (!(w == self->area.width && h == self->area.height)) {
1669         int basew, baseh, minw, minh;
1670
1671         /* base size is substituted with min size if not specified */
1672         if (self->base_size.width || self->base_size.height) {
1673             basew = self->base_size.width;
1674             baseh = self->base_size.height;
1675         } else {
1676             basew = self->min_size.width;
1677             baseh = self->min_size.height;
1678         }
1679         /* min size is substituted with base size if not specified */
1680         if (self->min_size.width || self->min_size.height) {
1681             minw = self->min_size.width;
1682             minh = self->min_size.height;
1683         } else {
1684             minw = self->base_size.width;
1685             minh = self->base_size.height;
1686         }
1687
1688         if (user) {
1689             /* for interactive resizing. have to move half an increment in each
1690                direction. */
1691
1692             /* how far we are towards the next size inc */
1693             int mw = (w - basew) % self->size_inc.width; 
1694             int mh = (h - baseh) % self->size_inc.height;
1695             /* amount to add */
1696             int aw = self->size_inc.width / 2;
1697             int ah = self->size_inc.height / 2;
1698             /* don't let us move into a new size increment */
1699             if (mw + aw >= self->size_inc.width)
1700                 aw = self->size_inc.width - mw - 1;
1701             if (mh + ah >= self->size_inc.height)
1702                 ah = self->size_inc.height - mh - 1;
1703             w += aw;
1704             h += ah;
1705     
1706             /* if this is a user-requested resize, then check against min/max
1707                sizes */
1708
1709             /* smaller than min size or bigger than max size? */
1710             if (w > self->max_size.width) w = self->max_size.width;
1711             if (w < minw) w = minw;
1712             if (h > self->max_size.height) h = self->max_size.height;
1713             if (h < minh) h = minh;
1714         }
1715
1716         w -= basew;
1717         h -= baseh;
1718
1719         /* keep to the increments */
1720         w /= self->size_inc.width;
1721         h /= self->size_inc.height;
1722
1723         /* you cannot resize to nothing */
1724         if (w < 1) w = 1;
1725         if (h < 1) h = 1;
1726   
1727         /* store the logical size */
1728         SIZE_SET(self->logical_size, w, h);
1729
1730         w *= self->size_inc.width;
1731         h *= self->size_inc.height;
1732
1733         w += basew;
1734         h += baseh;
1735
1736         if (user) {
1737             /* adjust the height to match the width for the aspect ratios.
1738              for this, min size is not substituted for base size ever. */
1739             w -= self->base_size.width;
1740             h -= self->base_size.height;
1741
1742             if (self->min_ratio)
1743                 if (h * self->min_ratio > w) h = (int)(w / self->min_ratio);
1744             if (self->max_ratio)
1745                 if (h * self->max_ratio < w) h = (int)(w / self->max_ratio);
1746
1747             w += self->base_size.width;
1748             h += self->base_size.height;
1749         }
1750     }
1751
1752     switch (anchor) {
1753     case Corner_TopLeft:
1754         break;
1755     case Corner_TopRight:
1756         x -= w - self->area.width;
1757         break;
1758     case Corner_BottomLeft:
1759         y -= h - self->area.height;
1760         break;
1761     case Corner_BottomRight:
1762         x -= w - self->area.width;
1763         y -= h - self->area.height;
1764         break;
1765     }
1766
1767     moved = x != self->area.x || y != self->area.y;
1768     resized = w != self->area.width || h != self->area.height;
1769
1770     RECT_SET(self->area, x, y, w, h);
1771
1772     /* for app-requested resizes, always resize if 'resized' is true.
1773        for user-requested ones, only resize if final is true, or when
1774        resizing in opaque mode */
1775     if ((!user && resized) ||
1776         (user && (final || (resized && config_opaque_resize))))
1777         XResizeWindow(ob_display, self->window, w, h);
1778
1779     /* move/resize the frame to match the request */
1780     if (self->frame) {
1781         if (self->decorations != self->frame->decorations)
1782             moved = resized = TRUE;
1783
1784         if (moved || resized)
1785             frame_adjust_area(self->frame, moved, resized);
1786
1787         /* If you send this and the client hasn't changed you end up with buggy
1788            clients (emacs) freaking out, cuz they send back a configure every
1789            time they receive this event, which resends them this event... etc.
1790         */
1791         if ((!user && moved) || (user && final)) {
1792             XEvent event;
1793             event.type = ConfigureNotify;
1794             event.xconfigure.display = ob_display;
1795             event.xconfigure.event = self->window;
1796             event.xconfigure.window = self->window;
1797     
1798             /* root window real coords */
1799             event.xconfigure.x = self->frame->area.x + self->frame->size.left;
1800             event.xconfigure.y = self->frame->area.y + self->frame->size.top;
1801     
1802             event.xconfigure.width = w;
1803             event.xconfigure.height = h;
1804             event.xconfigure.border_width = 0;
1805             event.xconfigure.above = self->frame->plate;
1806             event.xconfigure.override_redirect = FALSE;
1807             XSendEvent(event.xconfigure.display, event.xconfigure.window,
1808                        FALSE, StructureNotifyMask, &event);
1809         }
1810     }
1811 }
1812
1813 void client_fullscreen(Client *self, gboolean fs, gboolean savearea)
1814 {
1815     int x, y, w, h;
1816
1817     if (!(self->functions & Func_Fullscreen) || /* can't */
1818         self->fullscreen == fs) return;         /* already done */
1819
1820     self->fullscreen = fs;
1821     client_change_state(self); /* change the state hints on the client,
1822                                   and adjust out layer/stacking */
1823
1824     if (fs) {
1825         if (savearea) {
1826             guint32 dimensions[4];
1827             dimensions[0] = self->area.x;
1828             dimensions[1] = self->area.y;
1829             dimensions[2] = self->area.width;
1830             dimensions[3] = self->area.height;
1831   
1832             PROP_SETA32(self->window, openbox_premax, cardinal,
1833                         dimensions, 4);
1834         }
1835
1836         /* these are not actually used cuz client_configure will set them
1837            as appropriate when the window is fullscreened */
1838         x = y = w = h = 0;
1839     } else {
1840         guint num;
1841         gint32 *dimensions;
1842
1843         /* pick some fallbacks... */
1844         x = screen_area(self->desktop)->x +
1845             screen_area(self->desktop)->width / 4;
1846         y = screen_area(self->desktop)->y +
1847             screen_area(self->desktop)->height / 4;
1848         w = screen_area(self->desktop)->width / 2;
1849         h = screen_area(self->desktop)->height / 2;
1850
1851         if (PROP_GETA32(self->window, openbox_premax, cardinal,
1852                         (guint32**)&dimensions, &num)) {
1853             if (num == 4) {
1854                 x = dimensions[0];
1855                 y = dimensions[1];
1856                 w = dimensions[2];
1857                 h = dimensions[3];
1858             }
1859             g_free(dimensions);
1860         }
1861     }
1862
1863     client_setup_decor_and_functions(self);
1864
1865     client_configure(self, Corner_TopLeft, x, y, w, h, TRUE, TRUE);
1866
1867     /* try focus us when we go into fullscreen mode */
1868     client_focus(self);
1869 }
1870
1871 void client_iconify(Client *self, gboolean iconic, gboolean curdesk)
1872 {
1873     GSList *it;
1874
1875     /* move up the transient chain as far as possible first */
1876     if (self->transient_for) {
1877         if (self->transient_for != TRAN_GROUP) {
1878             if (self->transient_for->iconic != iconic) {
1879                 client_iconify(self->transient_for, iconic, curdesk);
1880                 return;
1881             }
1882         } else {
1883             GSList *it;
1884
1885             for (it = self->group->members; it; it = it->next) {
1886                 Client *c = it->data;
1887                 if (c != self && c->iconic != iconic &&
1888                     !c->transient_for) {
1889                     client_iconify(it->data, iconic, curdesk);
1890                     break;
1891                 }
1892             }
1893             if (it != NULL) return;
1894         }
1895     }
1896
1897     if (self->iconic == iconic) return; /* nothing to do */
1898
1899     g_message("%sconifying window: 0x%lx", (iconic ? "I" : "Uni"),
1900               self->window);
1901
1902     self->iconic = iconic;
1903
1904     if (iconic) {
1905         self->wmstate = IconicState;
1906         self->ignore_unmaps++;
1907         /* we unmap the client itself so that we can get MapRequest events,
1908            and because the ICCCM tells us to! */
1909         XUnmapWindow(ob_display, self->window);
1910
1911         /* update the focus lists.. iconic windows go to the bottom of the
1912          list, put the new iconic window at the 'top of the bottom'. */
1913         focus_order_to_top(self);
1914     } else {
1915         if (curdesk)
1916             client_set_desktop(self, screen_desktop, FALSE);
1917         self->wmstate = self->shaded ? IconicState : NormalState;
1918         XMapWindow(ob_display, self->window);
1919
1920         /* this puts it after the current focused window */
1921         focus_order_remove(self);
1922         focus_order_add_new(self);
1923
1924         /* this is here cuz with the VIDMODE extension, the viewport can change
1925            while a fullscreen window is iconic, and when it uniconifies, it
1926            would be nice if it did so to the new position of the viewport */
1927         client_reconfigure(self);
1928     }
1929     client_change_state(self);
1930     client_showhide(self);
1931     screen_update_struts();
1932
1933     dispatch_client(iconic ? Event_Client_Unmapped : Event_Client_Mapped,
1934                     self, 0, 0);
1935
1936     /* iconify all transients */
1937     for (it = self->transients; it != NULL; it = it->next)
1938         if (it->data != self) client_iconify(it->data, iconic, curdesk);
1939 }
1940
1941 void client_maximize(Client *self, gboolean max, int dir, gboolean savearea)
1942 {
1943     int x, y, w, h;
1944      
1945     g_assert(dir == 0 || dir == 1 || dir == 2);
1946     if (!(self->functions & Func_Maximize)) return; /* can't */
1947
1948     /* check if already done */
1949     if (max) {
1950         if (dir == 0 && self->max_horz && self->max_vert) return;
1951         if (dir == 1 && self->max_horz) return;
1952         if (dir == 2 && self->max_vert) return;
1953     } else {
1954         if (dir == 0 && !self->max_horz && !self->max_vert) return;
1955         if (dir == 1 && !self->max_horz) return;
1956         if (dir == 2 && !self->max_vert) return;
1957     }
1958
1959     /* work with the frame's coords */
1960     x = self->frame->area.x;
1961     y = self->frame->area.y;
1962     w = self->area.width;
1963     h = self->area.height;
1964
1965     if (max) {
1966         if (savearea) {
1967             gint32 dimensions[4];
1968             gint32 *readdim;
1969             guint num;
1970
1971             dimensions[0] = x;
1972             dimensions[1] = y;
1973             dimensions[2] = w;
1974             dimensions[3] = h;
1975
1976             /* get the property off the window and use it for the dimensions
1977                we are already maxed on */
1978             if (PROP_GETA32(self->window, openbox_premax, cardinal,
1979                             (guint32**)&readdim, &num)) {
1980                 if (num == 4) {
1981                     if (self->max_horz) {
1982                         dimensions[0] = readdim[0];
1983                         dimensions[2] = readdim[2];
1984                     }
1985                     if (self->max_vert) {
1986                         dimensions[1] = readdim[1];
1987                         dimensions[3] = readdim[3];
1988                     }
1989                 }
1990                 g_free(readdim);
1991             }
1992
1993             PROP_SETA32(self->window, openbox_premax, cardinal,
1994                         (guint32*)dimensions, 4);
1995         }
1996     } else {
1997         guint num;
1998         gint32 *dimensions;
1999
2000         /* pick some fallbacks... */
2001         if (dir == 0 || dir == 1) { /* horz */
2002             x = screen_area(self->desktop)->x +
2003                 screen_area(self->desktop)->width / 4;
2004             w = screen_area(self->desktop)->width / 2;
2005         }
2006         if (dir == 0 || dir == 2) { /* vert */
2007             y = screen_area(self->desktop)->y +
2008                 screen_area(self->desktop)->height / 4;
2009             h = screen_area(self->desktop)->height / 2;
2010         }
2011
2012         if (PROP_GETA32(self->window, openbox_premax, cardinal,
2013                         (guint32**)&dimensions, &num)) {
2014             if (num == 4) {
2015                 if (dir == 0 || dir == 1) { /* horz */
2016                     x = dimensions[0];
2017                     w = dimensions[2];
2018                 }
2019                 if (dir == 0 || dir == 2) { /* vert */
2020                     y = dimensions[1];
2021                     h = dimensions[3];
2022                 }
2023             }
2024             g_free(dimensions);
2025         }
2026     }
2027
2028     if (dir == 0 || dir == 1) /* horz */
2029         self->max_horz = max;
2030     if (dir == 0 || dir == 2) /* vert */
2031         self->max_vert = max;
2032
2033     if (!self->max_horz && !self->max_vert)
2034         PROP_ERASE(self->window, openbox_premax);
2035
2036     client_change_state(self); /* change the state hints on the client */
2037
2038     /* figure out where the client should be going */
2039     frame_frame_gravity(self->frame, &x, &y);
2040     client_configure(self, Corner_TopLeft, x, y, w, h, TRUE, TRUE);
2041 }
2042
2043 void client_shade(Client *self, gboolean shade)
2044 {
2045     if ((!(self->functions & Func_Shade) && shade) || /* can't shade */
2046         self->shaded == shade) return;     /* already done */
2047
2048     /* when we're iconic, don't change the wmstate */
2049     if (!self->iconic)
2050         self->wmstate = shade ? IconicState : NormalState;
2051     self->shaded = shade;
2052     client_change_state(self);
2053     /* resize the frame to just the titlebar */
2054     frame_adjust_area(self->frame, FALSE, FALSE);
2055 }
2056
2057 void client_close(Client *self)
2058 {
2059     XEvent ce;
2060
2061     if (!(self->functions & Func_Close)) return;
2062
2063     /*
2064       XXX: itd be cool to do timeouts and shit here for killing the client's
2065       process off
2066       like... if the window is around after 5 seconds, then the close button
2067       turns a nice red, and if this function is called again, the client is
2068       explicitly killed.
2069     */
2070
2071     ce.xclient.type = ClientMessage;
2072     ce.xclient.message_type =  prop_atoms.wm_protocols;
2073     ce.xclient.display = ob_display;
2074     ce.xclient.window = self->window;
2075     ce.xclient.format = 32;
2076     ce.xclient.data.l[0] = prop_atoms.wm_delete_window;
2077     ce.xclient.data.l[1] = event_lasttime;
2078     ce.xclient.data.l[2] = 0l;
2079     ce.xclient.data.l[3] = 0l;
2080     ce.xclient.data.l[4] = 0l;
2081     XSendEvent(ob_display, self->window, FALSE, NoEventMask, &ce);
2082 }
2083
2084 void client_kill(Client *self)
2085 {
2086     XKillClient(ob_display, self->window);
2087 }
2088
2089 void client_set_desktop(Client *self, guint target, gboolean donthide)
2090 {
2091     guint old;
2092
2093     if (target == self->desktop) return;
2094   
2095     g_message("Setting desktop %u", target+1);
2096
2097     g_assert(target < screen_num_desktops || target == DESKTOP_ALL);
2098
2099     /* remove from the old desktop(s) */
2100     focus_order_remove(self);
2101
2102     old = self->desktop;
2103     self->desktop = target;
2104     PROP_SET32(self->window, net_wm_desktop, cardinal, target);
2105     /* the frame can display the current desktop state */
2106     frame_adjust_state(self->frame);
2107     /* 'move' the window to the new desktop */
2108     if (!donthide)
2109         client_showhide(self);
2110     /* raise if it was not already on the desktop */
2111     if (old != DESKTOP_ALL)
2112         stacking_raise(CLIENT_AS_WINDOW(self));
2113     screen_update_struts();
2114
2115     /* add to the new desktop(s) */
2116     if (config_focus_new)
2117         focus_order_to_top(self);
2118     else
2119         focus_order_to_bottom(self);
2120
2121     dispatch_client(Event_Client_Desktop, self, target, old);
2122 }
2123
2124 Client *client_search_modal_child(Client *self)
2125 {
2126     GSList *it;
2127     Client *ret;
2128   
2129     for (it = self->transients; it != NULL; it = it->next) {
2130         Client *c = it->data;
2131         if ((ret = client_search_modal_child(c))) return ret;
2132         if (c->modal) return c;
2133     }
2134     return NULL;
2135 }
2136
2137 gboolean client_validate(Client *self)
2138 {
2139     XEvent e; 
2140
2141     XSync(ob_display, FALSE); /* get all events on the server */
2142
2143     if (XCheckTypedWindowEvent(ob_display, self->window, DestroyNotify, &e) ||
2144         XCheckTypedWindowEvent(ob_display, self->window, UnmapNotify, &e)) {
2145         XPutBackEvent(ob_display, &e);
2146         return FALSE;
2147     }
2148
2149     return TRUE;
2150 }
2151
2152 void client_set_wm_state(Client *self, long state)
2153 {
2154     if (state == self->wmstate) return; /* no change */
2155   
2156     switch (state) {
2157     case IconicState:
2158         client_iconify(self, TRUE, TRUE);
2159         break;
2160     case NormalState:
2161         client_iconify(self, FALSE, TRUE);
2162         break;
2163     }
2164 }
2165
2166 void client_set_state(Client *self, Atom action, long data1, long data2)
2167 {
2168     gboolean shaded = self->shaded;
2169     gboolean fullscreen = self->fullscreen;
2170     gboolean max_horz = self->max_horz;
2171     gboolean max_vert = self->max_vert;
2172     int i;
2173
2174     if (!(action == prop_atoms.net_wm_state_add ||
2175           action == prop_atoms.net_wm_state_remove ||
2176           action == prop_atoms.net_wm_state_toggle))
2177         /* an invalid action was passed to the client message, ignore it */
2178         return; 
2179
2180     for (i = 0; i < 2; ++i) {
2181         Atom state = i == 0 ? data1 : data2;
2182     
2183         if (!state) continue;
2184
2185         /* if toggling, then pick whether we're adding or removing */
2186         if (action == prop_atoms.net_wm_state_toggle) {
2187             if (state == prop_atoms.net_wm_state_modal)
2188                 action = self->modal ? prop_atoms.net_wm_state_remove :
2189                     prop_atoms.net_wm_state_add;
2190             else if (state == prop_atoms.net_wm_state_maximized_vert)
2191                 action = self->max_vert ? prop_atoms.net_wm_state_remove :
2192                     prop_atoms.net_wm_state_add;
2193             else if (state == prop_atoms.net_wm_state_maximized_horz)
2194                 action = self->max_horz ? prop_atoms.net_wm_state_remove :
2195                     prop_atoms.net_wm_state_add;
2196             else if (state == prop_atoms.net_wm_state_shaded)
2197                 action = self->shaded ? prop_atoms.net_wm_state_remove :
2198                     prop_atoms.net_wm_state_add;
2199             else if (state == prop_atoms.net_wm_state_skip_taskbar)
2200                 action = self->skip_taskbar ?
2201                     prop_atoms.net_wm_state_remove :
2202                     prop_atoms.net_wm_state_add;
2203             else if (state == prop_atoms.net_wm_state_skip_pager)
2204                 action = self->skip_pager ?
2205                     prop_atoms.net_wm_state_remove :
2206                     prop_atoms.net_wm_state_add;
2207             else if (state == prop_atoms.net_wm_state_fullscreen)
2208                 action = self->fullscreen ?
2209                     prop_atoms.net_wm_state_remove :
2210                     prop_atoms.net_wm_state_add;
2211             else if (state == prop_atoms.net_wm_state_above)
2212                 action = self->above ? prop_atoms.net_wm_state_remove :
2213                     prop_atoms.net_wm_state_add;
2214             else if (state == prop_atoms.net_wm_state_below)
2215                 action = self->below ? prop_atoms.net_wm_state_remove :
2216                     prop_atoms.net_wm_state_add;
2217         }
2218     
2219         if (action == prop_atoms.net_wm_state_add) {
2220             if (state == prop_atoms.net_wm_state_modal) {
2221                 /* XXX raise here or something? */
2222                 self->modal = TRUE;
2223             } else if (state == prop_atoms.net_wm_state_maximized_vert) {
2224                 max_vert = TRUE;
2225             } else if (state == prop_atoms.net_wm_state_maximized_horz) {
2226                 max_horz = TRUE;
2227             } else if (state == prop_atoms.net_wm_state_shaded) {
2228                 shaded = TRUE;
2229             } else if (state == prop_atoms.net_wm_state_skip_taskbar) {
2230                 self->skip_taskbar = TRUE;
2231             } else if (state == prop_atoms.net_wm_state_skip_pager) {
2232                 self->skip_pager = TRUE;
2233             } else if (state == prop_atoms.net_wm_state_fullscreen) {
2234                 fullscreen = TRUE;
2235             } else if (state == prop_atoms.net_wm_state_above) {
2236                 self->above = TRUE;
2237             } else if (state == prop_atoms.net_wm_state_below) {
2238                 self->below = TRUE;
2239             }
2240
2241         } else { /* action == prop_atoms.net_wm_state_remove */
2242             if (state == prop_atoms.net_wm_state_modal) {
2243                 self->modal = FALSE;
2244             } else if (state == prop_atoms.net_wm_state_maximized_vert) {
2245                 max_vert = FALSE;
2246             } else if (state == prop_atoms.net_wm_state_maximized_horz) {
2247                 max_horz = FALSE;
2248             } else if (state == prop_atoms.net_wm_state_shaded) {
2249                 shaded = FALSE;
2250             } else if (state == prop_atoms.net_wm_state_skip_taskbar) {
2251                 self->skip_taskbar = FALSE;
2252             } else if (state == prop_atoms.net_wm_state_skip_pager) {
2253                 self->skip_pager = FALSE;
2254             } else if (state == prop_atoms.net_wm_state_fullscreen) {
2255                 fullscreen = FALSE;
2256             } else if (state == prop_atoms.net_wm_state_above) {
2257                 self->above = FALSE;
2258             } else if (state == prop_atoms.net_wm_state_below) {
2259                 self->below = FALSE;
2260             }
2261         }
2262     }
2263     if (max_horz != self->max_horz || max_vert != self->max_vert) {
2264         if (max_horz != self->max_horz && max_vert != self->max_vert) {
2265             /* toggling both */
2266             if (max_horz == max_vert) { /* both going the same way */
2267                 client_maximize(self, max_horz, 0, TRUE);
2268             } else {
2269                 client_maximize(self, max_horz, 1, TRUE);
2270                 client_maximize(self, max_vert, 2, TRUE);
2271             }
2272         } else {
2273             /* toggling one */
2274             if (max_horz != self->max_horz)
2275                 client_maximize(self, max_horz, 1, TRUE);
2276             else
2277                 client_maximize(self, max_vert, 2, TRUE);
2278         }
2279     }
2280     /* change fullscreen state before shading, as it will affect if the window
2281        can shade or not */
2282     if (fullscreen != self->fullscreen)
2283         client_fullscreen(self, fullscreen, TRUE);
2284     if (shaded != self->shaded)
2285         client_shade(self, shaded);
2286     client_calc_layer(self);
2287     client_change_state(self); /* change the hint to reflect these changes */
2288 }
2289
2290 Client *client_focus_target(Client *self)
2291 {
2292     Client *child;
2293      
2294     /* if we have a modal child, then focus it, not us */
2295     child = client_search_modal_child(self);
2296     if (child) return child;
2297     return self;
2298 }
2299
2300 gboolean client_can_focus(Client *self)
2301 {
2302     XEvent ev;
2303
2304     /* choose the correct target */
2305     self = client_focus_target(self);
2306
2307     if (!self->frame->visible)
2308         return FALSE;
2309
2310     if (!((self->can_focus || self->focus_notify) &&
2311           (self->desktop == screen_desktop ||
2312            self->desktop == DESKTOP_ALL) &&
2313           !self->iconic))
2314         return FALSE;
2315
2316     /* do a check to see if the window has already been unmapped or destroyed
2317        do this intelligently while watching out for unmaps we've generated
2318        (ignore_unmaps > 0) */
2319     if (XCheckTypedWindowEvent(ob_display, self->window,
2320                                DestroyNotify, &ev)) {
2321         XPutBackEvent(ob_display, &ev);
2322         return FALSE;
2323     }
2324     while (XCheckTypedWindowEvent(ob_display, self->window,
2325                                   UnmapNotify, &ev)) {
2326         if (self->ignore_unmaps) {
2327             self->ignore_unmaps--;
2328         } else {
2329             XPutBackEvent(ob_display, &ev);
2330             return FALSE;
2331         }
2332     }
2333
2334     return TRUE;
2335 }
2336
2337 gboolean client_focus(Client *self)
2338 {
2339     /* choose the correct target */
2340     self = client_focus_target(self);
2341
2342     if (!client_can_focus(self)) {
2343         if (!self->frame->visible) {
2344             /* update the focus lists */
2345             focus_order_to_top(self);
2346         }
2347         return FALSE;
2348     }
2349
2350     if (self->can_focus)
2351         /* RevertToPointerRoot causes much more headache than RevertToNone, so
2352            I choose to use it always, hopefully to find errors quicker, if any
2353            are left. (I hate X. I hate focus events.) */
2354         XSetInputFocus(ob_display, self->window, RevertToPointerRoot,
2355                        event_lasttime);
2356
2357     if (self->focus_notify) {
2358         XEvent ce;
2359         ce.xclient.type = ClientMessage;
2360         ce.xclient.message_type = prop_atoms.wm_protocols;
2361         ce.xclient.display = ob_display;
2362         ce.xclient.window = self->window;
2363         ce.xclient.format = 32;
2364         ce.xclient.data.l[0] = prop_atoms.wm_take_focus;
2365         ce.xclient.data.l[1] = event_lasttime;
2366         ce.xclient.data.l[2] = 0l;
2367         ce.xclient.data.l[3] = 0l;
2368         ce.xclient.data.l[4] = 0l;
2369         XSendEvent(ob_display, self->window, FALSE, NoEventMask, &ce);
2370     }
2371
2372 #ifdef DEBUG_FOCUS
2373     g_message("%sively focusing %lx at %d", (self->can_focus ? "act" : "pass"),
2374               self->window, (int)
2375               event_lasttime);
2376 #endif
2377
2378     /* Cause the FocusIn to come back to us. Important for desktop switches,
2379        since otherwise we'll have no FocusIn on the queue and send it off to
2380        the focus_backup. */
2381     XSync(ob_display, FALSE);
2382     return TRUE;
2383 }
2384
2385 void client_unfocus(Client *self)
2386 {
2387     g_assert(focus_client == self);
2388 #ifdef DEBUG_FOCUS
2389     g_message("client_unfocus for %lx", self->window);
2390 #endif
2391     focus_fallback(Fallback_Unfocusing);
2392 }
2393
2394 void client_activate(Client *self)
2395 {
2396     if (client_normal(self) && screen_showing_desktop)
2397         screen_show_desktop(FALSE);
2398     if (self->iconic)
2399         client_iconify(self, FALSE, TRUE);
2400     else if (!self->frame->visible)
2401         /* if its not visible for other reasons, then don't mess
2402            with it */
2403         return;
2404     if (self->shaded)
2405         client_shade(self, FALSE);
2406     client_focus(self);
2407     stacking_raise(CLIENT_AS_WINDOW(self));
2408 }
2409
2410 gboolean client_focused(Client *self)
2411 {
2412     return self == focus_client;
2413 }
2414
2415 Icon *client_icon(Client *self, int w, int h)
2416 {
2417     int i;
2418     /* si is the smallest image >= req */
2419     /* li is the largest image < req */
2420     unsigned long size, smallest = 0xffffffff, largest = 0, si = 0, li = 0;
2421
2422     if (!self->nicons) return NULL;
2423
2424     for (i = 0; i < self->nicons; ++i) {
2425         size = self->icons[i].width * self->icons[i].height;
2426         if (size < smallest && size >= (unsigned)(w * h)) {
2427             smallest = size;
2428             si = i;
2429         }
2430         if (size > largest && size <= (unsigned)(w * h)) {
2431             largest = size;
2432             li = i;
2433         }
2434     }
2435     if (largest == 0) /* didnt find one smaller than the requested size */
2436         return &self->icons[si];
2437     return &self->icons[li];
2438 }
2439
2440 /* this be mostly ripped from fvwm */
2441 Client *client_find_directional(Client *c, Direction dir) 
2442 {
2443     int my_cx, my_cy, his_cx, his_cy;
2444     int offset = 0;
2445     int distance = 0;
2446     int score, best_score;
2447     Client *best_client, *cur;
2448     GList *it;
2449
2450     if(!client_list)
2451         return NULL;
2452
2453     /* first, find the centre coords of the currently focused window */
2454     my_cx = c->frame->area.x + c->frame->area.width / 2;
2455     my_cy = c->frame->area.y + c->frame->area.height / 2;
2456
2457     best_score = -1;
2458     best_client = NULL;
2459
2460     for(it = g_list_first(client_list); it; it = it->next) {
2461         cur = it->data;
2462
2463         /* the currently selected window isn't interesting */
2464         if(cur == c)
2465             continue;
2466         if (!client_normal(cur))
2467             continue;
2468         if(c->desktop != cur->desktop && cur->desktop != DESKTOP_ALL)
2469             continue;
2470         if(cur->iconic)
2471             continue;
2472         if(client_focus_target(cur) == cur &&
2473            !(cur->can_focus || cur->focus_notify))
2474             continue;
2475
2476         /* find the centre coords of this window, from the
2477          * currently focused window's point of view */
2478         his_cx = (cur->frame->area.x - my_cx)
2479             + cur->frame->area.width / 2;
2480         his_cy = (cur->frame->area.y - my_cy)
2481             + cur->frame->area.height / 2;
2482
2483         if(dir > 3) { 
2484             int tx;
2485             /* Rotate the diagonals 45 degrees counterclockwise.
2486              * To do this, multiply the matrix /+h +h\ with the
2487              * vector (x y).                   \-h +h/
2488              * h = sqrt(0.5). We can set h := 1 since absolute
2489              * distance doesn't matter here. */
2490             tx = his_cx + his_cy;
2491             his_cy = -his_cx + his_cy;
2492             his_cx = tx;
2493         }
2494
2495         switch(dir) {
2496         case Direction_North :
2497         case Direction_South :
2498         case Direction_NorthEast :
2499         case Direction_SouthWest :
2500             offset = (his_cx < 0) ? -his_cx : his_cx;
2501             distance = (dir == Direction_North || dir == Direction_NorthEast) ?
2502                 -his_cy : his_cy;
2503             break;
2504         case Direction_East :
2505         case Direction_West :
2506         case Direction_SouthEast :
2507         case Direction_NorthWest :
2508             offset = (his_cy < 0) ? -his_cy : his_cy;
2509             distance = (dir == Direction_West || dir == Direction_NorthWest) ?
2510                 -his_cx : his_cx;
2511             break;
2512         }
2513
2514         /* the target must be in the requested direction */
2515         if(distance <= 0)
2516             continue;
2517
2518         /* Calculate score for this window.  The smaller the better. */
2519         score = distance + offset;
2520
2521         /* windows more than 45 degrees off the direction are
2522          * heavily penalized and will only be chosen if nothing
2523          * else within a million pixels */
2524         if(offset > distance)
2525             score += 1000000;
2526
2527         if(best_score == -1 || score < best_score)
2528             best_client = cur,
2529                 best_score = score;
2530     }
2531
2532     return best_client;
2533 }
2534
2535 void client_set_layer(Client *self, int layer)
2536 {
2537     if (layer < 0) {
2538         self->below = TRUE;
2539         self->above = FALSE;
2540     } else if (layer == 0) {
2541         self->below = self->above = FALSE;
2542     } else {
2543         self->below = FALSE;
2544         self->above = TRUE;
2545     }
2546     client_calc_layer(self);
2547     client_change_state(self); /* reflect this in the state hints */
2548 }