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