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