]> icculus.org git repositories - mikachu/openbox.git/blob - openbox/client.c
remove/add instead of raising to put a window into a new layer
[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;
591
592     if (PROP_GET32(self->window, net_wm_desktop, cardinal, &d)) {
593         if (d >= screen_num_desktops && d != DESKTOP_ALL)
594             d = screen_num_desktops - 1;
595         self->desktop = d;
596     } else { 
597         gboolean trdesk = FALSE;
598
599        if (self->transient_for) {
600            if (self->transient_for != TRAN_GROUP) {
601                 self->desktop = self->transient_for->desktop;
602                 trdesk = TRUE;
603             } else {
604                 GSList *it;
605
606                 for (it = self->group->members; it; it = it->next)
607                     if (it->data != self &&
608                         !((Client*)it->data)->transient_for) {
609                         self->desktop = ((Client*)it->data)->desktop;
610                         trdesk = TRUE;
611                         break;
612                     }
613             }
614        }
615        if (!trdesk)
616            /* defaults to the current desktop */
617            self->desktop = screen_desktop;
618
619         /* set the desktop hint, to make sure that it always exists */
620         PROP_SET32(self->window, net_wm_desktop, cardinal, self->desktop);
621     }
622 }
623
624 static void client_get_state(Client *self)
625 {
626     guint32 *state;
627     guint num;
628   
629     self->modal = self->shaded = self->max_horz = self->max_vert =
630         self->fullscreen = self->above = self->below = self->iconic =
631         self->skip_taskbar = self->skip_pager = FALSE;
632
633     if (PROP_GETA32(self->window, net_wm_state, atom, &state, &num)) {
634         gulong i;
635         for (i = 0; i < num; ++i) {
636             if (state[i] == prop_atoms.net_wm_state_modal)
637                 self->modal = TRUE;
638             else if (state[i] == prop_atoms.net_wm_state_shaded)
639                 self->shaded = TRUE;
640             else if (state[i] == prop_atoms.net_wm_state_hidden)
641                 self->iconic = TRUE;
642             else if (state[i] == prop_atoms.net_wm_state_skip_taskbar)
643                 self->skip_taskbar = TRUE;
644             else if (state[i] == prop_atoms.net_wm_state_skip_pager)
645                 self->skip_pager = TRUE;
646             else if (state[i] == prop_atoms.net_wm_state_fullscreen)
647                 self->fullscreen = TRUE;
648             else if (state[i] == prop_atoms.net_wm_state_maximized_vert)
649                 self->max_vert = TRUE;
650             else if (state[i] == prop_atoms.net_wm_state_maximized_horz)
651                 self->max_horz = TRUE;
652             else if (state[i] == prop_atoms.net_wm_state_above)
653                 self->above = TRUE;
654             else if (state[i] == prop_atoms.net_wm_state_below)
655                 self->below = TRUE;
656         }
657
658         g_free(state);
659     }
660 }
661
662 static void client_get_shaped(Client *self)
663 {
664     self->shaped = FALSE;
665 #ifdef   SHAPE
666     if (extensions_shape) {
667         int foo;
668         guint ufoo;
669         int s;
670
671         XShapeSelectInput(ob_display, self->window, ShapeNotifyMask);
672
673         XShapeQueryExtents(ob_display, self->window, &s, &foo,
674                            &foo, &ufoo, &ufoo, &foo, &foo, &foo, &ufoo,
675                            &ufoo);
676         self->shaped = (s != 0);
677     }
678 #endif
679 }
680
681 void client_update_transient_for(Client *self)
682 {
683     Window t = None;
684     Client *c = NULL;
685
686     if (XGetTransientForHint(ob_display, self->window, &t)) {
687         self->transient = TRUE;
688         if (t != self->window) { /* cant be transient to itself! */
689             c = g_hash_table_lookup(window_map, &t);
690             /* if this happens then we need to check for it*/
691             g_assert(c != self);
692             g_assert(!c || WINDOW_IS_CLIENT(c));
693             
694             if (!c && self->group) {
695                 /* not transient to a client, see if it is transient for a
696                    group */
697                 if (t == self->group->leader ||
698                     t == None ||
699                     t == ob_root) {
700                     /* window is a transient for its group! */
701                     c = TRAN_GROUP;
702                 }
703             }
704         }
705     } else
706         self->transient = FALSE;
707
708     /* if anything has changed... */
709     if (c != self->transient_for) {
710         if (self->transient_for == TRAN_GROUP) { /* transient of group */
711             GSList *it;
712
713             /* remove from old parents */
714             for (it = self->group->members; it; it = it->next)
715                 if (it->data != self &&
716                     !((Client*)it->data)->transient_for)
717                     ((Client*)it->data)->transients =
718                         g_slist_remove(((Client*)it->data)->transients, self);
719         } else if (self->transient_for != NULL) { /* transient of window */
720             /* remove from old parent */
721             self->transient_for->transients =
722                 g_slist_remove(self->transient_for->transients, self);
723         }
724         self->transient_for = c;
725         if (self->transient_for == TRAN_GROUP) { /* transient of group */
726             GSList *it;
727
728             /* add to new parents */
729             for (it = self->group->members; it; it = it->next)
730                 if (it->data != self &&
731                     !((Client*)it->data)->transient_for)
732                     ((Client*)it->data)->transients =
733                         g_slist_append(((Client*)it->data)->transients, self);
734
735             /* remove all transients which are in the group, that causes
736                circlular pointer hell of doom */
737             for (it = self->group->members; it; it = it->next) {
738                 GSList *sit, *next;
739                 for (sit = self->transients; sit; sit = next) {
740                     next = sit->next;
741                     if (sit->data == it->data)
742                         self->transients = g_slist_remove(self->transients,
743                                                           sit->data);
744                 }
745             }
746         } else if (self->transient_for != NULL) { /* transient of window */
747             /* add to new parent */
748             self->transient_for->transients =
749                 g_slist_append(self->transient_for->transients, self);
750         }
751     }
752 }
753
754 static void client_get_mwm_hints(Client *self)
755 {
756     guint num;
757     guint32 *hints;
758
759     self->mwmhints.flags = 0; /* default to none */
760
761     if (PROP_GETA32(self->window, motif_wm_hints, motif_wm_hints,
762                     &hints, &num)) {
763         if (num >= MWM_ELEMENTS) {
764             self->mwmhints.flags = hints[0];
765             self->mwmhints.functions = hints[1];
766             self->mwmhints.decorations = hints[2];
767         }
768         g_free(hints);
769     }
770 }
771
772 void client_get_type(Client *self)
773 {
774     guint num, i;
775     guint32 *val;
776
777     self->type = -1;
778   
779     if (PROP_GETA32(self->window, net_wm_window_type, atom, &val, &num)) {
780         /* use the first value that we know about in the array */
781         for (i = 0; i < num; ++i) {
782             if (val[i] == prop_atoms.net_wm_window_type_desktop)
783                 self->type = Type_Desktop;
784             else if (val[i] == prop_atoms.net_wm_window_type_dock)
785                 self->type = Type_Dock;
786             else if (val[i] == prop_atoms.net_wm_window_type_toolbar)
787                 self->type = Type_Toolbar;
788             else if (val[i] == prop_atoms.net_wm_window_type_menu)
789                 self->type = Type_Menu;
790             else if (val[i] == prop_atoms.net_wm_window_type_utility)
791                 self->type = Type_Utility;
792             else if (val[i] == prop_atoms.net_wm_window_type_splash)
793                 self->type = Type_Splash;
794             else if (val[i] == prop_atoms.net_wm_window_type_dialog)
795                 self->type = Type_Dialog;
796             else if (val[i] == prop_atoms.net_wm_window_type_normal)
797                 self->type = Type_Normal;
798             else if (val[i] == prop_atoms.kde_net_wm_window_type_override) {
799                 /* prevent this window from getting any decor or
800                    functionality */
801                 self->mwmhints.flags &= (MwmFlag_Functions |
802                                          MwmFlag_Decorations);
803                 self->mwmhints.decorations = 0;
804                 self->mwmhints.functions = 0;
805             }
806             if (self->type != (WindowType) -1)
807                 break; /* grab the first legit type */
808         }
809         g_free(val);
810     }
811     
812     if (self->type == (WindowType) -1) {
813         /*the window type hint was not set, which means we either classify
814           ourself as a normal window or a dialog, depending on if we are a
815           transient. */
816         if (self->transient)
817             self->type = Type_Dialog;
818         else
819             self->type = Type_Normal;
820     }
821 }
822
823 void client_update_protocols(Client *self)
824 {
825     guint32 *proto;
826     guint num_return, i;
827
828     self->focus_notify = FALSE;
829     self->delete_window = FALSE;
830
831     if (PROP_GETA32(self->window, wm_protocols, atom, &proto, &num_return)) {
832         for (i = 0; i < num_return; ++i) {
833             if (proto[i] == prop_atoms.wm_delete_window) {
834                 /* this means we can request the window to close */
835                 self->delete_window = TRUE;
836             } else if (proto[i] == prop_atoms.wm_take_focus)
837                 /* if this protocol is requested, then the window will be
838                    notified whenever we want it to receive focus */
839                 self->focus_notify = TRUE;
840         }
841         g_free(proto);
842     }
843 }
844
845 static void client_get_gravity(Client *self)
846 {
847     XWindowAttributes wattrib;
848     Status ret;
849
850     ret = XGetWindowAttributes(ob_display, self->window, &wattrib);
851     g_assert(ret != BadWindow);
852     self->gravity = wattrib.win_gravity;
853 }
854
855 void client_update_normal_hints(Client *self)
856 {
857     XSizeHints size;
858     long ret;
859     int oldgravity = self->gravity;
860
861     /* defaults */
862     self->min_ratio = 0.0f;
863     self->max_ratio = 0.0f;
864     SIZE_SET(self->size_inc, 1, 1);
865     SIZE_SET(self->base_size, 0, 0);
866     SIZE_SET(self->min_size, 0, 0);
867     SIZE_SET(self->max_size, G_MAXINT, G_MAXINT);
868
869     /* get the hints from the window */
870     if (XGetWMNormalHints(ob_display, self->window, &size, &ret)) {
871         self->positioned = !!(size.flags & (PPosition|USPosition));
872
873         if (size.flags & PWinGravity) {
874             self->gravity = size.win_gravity;
875       
876             /* if the client has a frame, i.e. has already been mapped and
877                is changing its gravity */
878             if (self->frame && self->gravity != oldgravity) {
879                 /* move our idea of the client's position based on its new
880                    gravity */
881                 self->area.x = self->frame->area.x;
882                 self->area.y = self->frame->area.y;
883                 frame_frame_gravity(self->frame, &self->area.x, &self->area.y);
884             }
885         }
886
887         if (size.flags & PAspect) {
888             if (size.min_aspect.y)
889                 self->min_ratio = (float)size.min_aspect.x / size.min_aspect.y;
890             if (size.max_aspect.y)
891                 self->max_ratio = (float)size.max_aspect.x / size.max_aspect.y;
892         }
893
894         if (size.flags & PMinSize)
895             SIZE_SET(self->min_size, size.min_width, size.min_height);
896     
897         if (size.flags & PMaxSize)
898             SIZE_SET(self->max_size, size.max_width, size.max_height);
899     
900         if (size.flags & PBaseSize)
901             SIZE_SET(self->base_size, size.base_width, size.base_height);
902     
903         if (size.flags & PResizeInc)
904             SIZE_SET(self->size_inc, size.width_inc, size.height_inc);
905     }
906 }
907
908 void client_setup_decor_and_functions(Client *self)
909 {
910     /* start with everything (cept fullscreen) */
911     self->decorations = Decor_Titlebar | Decor_Handle | Decor_Border |
912         Decor_Icon | Decor_AllDesktops | Decor_Iconify | Decor_Maximize |
913         Decor_Shade;
914     self->functions = Func_Resize | Func_Move | Func_Iconify | Func_Maximize |
915         Func_Shade;
916     if (self->delete_window) {
917         self->decorations |= Decor_Close;
918         self->functions |= Func_Close;
919     }
920
921     if (!(self->min_size.width < self->max_size.width ||
922           self->min_size.height < self->max_size.height)) {
923         self->decorations &= ~(Decor_Maximize | Decor_Handle);
924         self->functions &= ~(Func_Resize | Func_Maximize);
925     }
926
927     switch (self->type) {
928     case Type_Normal:
929         /* normal windows retain all of the possible decorations and
930            functionality, and are the only windows that you can fullscreen */
931         self->functions |= Func_Fullscreen;
932         break;
933
934     case Type_Dialog:
935     case Type_Utility:
936         /* these windows cannot be maximized */
937         self->decorations &= ~Decor_Maximize;
938         self->functions &= ~Func_Maximize;
939         break;
940
941     case Type_Menu:
942     case Type_Toolbar:
943         /* these windows get less functionality */
944         self->decorations &= ~(Decor_Iconify | Decor_Handle);
945         self->functions &= ~(Func_Iconify | Func_Resize);
946         break;
947
948     case Type_Desktop:
949     case Type_Dock:
950     case Type_Splash:
951         /* none of these windows are manipulated by the window manager */
952         self->decorations = 0;
953         self->functions = 0;
954         break;
955     }
956
957     /* Mwm Hints are applied subtractively to what has already been chosen for
958        decor and functionality */
959     if (self->mwmhints.flags & MwmFlag_Decorations) {
960         if (! (self->mwmhints.decorations & MwmDecor_All)) {
961             if (! (self->mwmhints.decorations & MwmDecor_Border))
962                 self->decorations &= ~Decor_Border;
963             if (! (self->mwmhints.decorations & MwmDecor_Handle))
964                 self->decorations &= ~Decor_Handle;
965             if (! (self->mwmhints.decorations & MwmDecor_Title))
966                 self->decorations &= ~Decor_Titlebar;
967             if (! (self->mwmhints.decorations & MwmDecor_Iconify))
968                 self->decorations &= ~Decor_Iconify;
969             if (! (self->mwmhints.decorations & MwmDecor_Maximize))
970                 self->decorations &= ~Decor_Maximize;
971         }
972     }
973
974     if (self->mwmhints.flags & MwmFlag_Functions) {
975         if (! (self->mwmhints.functions & MwmFunc_All)) {
976             if (! (self->mwmhints.functions & MwmFunc_Resize))
977                 self->functions &= ~Func_Resize;
978             if (! (self->mwmhints.functions & MwmFunc_Move))
979                 self->functions &= ~Func_Move;
980             if (! (self->mwmhints.functions & MwmFunc_Iconify))
981                 self->functions &= ~Func_Iconify;
982             if (! (self->mwmhints.functions & MwmFunc_Maximize))
983                 self->functions &= ~Func_Maximize;
984             /* dont let mwm hints kill the close button
985                if (! (self->mwmhints.functions & MwmFunc_Close))
986                self->functions &= ~Func_Close; */
987         }
988     }
989
990     /* can't maximize without moving/resizing */
991     if (!((self->functions & Func_Move) && (self->functions & Func_Resize)))
992         self->functions &= ~(Func_Maximize | Func_Fullscreen);
993
994     /* finally, user specified disabled decorations are applied to subtract
995        decorations */
996     if (self->disabled_decorations & Decor_Titlebar)
997         self->decorations &= ~Decor_Titlebar;
998     if (self->disabled_decorations & Decor_Handle)
999         self->decorations &= ~Decor_Handle;
1000     if (self->disabled_decorations & Decor_Border)
1001         self->decorations &= ~Decor_Border;
1002     if (self->disabled_decorations & Decor_Iconify)
1003         self->decorations &= ~Decor_Iconify;
1004     if (self->disabled_decorations & Decor_Maximize)
1005         self->decorations &= ~Decor_Maximize;
1006     if (self->disabled_decorations & Decor_AllDesktops)
1007         self->decorations &= ~Decor_AllDesktops;
1008     if (self->disabled_decorations & Decor_Shade)
1009         self->decorations &= ~Decor_Shade;
1010     if (self->disabled_decorations & Decor_Close)
1011         self->decorations &= ~Decor_Close;
1012
1013     /* if we don't have a titlebar, then we cannot shade! */
1014     if (!(self->decorations & Decor_Titlebar))
1015         self->functions &= ~Func_Shade;
1016
1017     /* now we need to check against rules for the client's current state */
1018     if (self->fullscreen) {
1019         self->functions &= (Func_Close | Func_Fullscreen | Func_Iconify);
1020         self->decorations = 0;
1021     }
1022
1023     client_change_allowed_actions(self);
1024
1025     if (self->frame) {
1026         /* this makes sure that these windows appear on all desktops */
1027         if (self->type == Type_Desktop && self->desktop != DESKTOP_ALL)
1028             client_set_desktop(self, DESKTOP_ALL, FALSE);
1029
1030         /* adjust the client's decorations, etc. */
1031         client_reconfigure(self);
1032     } else {
1033         /* this makes sure that these windows appear on all desktops */
1034         if (self->type == Type_Desktop && self->desktop != DESKTOP_ALL)
1035             self->desktop = DESKTOP_ALL;
1036     }
1037 }
1038
1039 static void client_change_allowed_actions(Client *self)
1040 {
1041     guint32 actions[9];
1042     int num = 0;
1043
1044     /* desktop windows are kept on all desktops */
1045     if (self->type != Type_Desktop)
1046         actions[num++] = prop_atoms.net_wm_action_change_desktop;
1047
1048     if (self->functions & Func_Shade)
1049         actions[num++] = prop_atoms.net_wm_action_shade;
1050     if (self->functions & Func_Close)
1051         actions[num++] = prop_atoms.net_wm_action_close;
1052     if (self->functions & Func_Move)
1053         actions[num++] = prop_atoms.net_wm_action_move;
1054     if (self->functions & Func_Iconify)
1055         actions[num++] = prop_atoms.net_wm_action_minimize;
1056     if (self->functions & Func_Resize)
1057         actions[num++] = prop_atoms.net_wm_action_resize;
1058     if (self->functions & Func_Fullscreen)
1059         actions[num++] = prop_atoms.net_wm_action_fullscreen;
1060     if (self->functions & Func_Maximize) {
1061         actions[num++] = prop_atoms.net_wm_action_maximize_horz;
1062         actions[num++] = prop_atoms.net_wm_action_maximize_vert;
1063     }
1064
1065     PROP_SETA32(self->window, net_wm_allowed_actions, atom, actions, num);
1066
1067     /* make sure the window isn't breaking any rules now */
1068
1069     if (!(self->functions & Func_Shade) && self->shaded) {
1070         if (self->frame) client_shade(self, FALSE);
1071         else self->shaded = FALSE;
1072     }
1073     if (!(self->functions & Func_Iconify) && self->iconic) {
1074         g_message("UNSETTING ICONIC");
1075         if (self->frame) client_iconify(self, FALSE, TRUE);
1076         else self->iconic = FALSE;
1077     }
1078     if (!(self->functions & Func_Fullscreen) && self->fullscreen) {
1079         if (self->frame) client_fullscreen(self, FALSE, TRUE);
1080         else self->fullscreen = FALSE;
1081     }
1082     if (!(self->functions & Func_Maximize) && (self->max_horz ||
1083                                                self->max_vert)) {
1084         if (self->frame) client_maximize(self, FALSE, 0, TRUE);
1085         else self->max_vert = self->max_horz = FALSE;
1086     }
1087 }
1088
1089 void client_reconfigure(Client *self)
1090 {
1091     /* by making this pass FALSE for user, we avoid the emacs event storm where
1092        every configurenotify causes an update in its normal hints, i think this
1093        is generally what we want anyways... */
1094     client_configure(self, Corner_TopLeft, self->area.x, self->area.y,
1095                      self->area.width, self->area.height, FALSE, TRUE);
1096 }
1097
1098 void client_update_wmhints(Client *self)
1099 {
1100     XWMHints *hints;
1101     gboolean ur = FALSE;
1102     GSList *it;
1103
1104     /* assume a window takes input if it doesnt specify */
1105     self->can_focus = TRUE;
1106   
1107     if ((hints = XGetWMHints(ob_display, self->window)) != NULL) {
1108         if (hints->flags & InputHint)
1109             self->can_focus = hints->input;
1110
1111         /* only do this when first managing the window *AND* when we aren't
1112            starting up! */
1113         if (ob_state != State_Starting && self->frame == NULL)
1114             if (hints->flags & StateHint)
1115                 self->iconic = hints->initial_state == IconicState;
1116
1117         if (hints->flags & XUrgencyHint)
1118             ur = TRUE;
1119
1120         if (!(hints->flags & WindowGroupHint))
1121             hints->window_group = None;
1122
1123         /* did the group state change? */
1124         if (hints->window_group !=
1125             (self->group ? self->group->leader : None)) {
1126             /* remove from the old group if there was one */
1127             if (self->group != NULL) {
1128                 /* remove transients of the group */
1129                 for (it = self->group->members; it; it = it->next)
1130                     self->transients = g_slist_remove(self->transients,
1131                                                       it->data);
1132                 group_remove(self->group, self);
1133                 self->group = NULL;
1134             }
1135             if (hints->window_group != None) {
1136                 self->group = group_add(hints->window_group, self);
1137
1138                 /* i can only have transients from the group if i am not
1139                    transient myself */
1140                 if (!self->transient_for) {
1141                     /* add other transients of the group that are already
1142                        set up */
1143                     for (it = self->group->members; it; it = it->next)
1144                         if (it->data != self &&
1145                             ((Client*)it->data)->transient_for == TRAN_GROUP)
1146                             self->transients = g_slist_append(self->transients,
1147                                                               it->data);
1148                 }
1149             }
1150
1151             /* the WM_HINTS can contain an icon */
1152             client_update_icons(self);
1153
1154             /* because the self->transient flag wont change from this call,
1155                we don't need to update the window's type and such, only its
1156                transient_for, and the transients lists of other windows in
1157                the group may be affected */
1158             client_update_transient_for(self);
1159         }
1160
1161         XFree(hints);
1162     }
1163
1164     if (ur != self->urgent) {
1165         self->urgent = ur;
1166         g_message("Urgent Hint for 0x%lx: %s", self->window,
1167                   ur ? "ON" : "OFF");
1168         /* fire the urgent callback if we're mapped, otherwise, wait until
1169            after we're mapped */
1170         if (self->frame)
1171             dispatch_client(Event_Client_Urgent, self, self->urgent, 0);
1172     }
1173 }
1174
1175 void client_update_title(Client *self)
1176 {
1177     GList *it;
1178     guint32 nums;
1179     guint i;
1180     char *data = NULL;
1181     gboolean read_title;
1182
1183     g_free(self->title);
1184      
1185     /* try netwm */
1186     if (!PROP_GETS(self->window, net_wm_name, utf8, &data))
1187         /* try old x stuff */
1188         if (!PROP_GETS(self->window, wm_name, locale, &data))
1189             data = g_strdup("Unnamed Window");
1190
1191     /* look for duplicates and append a number */
1192     nums = 0;
1193     for (it = client_list; it; it = it->next)
1194         if (it->data != self) {
1195             Client *c = it->data;
1196             if (0 == strncmp(c->title, data, strlen(data)))
1197                 nums |= 1 << c->title_count;
1198         }
1199     /* find first free number */
1200     for (i = 1; i <= 32; ++i)
1201         if (!(nums & (1 << i))) {
1202             if (self->title_count == 1 || i == 1)
1203                 self->title_count = i;
1204             break;
1205         }
1206     /* dont display the number for the first window */
1207     if (self->title_count > 1) {
1208         char *vdata, *ndata;
1209         ndata = g_strdup_printf(" - [%u]", self->title_count);
1210         vdata = g_strconcat(data, ndata, NULL);
1211         g_free(ndata);
1212         g_free(data);
1213         data = vdata;
1214     }
1215
1216     PROP_SETS(self->window, net_wm_visible_name, data);
1217
1218     self->title = data;
1219
1220     if (self->frame)
1221         frame_adjust_title(self->frame);
1222
1223     /* update the icon title */
1224     data = NULL;
1225     g_free(self->icon_title);
1226
1227     read_title = TRUE;
1228     /* try netwm */
1229     if (!PROP_GETS(self->window, net_wm_icon_name, utf8, &data))
1230         /* try old x stuff */
1231         if (!PROP_GETS(self->window, wm_icon_name, locale, &data)) {
1232             data = g_strdup(self->title);
1233             read_title = FALSE;
1234         }
1235
1236     /* append the title count, dont display the number for the first window */
1237     if (read_title && self->title_count > 1) {
1238         char *vdata, *ndata;
1239         ndata = g_strdup_printf(" - [%u]", self->title_count);
1240         vdata = g_strconcat(data, ndata, NULL);
1241         g_free(ndata);
1242         g_free(data);
1243         data = vdata;
1244     }
1245
1246     PROP_SETS(self->window, net_wm_visible_icon_name, data);
1247
1248     self->icon_title = data;
1249 }
1250
1251 void client_update_class(Client *self)
1252 {
1253     char **data;
1254     char *s;
1255
1256     if (self->name) g_free(self->name);
1257     if (self->class) g_free(self->class);
1258     if (self->role) g_free(self->role);
1259
1260     self->name = self->class = self->role = NULL;
1261
1262     if (PROP_GETSS(self->window, wm_class, locale, &data)) {
1263         if (data[0]) {
1264             self->name = g_strdup(data[0]);
1265             if (data[1])
1266                 self->class = g_strdup(data[1]);
1267         }
1268         g_strfreev(data);     
1269     }
1270
1271     if (PROP_GETS(self->window, wm_window_role, locale, &s))
1272         self->role = g_strdup(s);
1273
1274     if (self->name == NULL) self->name = g_strdup("");
1275     if (self->class == NULL) self->class = g_strdup("");
1276     if (self->role == NULL) self->role = g_strdup("");
1277 }
1278
1279 void client_update_strut(Client *self)
1280 {
1281     guint num;
1282     guint32 *data;
1283
1284     if (!PROP_GETA32(self->window, net_wm_strut, cardinal, &data, &num)) {
1285         STRUT_SET(self->strut, 0, 0, 0, 0);
1286     } else {
1287         if (num == 4)
1288             STRUT_SET(self->strut, data[0], data[2], data[1], data[3]);
1289         else
1290             STRUT_SET(self->strut, 0, 0, 0, 0);
1291         g_free(data);
1292     }
1293
1294     /* updating here is pointless while we're being mapped cuz we're not in
1295        the client list yet */
1296     if (self->frame)
1297         screen_update_struts();
1298 }
1299
1300 void client_update_icons(Client *self)
1301 {
1302     guint num;
1303     guint32 *data;
1304     guint w, h, i;
1305     int j;
1306
1307     for (j = 0; j < self->nicons; ++j)
1308         g_free(self->icons[j].data);
1309     if (self->nicons > 0)
1310         g_free(self->icons);
1311     self->nicons = 0;
1312
1313     if (PROP_GETA32(self->window, net_wm_icon, cardinal, &data, &num)) {
1314         /* figure out how many valid icons are in here */
1315         i = 0;
1316         while (num - i > 2) {
1317             w = data[i++];
1318             h = data[i++];
1319             i += w * h;
1320             if (i > num || w*h == 0) break;
1321             ++self->nicons;
1322         }
1323
1324         self->icons = g_new(Icon, self->nicons);
1325     
1326         /* store the icons */
1327         i = 0;
1328         for (j = 0; j < self->nicons; ++j) {
1329             guint x, y, t;
1330
1331             w = self->icons[j].width = data[i++];
1332             h = self->icons[j].height = data[i++];
1333
1334             if (w*h == 0) continue;
1335
1336             self->icons[j].data = g_new(RrPixel32, w * h);
1337             for (x = 0, y = 0, t = 0; t < w * h; ++t, ++x, ++i) {
1338                 if (x >= w) {
1339                     x = 0;
1340                     ++y;
1341                 }
1342                 self->icons[j].data[t] =
1343                     (((data[i] >> 24) & 0xff) << RrDefaultAlphaOffset) +
1344                     (((data[i] >> 16) & 0xff) << RrDefaultRedOffset) +
1345                     (((data[i] >> 8) & 0xff) << RrDefaultGreenOffset) +
1346                     (((data[i] >> 0) & 0xff) << RrDefaultBlueOffset);
1347             }
1348             g_assert(i <= num);
1349         }
1350
1351         g_free(data);
1352     } else if (PROP_GETA32(self->window, kwm_win_icon,
1353                            kwm_win_icon, &data, &num)) {
1354         if (num == 2) {
1355             self->nicons++;
1356             self->icons = g_new(Icon, self->nicons);
1357             xerror_set_ignore(TRUE);
1358             if (!RrPixmapToRGBA(ob_rr_inst,
1359                                 data[0], data[1],
1360                                 &self->icons[self->nicons-1].width,
1361                                 &self->icons[self->nicons-1].height,
1362                                 &self->icons[self->nicons-1].data)) {
1363                 g_free(&self->icons[self->nicons-1]);
1364                 self->nicons--;
1365             }
1366             xerror_set_ignore(FALSE);
1367         }
1368         g_free(data);
1369     } else {
1370         XWMHints *hints;
1371
1372         if ((hints = XGetWMHints(ob_display, self->window))) {
1373             if (hints->flags & IconPixmapHint) {
1374                 self->nicons++;
1375                 self->icons = g_new(Icon, self->nicons);
1376                 xerror_set_ignore(TRUE);
1377                 if (!RrPixmapToRGBA(ob_rr_inst,
1378                                     hints->icon_pixmap,
1379                                     (hints->flags & IconMaskHint ?
1380                                      hints->icon_mask : None),
1381                                     &self->icons[self->nicons-1].width,
1382                                     &self->icons[self->nicons-1].height,
1383                                     &self->icons[self->nicons-1].data)){
1384                     g_free(&self->icons[self->nicons-1]);
1385                     self->nicons--;
1386                 }
1387                 xerror_set_ignore(FALSE);
1388             }
1389             XFree(hints);
1390         }
1391     }
1392
1393     if (self->frame)
1394         frame_adjust_icon(self->frame);
1395 }
1396
1397 static void client_change_state(Client *self)
1398 {
1399     guint32 state[2];
1400     guint32 netstate[10];
1401     guint num;
1402
1403     state[0] = self->wmstate;
1404     state[1] = None;
1405     PROP_SETA32(self->window, wm_state, wm_state, state, 2);
1406
1407     num = 0;
1408     if (self->modal)
1409         netstate[num++] = prop_atoms.net_wm_state_modal;
1410     if (self->shaded)
1411         netstate[num++] = prop_atoms.net_wm_state_shaded;
1412     if (self->iconic)
1413         netstate[num++] = prop_atoms.net_wm_state_hidden;
1414     if (self->skip_taskbar)
1415         netstate[num++] = prop_atoms.net_wm_state_skip_taskbar;
1416     if (self->skip_pager)
1417         netstate[num++] = prop_atoms.net_wm_state_skip_pager;
1418     if (self->fullscreen)
1419         netstate[num++] = prop_atoms.net_wm_state_fullscreen;
1420     if (self->max_vert)
1421         netstate[num++] = prop_atoms.net_wm_state_maximized_vert;
1422     if (self->max_horz)
1423         netstate[num++] = prop_atoms.net_wm_state_maximized_horz;
1424     if (self->above)
1425         netstate[num++] = prop_atoms.net_wm_state_above;
1426     if (self->below)
1427         netstate[num++] = prop_atoms.net_wm_state_below;
1428     PROP_SETA32(self->window, net_wm_state, atom, netstate, num);
1429
1430     client_calc_layer(self);
1431
1432     if (self->frame)
1433         frame_adjust_state(self->frame);
1434 }
1435
1436 Client *client_search_focus_tree(Client *self)
1437 {
1438     GSList *it;
1439     Client *ret;
1440
1441     for (it = self->transients; it != NULL; it = it->next) {
1442         if (client_focused(it->data)) return it->data;
1443         if ((ret = client_search_focus_tree(it->data))) return ret;
1444     }
1445     return NULL;
1446 }
1447
1448 Client *client_search_focus_tree_full(Client *self)
1449 {
1450     if (self->transient_for) {
1451         if (self->transient_for != TRAN_GROUP) {
1452             return client_search_focus_tree_full(self->transient_for);
1453         } else {
1454             GSList *it;
1455             gboolean recursed = FALSE;
1456         
1457             for (it = self->group->members; it; it = it->next)
1458                 if (!((Client*)it->data)->transient_for) {
1459                     Client *c;
1460                     if ((c = client_search_focus_tree_full(it->data)))
1461                         return c;
1462                     recursed = TRUE;
1463                 }
1464             if (recursed)
1465               return NULL;
1466         }
1467     }
1468
1469     /* this function checks the whole tree, the client_search_focus_tree~
1470        does not, so we need to check this window */
1471     if (client_focused(self))
1472       return self;
1473     return client_search_focus_tree(self);
1474 }
1475
1476 static StackLayer calc_layer(Client *self)
1477 {
1478     StackLayer l;
1479
1480     if (self->fullscreen) l = Layer_Fullscreen;
1481     else if (self->type == Type_Desktop) l = Layer_Desktop;
1482     else if (self->type == Type_Dock) {
1483         if (!self->below) l = Layer_Top;
1484         else l = Layer_Normal;
1485     }
1486     else if (self->above) l = Layer_Above;
1487     else if (self->below) l = Layer_Below;
1488     else l = Layer_Normal;
1489
1490     return l;
1491 }
1492
1493 static void calc_recursive(Client *self, Client *orig, StackLayer l,
1494                            gboolean raised)
1495 {
1496     StackLayer old, own;
1497     GSList *it;
1498
1499     old = self->layer;
1500     own = calc_layer(self);
1501     self->layer = l > own ? l : own;
1502
1503     for (it = self->transients; it; it = it->next)
1504         calc_recursive(it->data, orig, l, raised ? raised : l != old);
1505
1506     if (!raised && l != old)
1507         if (orig->frame) { /* only restack if the original window is managed */
1508             /* XXX add_non_intrusive ever? */
1509             stacking_remove(CLIENT_AS_WINDOW(self));
1510             stacking_add(CLIENT_AS_WINDOW(self));
1511         }
1512 }
1513
1514 void client_calc_layer(Client *self)
1515 {
1516     StackLayer l;
1517     Client *orig;
1518
1519     orig = self;
1520
1521     /* transients take on the layer of their parents */
1522     if (self->transient_for) {
1523         if (self->transient_for != TRAN_GROUP) {
1524             self = self->transient_for;
1525         } else {
1526             GSList *it;
1527
1528             for (it = self->group->members; it; it = it->next)
1529                 if (it->data != self &&
1530                     !((Client*)it->data)->transient_for) {
1531                     self = it->data;
1532                     break;
1533                 }
1534         }
1535     }
1536
1537     l = calc_layer(self);
1538
1539     calc_recursive(self, orig, l, FALSE);
1540 }
1541
1542 gboolean client_should_show(Client *self)
1543 {
1544     if (self->iconic) return FALSE;
1545     else if (!(self->desktop == screen_desktop ||
1546                self->desktop == DESKTOP_ALL)) return FALSE;
1547     else if (client_normal(self) && screen_showing_desktop) return FALSE;
1548     
1549     return TRUE;
1550 }
1551
1552 static void client_showhide(Client *self)
1553 {
1554
1555     if (client_should_show(self))
1556         frame_show(self->frame);
1557     else
1558         frame_hide(self->frame);
1559 }
1560
1561 gboolean client_normal(Client *self) {
1562     return ! (self->type == Type_Desktop || self->type == Type_Dock ||
1563               self->type == Type_Splash);
1564 }
1565
1566 static void client_apply_startup_state(Client *self)
1567 {
1568     /* these are in a carefully crafted order.. */
1569
1570     if (self->iconic) {
1571         self->iconic = FALSE;
1572         client_iconify(self, TRUE, FALSE);
1573     }
1574     if (self->fullscreen) {
1575         self->fullscreen = FALSE;
1576         client_fullscreen(self, TRUE, FALSE);
1577     }
1578     if (self->shaded) {
1579         self->shaded = FALSE;
1580         client_shade(self, TRUE);
1581     }
1582     if (self->urgent)
1583         dispatch_client(Event_Client_Urgent, self, self->urgent, 0);
1584   
1585     if (self->max_vert && self->max_horz) {
1586         self->max_vert = self->max_horz = FALSE;
1587         client_maximize(self, TRUE, 0, FALSE);
1588     } else if (self->max_vert) {
1589         self->max_vert = FALSE;
1590         client_maximize(self, TRUE, 2, FALSE);
1591     } else if (self->max_horz) {
1592         self->max_horz = FALSE;
1593         client_maximize(self, TRUE, 1, FALSE);
1594     }
1595
1596     /* nothing to do for the other states:
1597        skip_taskbar
1598        skip_pager
1599        modal
1600        above
1601        below
1602     */
1603 }
1604
1605 void client_configure(Client *self, Corner anchor, int x, int y, int w, int h,
1606                       gboolean user, gboolean final)
1607 {
1608     gboolean moved = FALSE, resized = FALSE;
1609
1610     /* gets the frame's position */
1611     frame_client_gravity(self->frame, &x, &y);
1612
1613     /* these positions are frame positions, not client positions */
1614
1615     /* set the size and position if fullscreen */
1616     if (self->fullscreen) {
1617 #ifdef VIDMODE
1618         int dot;
1619         XF86VidModeModeLine mode;
1620
1621         if (XF86VidModeGetModeLine(ob_display, ob_screen, &dot, &mode)) {
1622             w = mode.hdisplay;
1623             h = mode.vdisplay;
1624             if (mode.privsize) XFree(mode.private);
1625         } else {
1626 #else
1627             w = screen_physical_size.width;
1628             h = screen_physical_size.height;
1629 #endif
1630 #ifdef VIDMODE
1631         }
1632         if (!XF86VidModeGetViewPort(ob_display, ob_screen, &x, &y)) {
1633             x = y = 0;
1634 #endif
1635         }
1636         user = FALSE; /* ignore that increment etc shit when in fullscreen */
1637     } else {
1638         /* set the size and position if maximized */
1639         if (self->max_horz) {
1640             x = screen_area(self->desktop)->x - self->frame->size.left;
1641             w = screen_area(self->desktop)->width;
1642         }
1643         if (self->max_vert) {
1644             y = screen_area(self->desktop)->y;
1645             h = screen_area(self->desktop)->height -
1646                 self->frame->size.top - self->frame->size.bottom;
1647         }
1648     }
1649
1650     /* gets the client's position */
1651     frame_frame_gravity(self->frame, &x, &y);
1652
1653     /* these override the above states! if you cant move you can't move! */
1654     if (user) {
1655         if (!(self->functions & Func_Move)) {
1656             x = self->area.x;
1657             y = self->area.y;
1658         }
1659         if (!(self->functions & Func_Resize)) {
1660             w = self->area.width;
1661             h = self->area.height;
1662         }
1663     }
1664
1665     if (!(w == self->area.width && h == self->area.height)) {
1666         int basew, baseh, minw, minh;
1667
1668         /* base size is substituted with min size if not specified */
1669         if (self->base_size.width || self->base_size.height) {
1670             basew = self->base_size.width;
1671             baseh = self->base_size.height;
1672         } else {
1673             basew = self->min_size.width;
1674             baseh = self->min_size.height;
1675         }
1676         /* min size is substituted with base size if not specified */
1677         if (self->min_size.width || self->min_size.height) {
1678             minw = self->min_size.width;
1679             minh = self->min_size.height;
1680         } else {
1681             minw = self->base_size.width;
1682             minh = self->base_size.height;
1683         }
1684
1685         if (user) {
1686             /* for interactive resizing. have to move half an increment in each
1687                direction. */
1688
1689             /* how far we are towards the next size inc */
1690             int mw = (w - basew) % self->size_inc.width; 
1691             int mh = (h - baseh) % self->size_inc.height;
1692             /* amount to add */
1693             int aw = self->size_inc.width / 2;
1694             int ah = self->size_inc.height / 2;
1695             /* don't let us move into a new size increment */
1696             if (mw + aw >= self->size_inc.width)
1697                 aw = self->size_inc.width - mw - 1;
1698             if (mh + ah >= self->size_inc.height)
1699                 ah = self->size_inc.height - mh - 1;
1700             w += aw;
1701             h += ah;
1702     
1703             /* if this is a user-requested resize, then check against min/max
1704                sizes */
1705
1706             /* smaller than min size or bigger than max size? */
1707             if (w > self->max_size.width) w = self->max_size.width;
1708             if (w < minw) w = minw;
1709             if (h > self->max_size.height) h = self->max_size.height;
1710             if (h < minh) h = minh;
1711         }
1712
1713         w -= basew;
1714         h -= baseh;
1715
1716         /* keep to the increments */
1717         w /= self->size_inc.width;
1718         h /= self->size_inc.height;
1719
1720         /* you cannot resize to nothing */
1721         if (w < 1) w = 1;
1722         if (h < 1) h = 1;
1723   
1724         /* store the logical size */
1725         SIZE_SET(self->logical_size, w, h);
1726
1727         w *= self->size_inc.width;
1728         h *= self->size_inc.height;
1729
1730         w += basew;
1731         h += baseh;
1732
1733         if (user) {
1734             /* adjust the height to match the width for the aspect ratios.
1735              for this, min size is not substituted for base size ever. */
1736             w -= self->base_size.width;
1737             h -= self->base_size.height;
1738
1739             if (self->min_ratio)
1740                 if (h * self->min_ratio > w) h = (int)(w / self->min_ratio);
1741             if (self->max_ratio)
1742                 if (h * self->max_ratio < w) h = (int)(w / self->max_ratio);
1743
1744             w += self->base_size.width;
1745             h += self->base_size.height;
1746         }
1747     }
1748
1749     switch (anchor) {
1750     case Corner_TopLeft:
1751         break;
1752     case Corner_TopRight:
1753         x -= w - self->area.width;
1754         break;
1755     case Corner_BottomLeft:
1756         y -= h - self->area.height;
1757         break;
1758     case Corner_BottomRight:
1759         x -= w - self->area.width;
1760         y -= h - self->area.height;
1761         break;
1762     }
1763
1764     moved = x != self->area.x || y != self->area.y;
1765     resized = w != self->area.width || h != self->area.height;
1766
1767     RECT_SET(self->area, x, y, w, h);
1768
1769     /* for app-requested resizes, always resize if 'resized' is true.
1770        for user-requested ones, only resize if final is true, or when
1771        resizing in opaque mode */
1772     if ((!user && resized) ||
1773         (user && (final || (resized && config_opaque_resize))))
1774         XResizeWindow(ob_display, self->window, w, h);
1775
1776     /* move/resize the frame to match the request */
1777     if (self->frame) {
1778         if (self->decorations != self->frame->decorations)
1779             moved = resized = TRUE;
1780
1781         if (moved || resized)
1782             frame_adjust_area(self->frame, moved, resized);
1783
1784         /* If you send this and the client hasn't changed you end up with buggy
1785            clients (emacs) freaking out, cuz they send back a configure every
1786            time they receive this event, which resends them this event... etc.
1787         */
1788         if ((!user && moved) || (user && final)) {
1789             XEvent event;
1790             event.type = ConfigureNotify;
1791             event.xconfigure.display = ob_display;
1792             event.xconfigure.event = self->window;
1793             event.xconfigure.window = self->window;
1794     
1795             /* root window real coords */
1796             event.xconfigure.x = self->frame->area.x + self->frame->size.left;
1797             event.xconfigure.y = self->frame->area.y + self->frame->size.top;
1798     
1799             event.xconfigure.width = w;
1800             event.xconfigure.height = h;
1801             event.xconfigure.border_width = 0;
1802             event.xconfigure.above = self->frame->plate;
1803             event.xconfigure.override_redirect = FALSE;
1804             XSendEvent(event.xconfigure.display, event.xconfigure.window,
1805                        FALSE, StructureNotifyMask, &event);
1806         }
1807     }
1808 }
1809
1810 void client_fullscreen(Client *self, gboolean fs, gboolean savearea)
1811 {
1812     int x, y, w, h;
1813
1814     if (!(self->functions & Func_Fullscreen) || /* can't */
1815         self->fullscreen == fs) return;         /* already done */
1816
1817     self->fullscreen = fs;
1818     client_change_state(self); /* change the state hints on the client,
1819                                   and adjust out layer/stacking */
1820
1821     if (fs) {
1822         if (savearea) {
1823             guint32 dimensions[4];
1824             dimensions[0] = self->area.x;
1825             dimensions[1] = self->area.y;
1826             dimensions[2] = self->area.width;
1827             dimensions[3] = self->area.height;
1828   
1829             PROP_SETA32(self->window, openbox_premax, cardinal,
1830                         dimensions, 4);
1831         }
1832
1833         /* these are not actually used cuz client_configure will set them
1834            as appropriate when the window is fullscreened */
1835         x = y = w = h = 0;
1836     } else {
1837         guint num;
1838         gint32 *dimensions;
1839
1840         /* pick some fallbacks... */
1841         x = screen_area(self->desktop)->x +
1842             screen_area(self->desktop)->width / 4;
1843         y = screen_area(self->desktop)->y +
1844             screen_area(self->desktop)->height / 4;
1845         w = screen_area(self->desktop)->width / 2;
1846         h = screen_area(self->desktop)->height / 2;
1847
1848         if (PROP_GETA32(self->window, openbox_premax, cardinal,
1849                         (guint32**)&dimensions, &num)) {
1850             if (num == 4) {
1851                 x = dimensions[0];
1852                 y = dimensions[1];
1853                 w = dimensions[2];
1854                 h = dimensions[3];
1855             }
1856             g_free(dimensions);
1857         }
1858     }
1859
1860     client_setup_decor_and_functions(self);
1861
1862     client_configure(self, Corner_TopLeft, x, y, w, h, TRUE, TRUE);
1863
1864     /* try focus us when we go into fullscreen mode */
1865     client_focus(self);
1866 }
1867
1868 void client_iconify(Client *self, gboolean iconic, gboolean curdesk)
1869 {
1870     GSList *it;
1871
1872     /* move up the transient chain as far as possible first */
1873     if (self->transient_for) {
1874         if (self->transient_for != TRAN_GROUP) {
1875             if (self->transient_for->iconic != iconic) {
1876                 client_iconify(self->transient_for, iconic, curdesk);
1877                 return;
1878             }
1879         } else {
1880             GSList *it;
1881
1882             for (it = self->group->members; it; it = it->next) {
1883                 Client *c = it->data;
1884                 if (c != self && c->iconic != iconic &&
1885                     !c->transient_for) {
1886                     client_iconify(it->data, iconic, curdesk);
1887                     break;
1888                 }
1889             }
1890             if (it != NULL) return;
1891         }
1892     }
1893
1894     if (self->iconic == iconic) return; /* nothing to do */
1895
1896     g_message("%sconifying window: 0x%lx", (iconic ? "I" : "Uni"),
1897               self->window);
1898
1899     self->iconic = iconic;
1900
1901     if (iconic) {
1902         self->wmstate = IconicState;
1903         self->ignore_unmaps++;
1904         /* we unmap the client itself so that we can get MapRequest events,
1905            and because the ICCCM tells us to! */
1906         XUnmapWindow(ob_display, self->window);
1907
1908         /* update the focus lists.. iconic windows go to the bottom of the
1909          list, put the new iconic window at the 'top of the bottom'. */
1910         focus_order_to_top(self);
1911     } else {
1912         if (curdesk)
1913             client_set_desktop(self, screen_desktop, FALSE);
1914         self->wmstate = self->shaded ? IconicState : NormalState;
1915         XMapWindow(ob_display, self->window);
1916
1917         /* this puts it after the current focused window */
1918         focus_order_remove(self);
1919         focus_order_add_new(self);
1920
1921         /* this is here cuz with the VIDMODE extension, the viewport can change
1922            while a fullscreen window is iconic, and when it uniconifies, it
1923            would be nice if it did so to the new position of the viewport */
1924         client_reconfigure(self);
1925     }
1926     client_change_state(self);
1927     client_showhide(self);
1928     screen_update_struts();
1929
1930     dispatch_client(iconic ? Event_Client_Unmapped : Event_Client_Mapped,
1931                     self, 0, 0);
1932
1933     /* iconify all transients */
1934     for (it = self->transients; it != NULL; it = it->next)
1935         if (it->data != self) client_iconify(it->data, iconic, curdesk);
1936 }
1937
1938 void client_maximize(Client *self, gboolean max, int dir, gboolean savearea)
1939 {
1940     int x, y, w, h;
1941      
1942     g_assert(dir == 0 || dir == 1 || dir == 2);
1943     if (!(self->functions & Func_Maximize)) return; /* can't */
1944
1945     /* check if already done */
1946     if (max) {
1947         if (dir == 0 && self->max_horz && self->max_vert) return;
1948         if (dir == 1 && self->max_horz) return;
1949         if (dir == 2 && self->max_vert) return;
1950     } else {
1951         if (dir == 0 && !self->max_horz && !self->max_vert) return;
1952         if (dir == 1 && !self->max_horz) return;
1953         if (dir == 2 && !self->max_vert) return;
1954     }
1955
1956     /* work with the frame's coords */
1957     x = self->frame->area.x;
1958     y = self->frame->area.y;
1959     w = self->area.width;
1960     h = self->area.height;
1961
1962     if (max) {
1963         if (savearea) {
1964             gint32 dimensions[4];
1965             gint32 *readdim;
1966             guint num;
1967
1968             dimensions[0] = x;
1969             dimensions[1] = y;
1970             dimensions[2] = w;
1971             dimensions[3] = h;
1972
1973             /* get the property off the window and use it for the dimensions
1974                we are already maxed on */
1975             if (PROP_GETA32(self->window, openbox_premax, cardinal,
1976                             (guint32**)&readdim, &num)) {
1977                 if (num == 4) {
1978                     if (self->max_horz) {
1979                         dimensions[0] = readdim[0];
1980                         dimensions[2] = readdim[2];
1981                     }
1982                     if (self->max_vert) {
1983                         dimensions[1] = readdim[1];
1984                         dimensions[3] = readdim[3];
1985                     }
1986                 }
1987                 g_free(readdim);
1988             }
1989
1990             PROP_SETA32(self->window, openbox_premax, cardinal,
1991                         (guint32*)dimensions, 4);
1992         }
1993     } else {
1994         guint num;
1995         gint32 *dimensions;
1996
1997         /* pick some fallbacks... */
1998         if (dir == 0 || dir == 1) { /* horz */
1999             x = screen_area(self->desktop)->x +
2000                 screen_area(self->desktop)->width / 4;
2001             w = screen_area(self->desktop)->width / 2;
2002         }
2003         if (dir == 0 || dir == 2) { /* vert */
2004             y = screen_area(self->desktop)->y +
2005                 screen_area(self->desktop)->height / 4;
2006             h = screen_area(self->desktop)->height / 2;
2007         }
2008
2009         if (PROP_GETA32(self->window, openbox_premax, cardinal,
2010                         (guint32**)&dimensions, &num)) {
2011             if (num == 4) {
2012                 if (dir == 0 || dir == 1) { /* horz */
2013                     x = dimensions[0];
2014                     w = dimensions[2];
2015                 }
2016                 if (dir == 0 || dir == 2) { /* vert */
2017                     y = dimensions[1];
2018                     h = dimensions[3];
2019                 }
2020             }
2021             g_free(dimensions);
2022         }
2023     }
2024
2025     if (dir == 0 || dir == 1) /* horz */
2026         self->max_horz = max;
2027     if (dir == 0 || dir == 2) /* vert */
2028         self->max_vert = max;
2029
2030     if (!self->max_horz && !self->max_vert)
2031         PROP_ERASE(self->window, openbox_premax);
2032
2033     client_change_state(self); /* change the state hints on the client */
2034
2035     /* figure out where the client should be going */
2036     frame_frame_gravity(self->frame, &x, &y);
2037     client_configure(self, Corner_TopLeft, x, y, w, h, TRUE, TRUE);
2038 }
2039
2040 void client_shade(Client *self, gboolean shade)
2041 {
2042     if ((!(self->functions & Func_Shade) && shade) || /* can't shade */
2043         self->shaded == shade) return;     /* already done */
2044
2045     /* when we're iconic, don't change the wmstate */
2046     if (!self->iconic)
2047         self->wmstate = shade ? IconicState : NormalState;
2048     self->shaded = shade;
2049     client_change_state(self);
2050     /* resize the frame to just the titlebar */
2051     frame_adjust_area(self->frame, FALSE, FALSE);
2052 }
2053
2054 void client_close(Client *self)
2055 {
2056     XEvent ce;
2057
2058     if (!(self->functions & Func_Close)) return;
2059
2060     /*
2061       XXX: itd be cool to do timeouts and shit here for killing the client's
2062       process off
2063       like... if the window is around after 5 seconds, then the close button
2064       turns a nice red, and if this function is called again, the client is
2065       explicitly killed.
2066     */
2067
2068     ce.xclient.type = ClientMessage;
2069     ce.xclient.message_type =  prop_atoms.wm_protocols;
2070     ce.xclient.display = ob_display;
2071     ce.xclient.window = self->window;
2072     ce.xclient.format = 32;
2073     ce.xclient.data.l[0] = prop_atoms.wm_delete_window;
2074     ce.xclient.data.l[1] = event_lasttime;
2075     ce.xclient.data.l[2] = 0l;
2076     ce.xclient.data.l[3] = 0l;
2077     ce.xclient.data.l[4] = 0l;
2078     XSendEvent(ob_display, self->window, FALSE, NoEventMask, &ce);
2079 }
2080
2081 void client_kill(Client *self)
2082 {
2083     XKillClient(ob_display, self->window);
2084 }
2085
2086 void client_set_desktop(Client *self, guint target, gboolean donthide)
2087 {
2088     guint old;
2089
2090     if (target == self->desktop) return;
2091   
2092     g_message("Setting desktop %u", target+1);
2093
2094     g_assert(target < screen_num_desktops || target == DESKTOP_ALL);
2095
2096     /* remove from the old desktop(s) */
2097     focus_order_remove(self);
2098
2099     old = self->desktop;
2100     self->desktop = target;
2101     PROP_SET32(self->window, net_wm_desktop, cardinal, target);
2102     /* the frame can display the current desktop state */
2103     frame_adjust_state(self->frame);
2104     /* 'move' the window to the new desktop */
2105     if (!donthide)
2106         client_showhide(self);
2107     /* raise if it was not already on the desktop */
2108     if (old != DESKTOP_ALL)
2109         stacking_raise(CLIENT_AS_WINDOW(self));
2110     screen_update_struts();
2111
2112     /* add to the new desktop(s) */
2113     if (config_focus_new)
2114         focus_order_to_top(self);
2115     else
2116         focus_order_to_bottom(self);
2117
2118     dispatch_client(Event_Client_Desktop, self, target, old);
2119 }
2120
2121 Client *client_search_modal_child(Client *self)
2122 {
2123     GSList *it;
2124     Client *ret;
2125   
2126     for (it = self->transients; it != NULL; it = it->next) {
2127         Client *c = it->data;
2128         if ((ret = client_search_modal_child(c))) return ret;
2129         if (c->modal) return c;
2130     }
2131     return NULL;
2132 }
2133
2134 gboolean client_validate(Client *self)
2135 {
2136     XEvent e; 
2137
2138     XSync(ob_display, FALSE); /* get all events on the server */
2139
2140     if (XCheckTypedWindowEvent(ob_display, self->window, DestroyNotify, &e) ||
2141         XCheckTypedWindowEvent(ob_display, self->window, UnmapNotify, &e)) {
2142         XPutBackEvent(ob_display, &e);
2143         return FALSE;
2144     }
2145
2146     return TRUE;
2147 }
2148
2149 void client_set_wm_state(Client *self, long state)
2150 {
2151     if (state == self->wmstate) return; /* no change */
2152   
2153     switch (state) {
2154     case IconicState:
2155         client_iconify(self, TRUE, TRUE);
2156         break;
2157     case NormalState:
2158         client_iconify(self, FALSE, TRUE);
2159         break;
2160     }
2161 }
2162
2163 void client_set_state(Client *self, Atom action, long data1, long data2)
2164 {
2165     gboolean shaded = self->shaded;
2166     gboolean fullscreen = self->fullscreen;
2167     gboolean max_horz = self->max_horz;
2168     gboolean max_vert = self->max_vert;
2169     int i;
2170
2171     if (!(action == prop_atoms.net_wm_state_add ||
2172           action == prop_atoms.net_wm_state_remove ||
2173           action == prop_atoms.net_wm_state_toggle))
2174         /* an invalid action was passed to the client message, ignore it */
2175         return; 
2176
2177     for (i = 0; i < 2; ++i) {
2178         Atom state = i == 0 ? data1 : data2;
2179     
2180         if (!state) continue;
2181
2182         /* if toggling, then pick whether we're adding or removing */
2183         if (action == prop_atoms.net_wm_state_toggle) {
2184             if (state == prop_atoms.net_wm_state_modal)
2185                 action = self->modal ? prop_atoms.net_wm_state_remove :
2186                     prop_atoms.net_wm_state_add;
2187             else if (state == prop_atoms.net_wm_state_maximized_vert)
2188                 action = self->max_vert ? prop_atoms.net_wm_state_remove :
2189                     prop_atoms.net_wm_state_add;
2190             else if (state == prop_atoms.net_wm_state_maximized_horz)
2191                 action = self->max_horz ? prop_atoms.net_wm_state_remove :
2192                     prop_atoms.net_wm_state_add;
2193             else if (state == prop_atoms.net_wm_state_shaded)
2194                 action = self->shaded ? prop_atoms.net_wm_state_remove :
2195                     prop_atoms.net_wm_state_add;
2196             else if (state == prop_atoms.net_wm_state_skip_taskbar)
2197                 action = self->skip_taskbar ?
2198                     prop_atoms.net_wm_state_remove :
2199                     prop_atoms.net_wm_state_add;
2200             else if (state == prop_atoms.net_wm_state_skip_pager)
2201                 action = self->skip_pager ?
2202                     prop_atoms.net_wm_state_remove :
2203                     prop_atoms.net_wm_state_add;
2204             else if (state == prop_atoms.net_wm_state_fullscreen)
2205                 action = self->fullscreen ?
2206                     prop_atoms.net_wm_state_remove :
2207                     prop_atoms.net_wm_state_add;
2208             else if (state == prop_atoms.net_wm_state_above)
2209                 action = self->above ? prop_atoms.net_wm_state_remove :
2210                     prop_atoms.net_wm_state_add;
2211             else if (state == prop_atoms.net_wm_state_below)
2212                 action = self->below ? prop_atoms.net_wm_state_remove :
2213                     prop_atoms.net_wm_state_add;
2214         }
2215     
2216         if (action == prop_atoms.net_wm_state_add) {
2217             if (state == prop_atoms.net_wm_state_modal) {
2218                 /* XXX raise here or something? */
2219                 self->modal = TRUE;
2220             } else if (state == prop_atoms.net_wm_state_maximized_vert) {
2221                 max_vert = TRUE;
2222             } else if (state == prop_atoms.net_wm_state_maximized_horz) {
2223                 max_horz = TRUE;
2224             } else if (state == prop_atoms.net_wm_state_shaded) {
2225                 shaded = TRUE;
2226             } else if (state == prop_atoms.net_wm_state_skip_taskbar) {
2227                 self->skip_taskbar = TRUE;
2228             } else if (state == prop_atoms.net_wm_state_skip_pager) {
2229                 self->skip_pager = TRUE;
2230             } else if (state == prop_atoms.net_wm_state_fullscreen) {
2231                 fullscreen = TRUE;
2232             } else if (state == prop_atoms.net_wm_state_above) {
2233                 self->above = TRUE;
2234             } else if (state == prop_atoms.net_wm_state_below) {
2235                 self->below = TRUE;
2236             }
2237
2238         } else { /* action == prop_atoms.net_wm_state_remove */
2239             if (state == prop_atoms.net_wm_state_modal) {
2240                 self->modal = FALSE;
2241             } else if (state == prop_atoms.net_wm_state_maximized_vert) {
2242                 max_vert = FALSE;
2243             } else if (state == prop_atoms.net_wm_state_maximized_horz) {
2244                 max_horz = FALSE;
2245             } else if (state == prop_atoms.net_wm_state_shaded) {
2246                 shaded = FALSE;
2247             } else if (state == prop_atoms.net_wm_state_skip_taskbar) {
2248                 self->skip_taskbar = FALSE;
2249             } else if (state == prop_atoms.net_wm_state_skip_pager) {
2250                 self->skip_pager = FALSE;
2251             } else if (state == prop_atoms.net_wm_state_fullscreen) {
2252                 fullscreen = FALSE;
2253             } else if (state == prop_atoms.net_wm_state_above) {
2254                 self->above = FALSE;
2255             } else if (state == prop_atoms.net_wm_state_below) {
2256                 self->below = FALSE;
2257             }
2258         }
2259     }
2260     if (max_horz != self->max_horz || max_vert != self->max_vert) {
2261         if (max_horz != self->max_horz && max_vert != self->max_vert) {
2262             /* toggling both */
2263             if (max_horz == max_vert) { /* both going the same way */
2264                 client_maximize(self, max_horz, 0, TRUE);
2265             } else {
2266                 client_maximize(self, max_horz, 1, TRUE);
2267                 client_maximize(self, max_vert, 2, TRUE);
2268             }
2269         } else {
2270             /* toggling one */
2271             if (max_horz != self->max_horz)
2272                 client_maximize(self, max_horz, 1, TRUE);
2273             else
2274                 client_maximize(self, max_vert, 2, TRUE);
2275         }
2276     }
2277     /* change fullscreen state before shading, as it will affect if the window
2278        can shade or not */
2279     if (fullscreen != self->fullscreen)
2280         client_fullscreen(self, fullscreen, TRUE);
2281     if (shaded != self->shaded)
2282         client_shade(self, shaded);
2283     client_calc_layer(self);
2284     client_change_state(self); /* change the hint to reflect these changes */
2285 }
2286
2287 Client *client_focus_target(Client *self)
2288 {
2289     Client *child;
2290      
2291     /* if we have a modal child, then focus it, not us */
2292     child = client_search_modal_child(self);
2293     if (child) return child;
2294     return self;
2295 }
2296
2297 gboolean client_can_focus(Client *self)
2298 {
2299     XEvent ev;
2300
2301     /* choose the correct target */
2302     self = client_focus_target(self);
2303
2304     if (!self->frame->visible)
2305         return FALSE;
2306
2307     if (!((self->can_focus || self->focus_notify) &&
2308           (self->desktop == screen_desktop ||
2309            self->desktop == DESKTOP_ALL) &&
2310           !self->iconic))
2311         return FALSE;
2312
2313     /* do a check to see if the window has already been unmapped or destroyed
2314        do this intelligently while watching out for unmaps we've generated
2315        (ignore_unmaps > 0) */
2316     if (XCheckTypedWindowEvent(ob_display, self->window,
2317                                DestroyNotify, &ev)) {
2318         XPutBackEvent(ob_display, &ev);
2319         return FALSE;
2320     }
2321     while (XCheckTypedWindowEvent(ob_display, self->window,
2322                                   UnmapNotify, &ev)) {
2323         if (self->ignore_unmaps) {
2324             self->ignore_unmaps--;
2325         } else {
2326             XPutBackEvent(ob_display, &ev);
2327             return FALSE;
2328         }
2329     }
2330
2331     return TRUE;
2332 }
2333
2334 gboolean client_focus(Client *self)
2335 {
2336     /* choose the correct target */
2337     self = client_focus_target(self);
2338
2339     if (!client_can_focus(self)) {
2340         if (!self->frame->visible) {
2341             /* update the focus lists */
2342             focus_order_to_top(self);
2343         }
2344         return FALSE;
2345     }
2346
2347     if (self->can_focus)
2348         /* RevertToPointerRoot causes much more headache than RevertToNone, so
2349            I choose to use it always, hopefully to find errors quicker, if any
2350            are left. (I hate X. I hate focus events.) */
2351         XSetInputFocus(ob_display, self->window, RevertToPointerRoot,
2352                        event_lasttime);
2353
2354     if (self->focus_notify) {
2355         XEvent ce;
2356         ce.xclient.type = ClientMessage;
2357         ce.xclient.message_type = prop_atoms.wm_protocols;
2358         ce.xclient.display = ob_display;
2359         ce.xclient.window = self->window;
2360         ce.xclient.format = 32;
2361         ce.xclient.data.l[0] = prop_atoms.wm_take_focus;
2362         ce.xclient.data.l[1] = event_lasttime;
2363         ce.xclient.data.l[2] = 0l;
2364         ce.xclient.data.l[3] = 0l;
2365         ce.xclient.data.l[4] = 0l;
2366         XSendEvent(ob_display, self->window, FALSE, NoEventMask, &ce);
2367     }
2368
2369 #ifdef DEBUG_FOCUS
2370     g_message("%sively focusing %lx at %d", (self->can_focus ? "act" : "pass"),
2371               self->window, (int)
2372               event_lasttime);
2373 #endif
2374
2375     /* Cause the FocusIn to come back to us. Important for desktop switches,
2376        since otherwise we'll have no FocusIn on the queue and send it off to
2377        the focus_backup. */
2378     XSync(ob_display, FALSE);
2379     return TRUE;
2380 }
2381
2382 void client_unfocus(Client *self)
2383 {
2384     g_assert(focus_client == self);
2385 #ifdef DEBUG_FOCUS
2386     g_message("client_unfocus for %lx", self->window);
2387 #endif
2388     focus_fallback(Fallback_Unfocusing);
2389 }
2390
2391 void client_activate(Client *self)
2392 {
2393     if (client_normal(self) && screen_showing_desktop)
2394         screen_show_desktop(FALSE);
2395     if (self->iconic)
2396         client_iconify(self, FALSE, TRUE);
2397     else if (!self->frame->visible)
2398         /* if its not visible for other reasons, then don't mess
2399            with it */
2400         return;
2401     if (self->shaded)
2402         client_shade(self, FALSE);
2403     client_focus(self);
2404     stacking_raise(CLIENT_AS_WINDOW(self));
2405 }
2406
2407 gboolean client_focused(Client *self)
2408 {
2409     return self == focus_client;
2410 }
2411
2412 Icon *client_icon(Client *self, int w, int h)
2413 {
2414     int i;
2415     /* si is the smallest image >= req */
2416     /* li is the largest image < req */
2417     unsigned long size, smallest = 0xffffffff, largest = 0, si = 0, li = 0;
2418
2419     if (!self->nicons) return NULL;
2420
2421     for (i = 0; i < self->nicons; ++i) {
2422         size = self->icons[i].width * self->icons[i].height;
2423         if (size < smallest && size >= (unsigned)(w * h)) {
2424             smallest = size;
2425             si = i;
2426         }
2427         if (size > largest && size <= (unsigned)(w * h)) {
2428             largest = size;
2429             li = i;
2430         }
2431     }
2432     if (largest == 0) /* didnt find one smaller than the requested size */
2433         return &self->icons[si];
2434     return &self->icons[li];
2435 }
2436
2437 /* this be mostly ripped from fvwm */
2438 Client *client_find_directional(Client *c, Direction dir) 
2439 {
2440     int my_cx, my_cy, his_cx, his_cy;
2441     int offset = 0;
2442     int distance = 0;
2443     int score, best_score;
2444     Client *best_client, *cur;
2445     GList *it;
2446
2447     if(!client_list)
2448         return NULL;
2449
2450     /* first, find the centre coords of the currently focused window */
2451     my_cx = c->frame->area.x + c->frame->area.width / 2;
2452     my_cy = c->frame->area.y + c->frame->area.height / 2;
2453
2454     best_score = -1;
2455     best_client = NULL;
2456
2457     for(it = g_list_first(client_list); it; it = it->next) {
2458         cur = it->data;
2459
2460         /* the currently selected window isn't interesting */
2461         if(cur == c)
2462             continue;
2463         if (!client_normal(cur))
2464             continue;
2465         if(c->desktop != cur->desktop && cur->desktop != DESKTOP_ALL)
2466             continue;
2467         if(cur->iconic)
2468             continue;
2469         if(client_focus_target(cur) == cur &&
2470            !(cur->can_focus || cur->focus_notify))
2471             continue;
2472
2473         /* find the centre coords of this window, from the
2474          * currently focused window's point of view */
2475         his_cx = (cur->frame->area.x - my_cx)
2476             + cur->frame->area.width / 2;
2477         his_cy = (cur->frame->area.y - my_cy)
2478             + cur->frame->area.height / 2;
2479
2480         if(dir > 3) { 
2481             int tx;
2482             /* Rotate the diagonals 45 degrees counterclockwise.
2483              * To do this, multiply the matrix /+h +h\ with the
2484              * vector (x y).                   \-h +h/
2485              * h = sqrt(0.5). We can set h := 1 since absolute
2486              * distance doesn't matter here. */
2487             tx = his_cx + his_cy;
2488             his_cy = -his_cx + his_cy;
2489             his_cx = tx;
2490         }
2491
2492         switch(dir) {
2493         case Direction_North :
2494         case Direction_South :
2495         case Direction_NorthEast :
2496         case Direction_SouthWest :
2497             offset = (his_cx < 0) ? -his_cx : his_cx;
2498             distance = (dir == Direction_North || dir == Direction_NorthEast) ?
2499                 -his_cy : his_cy;
2500             break;
2501         case Direction_East :
2502         case Direction_West :
2503         case Direction_SouthEast :
2504         case Direction_NorthWest :
2505             offset = (his_cy < 0) ? -his_cy : his_cy;
2506             distance = (dir == Direction_West || dir == Direction_NorthWest) ?
2507                 -his_cx : his_cx;
2508             break;
2509         }
2510
2511         /* the target must be in the requested direction */
2512         if(distance <= 0)
2513             continue;
2514
2515         /* Calculate score for this window.  The smaller the better. */
2516         score = distance + offset;
2517
2518         /* windows more than 45 degrees off the direction are
2519          * heavily penalized and will only be chosen if nothing
2520          * else within a million pixels */
2521         if(offset > distance)
2522             score += 1000000;
2523
2524         if(best_score == -1 || score < best_score)
2525             best_client = cur,
2526                 best_score = score;
2527     }
2528
2529     return best_client;
2530 }
2531
2532 void client_set_layer(Client *self, int layer)
2533 {
2534     if (layer < 0) {
2535         self->below = TRUE;
2536         self->above = FALSE;
2537     } else if (layer == 0) {
2538         self->below = self->above = FALSE;
2539     } else {
2540         self->below = FALSE;
2541         self->above = TRUE;
2542     }
2543     client_calc_layer(self);
2544     client_change_state(self); /* reflect this in the state hints */
2545 }