set the frame's initial size to something invalid so the extents hint will be
[dana/openbox.git] / openbox / client.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2
3    client.c for the Openbox window manager
4    Copyright (c) 2006        Mikael Magnusson
5    Copyright (c) 2003-2007   Dana Jansens
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    See the COPYING file for a copy of the GNU General Public License.
18 */
19
20 #include "client.h"
21 #include "debug.h"
22 #include "startupnotify.h"
23 #include "dock.h"
24 #include "screen.h"
25 #include "moveresize.h"
26 #include "ping.h"
27 #include "place.h"
28 #include "frame.h"
29 #include "session.h"
30 #include "event.h"
31 #include "grab.h"
32 #include "prompt.h"
33 #include "focus.h"
34 #include "focus_cycle.h"
35 #include "stacking.h"
36 #include "openbox.h"
37 #include "group.h"
38 #include "config.h"
39 #include "menuframe.h"
40 #include "keyboard.h"
41 #include "mouse.h"
42 #include "obrender/render.h"
43 #include "gettext.h"
44 #include "obt/display.h"
45 #include "obt/xqueue.h"
46 #include "obt/prop.h"
47
48 #ifdef HAVE_UNISTD_H
49 #  include <unistd.h>
50 #endif
51
52 #ifdef HAVE_SIGNAL_H
53 #  include <signal.h> /* for kill() */
54 #endif
55
56 #include <glib.h>
57 #include <X11/Xutil.h>
58
59 /*! The event mask to grab on client windows */
60 #define CLIENT_EVENTMASK (PropertyChangeMask | StructureNotifyMask | \
61                           ColormapChangeMask)
62
63 #define CLIENT_NOPROPAGATEMASK (ButtonPressMask | ButtonReleaseMask | \
64                                 ButtonMotionMask)
65
66 typedef struct
67 {
68     ObClientCallback func;
69     gpointer data;
70 } ClientCallback;
71
72 GList          *client_list             = NULL;
73
74 static GSList  *client_destroy_notifies = NULL;
75 static RrImage *client_default_icon     = NULL;
76
77 static void client_get_all(ObClient *self, gboolean real);
78 static void client_get_startup_id(ObClient *self);
79 static void client_get_session_ids(ObClient *self);
80 static void client_save_app_rule_values(ObClient *self);
81 static void client_get_area(ObClient *self);
82 static void client_get_desktop(ObClient *self);
83 static void client_get_state(ObClient *self);
84 static void client_get_shaped(ObClient *self);
85 static void client_get_colormap(ObClient *self);
86 static void client_set_desktop_recursive(ObClient *self,
87                                          guint target,
88                                          gboolean donthide,
89                                          gboolean dontraise);
90 static void client_change_allowed_actions(ObClient *self);
91 static void client_change_state(ObClient *self);
92 static void client_change_wm_state(ObClient *self);
93 static void client_apply_startup_state(ObClient *self,
94                                        gint x, gint y, gint w, gint h);
95 static void client_restore_session_state(ObClient *self);
96 static gboolean client_restore_session_stacking(ObClient *self);
97 static ObAppSettings *client_get_settings_state(ObClient *self);
98 static void client_update_transient_tree(ObClient *self,
99                                          ObGroup *oldgroup, ObGroup *newgroup,
100                                          gboolean oldgtran, gboolean newgtran,
101                                          ObClient* oldparent,
102                                          ObClient *newparent);
103 static void client_present(ObClient *self, gboolean here, gboolean raise,
104                            gboolean unshade);
105 static GSList *client_search_all_top_parents_internal(ObClient *self,
106                                                       gboolean bylayer,
107                                                       ObStackingLayer layer);
108 static void client_call_notifies(ObClient *self, GSList *list);
109 static void client_ping_event(ObClient *self, gboolean dead);
110 static void client_prompt_kill(ObClient *self);
111 static gboolean client_can_steal_focus(ObClient *self, Time steal_time,
112                                        Time launch_time);
113
114 void client_startup(gboolean reconfig)
115 {
116     if ((client_default_icon = RrImageCacheFind(ob_rr_icons,
117                                                 ob_rr_theme->def_win_icon,
118                                                 ob_rr_theme->def_win_icon_w,
119                                                 ob_rr_theme->def_win_icon_h)))
120         RrImageRef(client_default_icon);
121     else {
122         client_default_icon = RrImageNew(ob_rr_icons);
123         RrImageAddPicture(client_default_icon,
124                           ob_rr_theme->def_win_icon,
125                           ob_rr_theme->def_win_icon_w,
126                           ob_rr_theme->def_win_icon_h);
127     }
128
129     if (reconfig) return;
130
131     client_set_list();
132 }
133
134 void client_shutdown(gboolean reconfig)
135 {
136     RrImageUnref(client_default_icon);
137     client_default_icon = NULL;
138
139     if (reconfig) return;
140 }
141
142 static void client_call_notifies(ObClient *self, GSList *list)
143 {
144     GSList *it;
145
146     for (it = list; it; it = g_slist_next(it)) {
147         ClientCallback *d = it->data;
148         d->func(self, d->data);
149     }
150 }
151
152 void client_add_destroy_notify(ObClientCallback func, gpointer data)
153 {
154     ClientCallback *d = g_slice_new(ClientCallback);
155     d->func = func;
156     d->data = data;
157     client_destroy_notifies = g_slist_prepend(client_destroy_notifies, d);
158 }
159
160 void client_remove_destroy_notify(ObClientCallback func)
161 {
162     GSList *it;
163
164     for (it = client_destroy_notifies; it; it = g_slist_next(it)) {
165         ClientCallback *d = it->data;
166         if (d->func == func) {
167             g_slice_free(ClientCallback, d);
168             client_destroy_notifies =
169                 g_slist_delete_link(client_destroy_notifies, it);
170             break;
171         }
172     }
173 }
174
175 void client_set_list(void)
176 {
177     Window *windows, *win_it;
178     GList *it;
179     guint size = g_list_length(client_list);
180
181     /* create an array of the window ids */
182     if (size > 0) {
183         windows = g_new(Window, size);
184         win_it = windows;
185         for (it = client_list; it; it = g_list_next(it), ++win_it)
186             *win_it = ((ObClient*)it->data)->window;
187     } else
188         windows = NULL;
189
190     OBT_PROP_SETA32(obt_root(ob_screen), NET_CLIENT_LIST, WINDOW,
191                     (gulong*)windows, size);
192
193     if (windows)
194         g_free(windows);
195
196     stacking_set_list();
197 }
198
199 void client_manage(Window window, ObPrompt *prompt)
200 {
201     ObClient *self;
202     XSetWindowAttributes attrib_set;
203     gboolean activate = FALSE;
204     ObAppSettings *settings;
205     gboolean transient = FALSE;
206     Rect place;
207     Time launch_time;
208     guint32 user_time;
209     gboolean obplaced;
210
211     ob_debug("Managing window: 0x%lx", window);
212
213     /* choose the events we want to receive on the CLIENT window
214        (ObPrompt windows can request events too) */
215     attrib_set.event_mask = CLIENT_EVENTMASK |
216         (prompt ? prompt->event_mask : 0);
217     attrib_set.do_not_propagate_mask = CLIENT_NOPROPAGATEMASK;
218     XChangeWindowAttributes(obt_display, window,
219                             CWEventMask|CWDontPropagate, &attrib_set);
220
221     /* create the ObClient struct, and populate it from the hints on the
222        window */
223     self = g_slice_new0(ObClient);
224     self->obwin.type = OB_WINDOW_CLASS_CLIENT;
225     self->window = window;
226     self->prompt = prompt;
227     self->managed = TRUE;
228
229     /* non-zero defaults */
230     self->wmstate = WithdrawnState; /* make sure it gets updated first time */
231     self->gravity = NorthWestGravity;
232     self->desktop = screen_num_desktops; /* always an invalid value */
233
234     /* get all the stuff off the window */
235     client_get_all(self, TRUE);
236
237     ob_debug("Window type: %d", self->type);
238     ob_debug("Window group: 0x%x", self->group?self->group->leader:0);
239     ob_debug("Window name: %s class: %s role: %s title: %s",
240              self->name, self->class, self->role, self->title);
241
242     /* per-app settings override stuff from client_get_all, and return the
243        settings for other uses too. the returned settings is a shallow copy,
244        that needs to be freed with g_free(). */
245     settings = client_get_settings_state(self);
246
247     /* now we have all of the window's information so we can set this up.
248        do this before creating the frame, so it can tell that we are still
249        mapping and doesn't go applying things right away */
250     client_setup_decor_and_functions(self, FALSE);
251
252     /* specify that if we exit, the window should not be destroyed and
253        should be reparented back to root automatically, unless we are managing
254        an internal ObPrompt window  */
255     if (!self->prompt)
256         XChangeSaveSet(obt_display, window, SetModeInsert);
257
258     /* create the decoration frame for the client window */
259     self->frame = frame_new(self);
260
261     frame_grab_client(self->frame);
262
263     /* we've grabbed everything and set everything that we need to at mapping
264        time now */
265     grab_server(FALSE);
266
267     /* the session should get the last say though */
268     client_restore_session_state(self);
269
270     /* tell startup notification that this app started */
271     launch_time = sn_app_started(self->startup_id, self->class, self->name);
272
273     if (!OBT_PROP_GET32(self->window, NET_WM_USER_TIME, CARDINAL, &user_time))
274         user_time = event_time();
275
276     /* do this after we have a frame.. it uses the frame to help determine the
277        WM_STATE to apply. */
278     client_change_state(self);
279
280     /* add ourselves to the focus order */
281     focus_order_add_new(self);
282
283     /* do this to add ourselves to the stacking list in a non-intrusive way */
284     client_calc_layer(self);
285
286     /* focus the new window? */
287     if (ob_state() != OB_STATE_STARTING &&
288         (!self->session || self->session->focused) &&
289         /* this means focus=true for window is same as config_focus_new=true */
290         ((config_focus_new || (settings && settings->focus == 1)) ||
291          client_search_focus_tree_full(self)) &&
292         /* NET_WM_USER_TIME 0 when mapping means don't focus */
293         (user_time != 0) &&
294         /* this checks for focus=false for the window */
295         (!settings || settings->focus != 0) &&
296         focus_valid_target(self, self->desktop,
297                            FALSE, FALSE, TRUE, TRUE, FALSE, FALSE,
298                            settings->focus == 1))
299     {
300         activate = TRUE;
301     }
302
303     /* remove the client's border */
304     XSetWindowBorderWidth(obt_display, self->window, 0);
305
306     /* adjust the frame to the client's size before showing or placing
307        the window */
308     frame_adjust_area(self->frame, FALSE, TRUE, FALSE);
309     frame_adjust_client_area(self->frame);
310
311     /* where the frame was placed is where the window was originally */
312     place = self->area;
313
314     /* figure out placement for the window if the window is new */
315     if (ob_state() == OB_STATE_RUNNING) {
316         ob_debug("Positioned: %s @ %d %d",
317                  (!self->positioned ? "no" :
318                   (self->positioned == PPosition ? "program specified" :
319                    (self->positioned == USPosition ? "user specified" :
320                     (self->positioned == (PPosition | USPosition) ?
321                      "program + user specified" :
322                      "BADNESS !?")))), place.x, place.y);
323
324         ob_debug("Sized: %s @ %d %d",
325                  (!self->sized ? "no" :
326                   (self->sized == PSize ? "program specified" :
327                    (self->sized == USSize ? "user specified" :
328                     (self->sized == (PSize | USSize) ?
329                      "program + user specified" :
330                      "BADNESS !?")))), place.width, place.height);
331
332         obplaced = place_client(self, &place.x, &place.y, settings);
333
334         /* watch for buggy apps that ask to be placed at (0,0) when there is
335            a strut there */
336         if (!obplaced && place.x == 0 && place.y == 0 &&
337             /* non-normal windows are allowed */
338             client_normal(self) &&
339             /* oldschool fullscreen windows are allowed */
340             !client_is_oldfullscreen(self, &place))
341         {
342             Rect *r;
343
344             r = screen_area(self->desktop, SCREEN_AREA_ALL_MONITORS, NULL);
345             if (r->x || r->y) {
346                 place.x = r->x;
347                 place.y = r->y;
348                 ob_debug("Moving buggy app from (0,0) to (%d,%d)", r->x, r->y);
349             }
350             g_slice_free(Rect, r);
351         }
352
353         /* make sure the window is visible. */
354         client_find_onscreen(self, &place.x, &place.y,
355                              place.width, place.height,
356                              /* non-normal clients has less rules, and
357                                 windows that are being restored from a
358                                 session do also. we can assume you want
359                                 it back where you saved it. Clients saying
360                                 they placed themselves are subjected to
361                                 harder rules, ones that are placed by
362                                 place.c or by the user are allowed partially
363                                 off-screen and on xinerama divides (ie,
364                                 it is up to the placement routines to avoid
365                                 the xinerama divides)
366
367                                 children and splash screens are forced on
368                                 screen, but i don't remember why i decided to
369                                 do that.
370                              */
371                              ob_state() == OB_STATE_RUNNING &&
372                              (self->type == OB_CLIENT_TYPE_DIALOG ||
373                               self->type == OB_CLIENT_TYPE_SPLASH ||
374                               (!((self->positioned & USPosition) ||
375                                  (settings && settings->pos_given)) &&
376                                client_normal(self) &&
377                                !self->session &&
378                                /* don't move oldschool fullscreen windows to
379                                   fit inside the struts (fixes Acroread, which
380                                   makes its fullscreen window fit the screen
381                                   but it is not USSize'd or USPosition'd) */
382                                !client_is_oldfullscreen(self, &place))));
383     }
384
385     /* if the window isn't user-sized, then make it fit inside
386        the visible screen area on its monitor. Use basically the same rules
387        for forcing the window on screen in the client_find_onscreen call.
388
389        do this after place_client, it chooses the monitor!
390
391        splash screens get "transient" set to TRUE by
392        the place_client call
393     */
394     if (ob_state() == OB_STATE_RUNNING &&
395         (transient ||
396          (!(self->sized & USSize || self->positioned & USPosition) &&
397           client_normal(self) &&
398           !self->session &&
399           /* don't shrink oldschool fullscreen windows to fit inside the
400              struts (fixes Acroread, which makes its fullscreen window
401              fit the screen but it is not USSize'd or USPosition'd) */
402           !client_is_oldfullscreen(self, &place))))
403     {
404         Rect *a = screen_area(self->desktop, SCREEN_AREA_ONE_MONITOR, &place);
405
406         /* get the size of the frame */
407         place.width += self->frame->size.left + self->frame->size.right;
408         place.height += self->frame->size.top + self->frame->size.bottom;
409
410         /* fit the window inside the area */
411         place.width = MIN(place.width, a->width);
412         place.height = MIN(place.height, a->height);
413
414         ob_debug("setting window size to %dx%d", place.width, place.height);
415
416         /* get the size of the client back */
417         place.width -= self->frame->size.left + self->frame->size.right;
418         place.height -= self->frame->size.top + self->frame->size.bottom;
419
420         g_slice_free(Rect, a);
421     }
422
423     ob_debug("placing window 0x%x at %d, %d with size %d x %d. "
424              "some restrictions may apply",
425              self->window, place.x, place.y, place.width, place.height);
426     if (self->session)
427         ob_debug("  but session requested %d, %d  %d x %d instead, "
428                  "overriding",
429                  self->session->x, self->session->y,
430                  self->session->w, self->session->h);
431
432     /* do this after the window is placed, so the premax/prefullscreen numbers
433        won't be all wacko!!
434
435        this also places the window
436     */
437     client_apply_startup_state(self, place.x, place.y,
438                                place.width, place.height);
439
440     ob_debug_type(OB_DEBUG_FOCUS, "Going to try activate new window? %s",
441                   activate ? "yes" : "no");
442     if (activate) {
443         activate = client_can_steal_focus(self, event_time(), launch_time);
444
445         if (!activate) {
446             /* if the client isn't stealing focus, then hilite it so the user
447                knows it is there, but don't do this if we're restoring from a
448                session */
449             if (!client_restore_session_stacking(self))
450                 client_hilite(self, TRUE);
451         }
452     }
453     else {
454         /* This may look rather odd. Well it's because new windows are added
455            to the stacking order non-intrusively. If we're not going to focus
456            the new window or hilite it, then we raise it to the top. This will
457            take affect for things that don't get focused like splash screens.
458            Also if you don't have focus_new enabled, then it's going to get
459            raised to the top. Legacy begets legacy I guess?
460         */
461         if (!client_restore_session_stacking(self))
462             stacking_raise(CLIENT_AS_WINDOW(self));
463     }
464
465     mouse_grab_for_client(self, TRUE);
466
467     /* this has to happen before we try focus the window, but we want it to
468        happen after the client's stacking has been determined or it looks bad
469     */
470     {
471         gulong ignore_start;
472         if (!config_focus_under_mouse)
473             ignore_start = event_start_ignore_all_enters();
474
475         client_show(self);
476
477         if (!config_focus_under_mouse)
478             event_end_ignore_all_enters(ignore_start);
479     }
480
481     if (activate) {
482         gboolean stacked = client_restore_session_stacking(self);
483         client_present(self, FALSE, !stacked, TRUE);
484     }
485
486     /* add to client list/map */
487     client_list = g_list_append(client_list, self);
488     window_add(&self->window, CLIENT_AS_WINDOW(self));
489
490     /* this has to happen after we're in the client_list */
491     if (STRUT_EXISTS(self->strut))
492         screen_update_areas();
493
494     /* update the list hints */
495     client_set_list();
496
497     /* free the ObAppSettings shallow copy */
498     g_slice_free(ObAppSettings, settings);
499
500     ob_debug("Managed window 0x%lx plate 0x%x (%s)",
501              window, self->frame->window, self->class);
502 }
503
504 ObClient *client_fake_manage(Window window)
505 {
506     ObClient *self;
507     ObAppSettings *settings;
508
509     ob_debug("Pretend-managing window: %lx", window);
510
511     /* do this minimal stuff to figure out the client's decorations */
512
513     self = g_slice_new0(ObClient);
514     self->window = window;
515
516     client_get_all(self, FALSE);
517     /* per-app settings override stuff, and return the settings for other
518        uses too. this returns a shallow copy that needs to be freed */
519     settings = client_get_settings_state(self);
520
521     client_setup_decor_and_functions(self, FALSE);
522
523     /* create the decoration frame for the client window and adjust its size */
524     self->frame = frame_new(self);
525     frame_adjust_area(self->frame, FALSE, TRUE, TRUE);
526
527     ob_debug("gave extents left %d right %d top %d bottom %d",
528              self->frame->size.left, self->frame->size.right,
529              self->frame->size.top, self->frame->size.bottom);
530
531     /* free the ObAppSettings shallow copy */
532     g_slice_free(ObAppSettings, settings);
533
534     return self;
535 }
536
537 void client_unmanage_all(void)
538 {
539     while (client_list)
540         client_unmanage(client_list->data);
541 }
542
543 void client_unmanage(ObClient *self)
544 {
545     GSList *it;
546     gulong ignore_start;
547
548     ob_debug("Unmanaging window: 0x%x plate 0x%x (%s) (%s)",
549              self->window, self->frame->window,
550              self->class, self->title ? self->title : "");
551
552     g_assert(self != NULL);
553
554     /* we dont want events no more. do this before hiding the frame so we
555        don't generate more events */
556     XSelectInput(obt_display, self->window, NoEventMask);
557
558     /* ignore enter events from the unmap so it doesnt mess with the focus */
559     if (!config_focus_under_mouse)
560         ignore_start = event_start_ignore_all_enters();
561
562     frame_hide(self->frame);
563     /* flush to send the hide to the server quickly */
564     XFlush(obt_display);
565
566     if (!config_focus_under_mouse)
567         event_end_ignore_all_enters(ignore_start);
568
569     mouse_grab_for_client(self, FALSE);
570
571     self->managed = FALSE;
572
573     /* remove the window from our save set, unless we are managing an internal
574        ObPrompt window */
575     if (!self->prompt)
576         XChangeSaveSet(obt_display, self->window, SetModeDelete);
577
578     /* update the focus lists */
579     focus_order_remove(self);
580     if (client_focused(self)) {
581         /* don't leave an invalid focus_client */
582         focus_client = NULL;
583     }
584
585     /* if we're prompting to kill the client, close that */
586     prompt_unref(self->kill_prompt);
587     self->kill_prompt = NULL;
588
589     client_list = g_list_remove(client_list, self);
590     stacking_remove(self);
591     window_remove(self->window);
592
593     /* once the client is out of the list, update the struts to remove its
594        influence */
595     if (STRUT_EXISTS(self->strut))
596         screen_update_areas();
597
598     client_call_notifies(self, client_destroy_notifies);
599
600     /* tell our parent(s) that we're gone */
601     for (it = self->parents; it; it = g_slist_next(it))
602         ((ObClient*)it->data)->transients =
603             g_slist_remove(((ObClient*)it->data)->transients,self);
604
605     /* tell our transients that we're gone */
606     for (it = self->transients; it; it = g_slist_next(it)) {
607         ((ObClient*)it->data)->parents =
608             g_slist_remove(((ObClient*)it->data)->parents, self);
609         /* we could be keeping our children in a higher layer */
610         client_calc_layer(it->data);
611     }
612
613     /* remove from its group */
614     if (self->group) {
615         group_remove(self->group, self);
616         self->group = NULL;
617     }
618
619     /* restore the window's original geometry so it is not lost */
620     {
621         Rect a;
622
623         a = self->area;
624
625         if (self->fullscreen)
626             a = self->pre_fullscreen_area;
627         else if (self->max_horz || self->max_vert) {
628             if (self->max_horz) {
629                 a.x = self->pre_max_area.x;
630                 a.width = self->pre_max_area.width;
631             }
632             if (self->max_vert) {
633                 a.y = self->pre_max_area.y;
634                 a.height = self->pre_max_area.height;
635             }
636         }
637
638         self->fullscreen = self->max_horz = self->max_vert = FALSE;
639         /* let it be moved and resized no matter what */
640         self->functions = OB_CLIENT_FUNC_MOVE | OB_CLIENT_FUNC_RESIZE;
641         self->decorations = 0; /* unmanaged windows have no decor */
642
643         /* give the client its border back */
644         XSetWindowBorderWidth(obt_display, self->window, self->border_width);
645
646         client_move_resize(self, a.x, a.y, a.width, a.height);
647     }
648
649     /* reparent the window out of the frame, and free the frame */
650     frame_release_client(self->frame);
651     frame_free(self->frame);
652     self->frame = NULL;
653
654     if (ob_state() != OB_STATE_EXITING) {
655         /* these values should not be persisted across a window
656            unmapping/mapping */
657         OBT_PROP_ERASE(self->window, NET_WM_DESKTOP);
658         OBT_PROP_ERASE(self->window, NET_WM_STATE);
659         OBT_PROP_ERASE(self->window, WM_STATE);
660     } else {
661         /* if we're left in an unmapped state, the client wont be mapped.
662            this is bad, since we will no longer be managing the window on
663            restart */
664         XMapWindow(obt_display, self->window);
665     }
666
667     /* these should not be left on the window ever.  other window managers
668        don't necessarily use them and it will mess them up (like compiz) */
669     OBT_PROP_ERASE(self->window, NET_WM_VISIBLE_NAME);
670     OBT_PROP_ERASE(self->window, NET_WM_VISIBLE_ICON_NAME);
671
672     /* update the list hints */
673     client_set_list();
674
675     ob_debug("Unmanaged window 0x%lx", self->window);
676
677     /* free all data allocated in the client struct */
678     RrImageUnref(self->icon_set);
679     g_slist_free(self->transients);
680     g_free(self->startup_id);
681     g_free(self->wm_command);
682     g_free(self->title);
683     g_free(self->icon_title);
684     g_free(self->original_title);
685     g_free(self->name);
686     g_free(self->class);
687     g_free(self->role);
688     g_free(self->client_machine);
689     g_free(self->sm_client_id);
690     g_slice_free(ObClient, self);
691 }
692
693 void client_fake_unmanage(ObClient *self)
694 {
695     /* this is all that got allocated to get the decorations */
696
697     frame_free(self->frame);
698     g_slice_free(ObClient, self);
699 }
700
701 static gboolean client_can_steal_focus(ObClient *self, Time steal_time,
702                                        Time launch_time)
703 {
704     gboolean steal;
705     gboolean relative_focused;
706     gboolean parent_focused;
707
708     steal = TRUE;
709
710     parent_focused = (focus_client != NULL &&
711                       client_search_focus_parent(self));
712     relative_focused = (focus_client != NULL &&
713                         (client_search_focus_tree_full(self) != NULL ||
714                          client_search_focus_group_full(self) != NULL));
715
716     /* This is focus stealing prevention */
717     ob_debug_type(OB_DEBUG_FOCUS,
718                   "Want to focus window 0x%x at time %u "
719                   "launched at %u (last user interaction time %u)",
720                   self->window, steal_time, launch_time,
721                   event_last_user_time);
722
723     /* if it's on another desktop */
724     if (!(self->desktop == screen_desktop ||
725           self->desktop == DESKTOP_ALL) &&
726         /* the timestamp is from before you changed desktops */
727         (!launch_time ||
728          (screen_desktop_user_time &&
729           !event_time_after(launch_time, screen_desktop_user_time))))
730     {
731         steal = FALSE;
732         ob_debug_type(OB_DEBUG_FOCUS,
733                       "Not focusing the window because its on another "
734                       "desktop\n");
735     }
736     /* If something is focused... */
737     else if (focus_client) {
738         /* If the user is working in another window right now, then don't
739            steal focus */
740         if (!parent_focused &&
741             event_last_user_time && launch_time &&
742             event_time_after(event_last_user_time, launch_time) &&
743             event_last_user_time != launch_time &&
744             event_time_after(event_last_user_time,
745                              steal_time - OB_EVENT_USER_TIME_DELAY))
746         {
747             steal = FALSE;
748             ob_debug_type(OB_DEBUG_FOCUS,
749                           "Not focusing the window because the user is "
750                           "working in another window that is not "
751                           "its parent");
752         }
753         /* If the new window is a transient (and its relatives aren't
754            focused) */
755         else if (client_has_parent(self) && !relative_focused) {
756             steal = FALSE;
757             ob_debug_type(OB_DEBUG_FOCUS,
758                           "Not focusing the window because it is a "
759                           "transient, and its relatives aren't focused");
760         }
761         /* Don't steal focus from globally active clients.
762            I stole this idea from KWin. It seems nice.
763         */
764         else if (!(focus_client->can_focus ||
765                    focus_client->focus_notify))
766         {
767             steal = FALSE;
768             ob_debug_type(OB_DEBUG_FOCUS,
769                           "Not focusing the window because a globally "
770                           "active client has focus");
771         }
772         /* Don't move focus if it's not going to go to this window
773            anyway */
774         else if (client_focus_target(self) != self) {
775             steal = FALSE;
776             ob_debug_type(OB_DEBUG_FOCUS,
777                           "Not focusing the window because another window "
778                           "would get the focus anyway");
779         }
780         /* Don't move focus if the window is not visible on the current
781            desktop and none of its relatives are focused */
782         else if (!(self->desktop == screen_desktop ||
783                    self->desktop == DESKTOP_ALL) &&
784                  !relative_focused)
785         {
786             steal = FALSE;
787             ob_debug_type(OB_DEBUG_FOCUS,
788                           "Not focusing the window because it is on "
789                           "another desktop and no relatives are focused ");
790         }
791     }
792
793     if (!steal)
794         ob_debug_type(OB_DEBUG_FOCUS,
795                       "Focus stealing prevention activated for %s at "
796                       "time %u (last user interaction time %u)",
797                       self->title, steal_time, event_last_user_time);
798     return steal;
799 }
800
801 /*! Returns a new structure containing the per-app settings for this client.
802   The returned structure needs to be freed with g_free. */
803 static ObAppSettings *client_get_settings_state(ObClient *self)
804 {
805     ObAppSettings *settings;
806     GSList *it;
807
808     settings = config_create_app_settings();
809
810     for (it = config_per_app_settings; it; it = g_slist_next(it)) {
811         ObAppSettings *app = it->data;
812         gboolean match = TRUE;
813
814         g_assert(app->name != NULL || app->class != NULL ||
815                  app->role != NULL || app->title != NULL ||
816                  (signed)app->type >= 0);
817
818         if (app->name &&
819             !g_pattern_match(app->name, strlen(self->name), self->name, NULL))
820             match = FALSE;
821         else if (app->class &&
822                  !g_pattern_match(app->class,
823                                   strlen(self->class), self->class, NULL))
824             match = FALSE;
825         else if (app->role &&
826                  !g_pattern_match(app->role,
827                                   strlen(self->role), self->role, NULL))
828             match = FALSE;
829         else if (app->title &&
830                  !g_pattern_match(app->title,
831                                   strlen(self->title), self->title, NULL))
832             match = FALSE;
833         else if ((signed)app->type >= 0 && app->type != self->type) {
834             match = FALSE;
835         }
836
837         if (match) {
838             ob_debug("Window matching: %s", app->name);
839
840             /* copy the settings to our struct, overriding the existing
841                settings if they are not defaults */
842             config_app_settings_copy_non_defaults(app, settings);
843         }
844     }
845
846     if (settings->shade != -1)
847         self->shaded = !!settings->shade;
848     if (settings->decor != -1)
849         self->undecorated = !settings->decor;
850     if (settings->iconic != -1)
851         self->iconic = !!settings->iconic;
852     if (settings->skip_pager != -1)
853         self->skip_pager = !!settings->skip_pager;
854     if (settings->skip_taskbar != -1)
855         self->skip_taskbar = !!settings->skip_taskbar;
856
857     if (settings->max_vert != -1)
858         self->max_vert = !!settings->max_vert;
859     if (settings->max_horz != -1)
860         self->max_horz = !!settings->max_horz;
861
862     if (settings->fullscreen != -1)
863         self->fullscreen = !!settings->fullscreen;
864
865     if (settings->desktop) {
866         if (settings->desktop == DESKTOP_ALL)
867             self->desktop = settings->desktop;
868         else if (settings->desktop > 0 &&
869                  settings->desktop <= screen_num_desktops)
870             self->desktop = settings->desktop - 1;
871     }
872
873     if (settings->layer == -1) {
874         self->below = TRUE;
875         self->above = FALSE;
876     }
877     else if (settings->layer == 0) {
878         self->below = FALSE;
879         self->above = FALSE;
880     }
881     else if (settings->layer == 1) {
882         self->below = FALSE;
883         self->above = TRUE;
884     }
885     return settings;
886 }
887
888 static void client_restore_session_state(ObClient *self)
889 {
890     GList *it;
891
892     ob_debug_type(OB_DEBUG_SM,
893                   "Restore session for client %s", self->title);
894
895     if (!(it = session_state_find(self))) {
896         ob_debug_type(OB_DEBUG_SM,
897                       "Session data not found for client %s", self->title);
898         return;
899     }
900
901     self->session = it->data;
902
903     ob_debug_type(OB_DEBUG_SM, "Session data loaded for client %s",
904                   self->title);
905
906     RECT_SET_POINT(self->area, self->session->x, self->session->y);
907     self->positioned = USPosition;
908     self->sized = USSize;
909     if (self->session->w > 0)
910         self->area.width = self->session->w;
911     if (self->session->h > 0)
912         self->area.height = self->session->h;
913     XResizeWindow(obt_display, self->window,
914                   self->area.width, self->area.height);
915
916     self->desktop = (self->session->desktop == DESKTOP_ALL ?
917                      self->session->desktop :
918                      MIN(screen_num_desktops - 1, self->session->desktop));
919     OBT_PROP_SET32(self->window, NET_WM_DESKTOP, CARDINAL, self->desktop);
920
921     self->shaded = self->session->shaded;
922     self->iconic = self->session->iconic;
923     self->skip_pager = self->session->skip_pager;
924     self->skip_taskbar = self->session->skip_taskbar;
925     self->fullscreen = self->session->fullscreen;
926     self->above = self->session->above;
927     self->below = self->session->below;
928     self->max_horz = self->session->max_horz;
929     self->max_vert = self->session->max_vert;
930     self->undecorated = self->session->undecorated;
931 }
932
933 static gboolean client_restore_session_stacking(ObClient *self)
934 {
935     GList *it, *mypos;
936
937     if (!self->session) return FALSE;
938
939     mypos = g_list_find(session_saved_state, self->session);
940     if (!mypos) return FALSE;
941
942     /* start above me and look for the first client */
943     for (it = g_list_previous(mypos); it; it = g_list_previous(it)) {
944         GList *cit;
945
946         for (cit = client_list; cit; cit = g_list_next(cit)) {
947             ObClient *c = cit->data;
948             /* found a client that was in the session, so go below it */
949             if (c->session == it->data) {
950                 stacking_below(CLIENT_AS_WINDOW(self),
951                                CLIENT_AS_WINDOW(cit->data));
952                 return TRUE;
953             }
954         }
955     }
956     return FALSE;
957 }
958
959 void client_move_onscreen(ObClient *self, gboolean rude)
960 {
961     gint x = self->area.x;
962     gint y = self->area.y;
963     if (client_find_onscreen(self, &x, &y,
964                              self->area.width,
965                              self->area.height, rude)) {
966         client_move(self, x, y);
967     }
968 }
969
970 gboolean client_find_onscreen(ObClient *self, gint *x, gint *y, gint w, gint h,
971                               gboolean rude)
972 {
973     gint ox = *x, oy = *y;
974     gboolean rudel = rude, ruder = rude, rudet = rude, rudeb = rude;
975     gint fw, fh;
976     Rect desired;
977     guint i;
978     gboolean found_mon;
979
980     RECT_SET(desired, *x, *y, w, h);
981     frame_rect_to_frame(self->frame, &desired);
982
983     /* get where the frame would be */
984     frame_client_gravity(self->frame, x, y);
985
986     /* get the requested size of the window with decorations */
987     fw = self->frame->size.left + w + self->frame->size.right;
988     fh = self->frame->size.top + h + self->frame->size.bottom;
989
990     /* If rudeness wasn't requested, then still be rude in a given direction
991        if the client is not moving, only resizing in that direction */
992     if (!rude) {
993         Point oldtl, oldtr, oldbl, oldbr;
994         Point newtl, newtr, newbl, newbr;
995         gboolean stationary_l, stationary_r, stationary_t, stationary_b;
996
997         POINT_SET(oldtl, self->frame->area.x, self->frame->area.y);
998         POINT_SET(oldbr, self->frame->area.x + self->frame->area.width - 1,
999                   self->frame->area.y + self->frame->area.height - 1);
1000         POINT_SET(oldtr, oldbr.x, oldtl.y);
1001         POINT_SET(oldbl, oldtl.x, oldbr.y);
1002
1003         POINT_SET(newtl, *x, *y);
1004         POINT_SET(newbr, *x + fw - 1, *y + fh - 1);
1005         POINT_SET(newtr, newbr.x, newtl.y);
1006         POINT_SET(newbl, newtl.x, newbr.y);
1007
1008         /* is it moving or just resizing from some corner? */
1009         stationary_l = oldtl.x == newtl.x;
1010         stationary_r = oldtr.x == newtr.x;
1011         stationary_t = oldtl.y == newtl.y;
1012         stationary_b = oldbl.y == newbl.y;
1013
1014         /* if left edge is growing and didnt move right edge */
1015         if (stationary_r && newtl.x < oldtl.x)
1016             rudel = TRUE;
1017         /* if right edge is growing and didnt move left edge */
1018         if (stationary_l && newtr.x > oldtr.x)
1019             ruder = TRUE;
1020         /* if top edge is growing and didnt move bottom edge */
1021         if (stationary_b && newtl.y < oldtl.y)
1022             rudet = TRUE;
1023         /* if bottom edge is growing and didnt move top edge */
1024         if (stationary_t && newbl.y > oldbl.y)
1025             rudeb = TRUE;
1026     }
1027
1028     /* we iterate through every monitor that the window is at least partially
1029        on, to make sure it is obeying the rules on them all
1030
1031        if the window does not appear on any monitors, then use the first one
1032     */
1033     found_mon = FALSE;
1034     for (i = 0; i < screen_num_monitors; ++i) {
1035         Rect *a;
1036
1037         if (!screen_physical_area_monitor_contains(i, &desired)) {
1038             if (i < screen_num_monitors - 1 || found_mon)
1039                 continue;
1040
1041             /* the window is not inside any monitor! so just use the first
1042                one */
1043             a = screen_area(self->desktop, 0, NULL);
1044         } else {
1045             found_mon = TRUE;
1046             a = screen_area(self->desktop, SCREEN_AREA_ONE_MONITOR, &desired);
1047         }
1048
1049         /* This makes sure windows aren't entirely outside of the screen so you
1050            can't see them at all.
1051            It makes sure 10% of the window is on the screen at least. And don't
1052            let it move itself off the top of the screen, which would hide the
1053            titlebar on you. (The user can still do this if they want too, it's
1054            only limiting the application.
1055         */
1056         if (client_normal(self)) {
1057             if (!self->strut.right && *x + fw/10 >= a->x + a->width - 1)
1058                 *x = a->x + a->width - fw/10;
1059             if (!self->strut.bottom && *y + fh/10 >= a->y + a->height - 1)
1060                 *y = a->y + a->height - fh/10;
1061             if (!self->strut.left && *x + fw*9/10 - 1 < a->x)
1062                 *x = a->x - fw*9/10;
1063             if (!self->strut.top && *y + fh*9/10 - 1 < a->y)
1064                 *y = a->y - fh*9/10;
1065         }
1066
1067         /* This here doesn't let windows even a pixel outside the
1068            struts/screen. When called from client_manage, programs placing
1069            themselves are forced completely onscreen, while things like
1070            xterm -geometry resolution-width/2 will work fine. Trying to
1071            place it completely offscreen will be handled in the above code.
1072            Sorry for this confused comment, i am tired. */
1073         if (rudel && !self->strut.left && *x < a->x) *x = a->x;
1074         if (ruder && !self->strut.right && *x + fw > a->x + a->width)
1075             *x = a->x + MAX(0, a->width - fw);
1076
1077         if (rudet && !self->strut.top && *y < a->y) *y = a->y;
1078         if (rudeb && !self->strut.bottom && *y + fh > a->y + a->height)
1079             *y = a->y + MAX(0, a->height - fh);
1080
1081         g_slice_free(Rect, a);
1082     }
1083
1084     /* get where the client should be */
1085     frame_frame_gravity(self->frame, x, y);
1086
1087     return ox != *x || oy != *y;
1088 }
1089
1090 static void client_get_all(ObClient *self, gboolean real)
1091 {
1092     /* this is needed for the frame to set itself up */
1093     client_get_area(self);
1094
1095     /* these things can change the decor and functions of the window */
1096
1097     client_get_mwm_hints(self);
1098     /* this can change the mwmhints for special cases */
1099     client_get_type_and_transientness(self);
1100     client_get_state(self);
1101     client_update_normal_hints(self);
1102
1103     /* get the session related properties, these can change decorations
1104        from per-app settings */
1105     client_get_session_ids(self);
1106
1107     /* now we got everything that can affect the decorations */
1108     if (!real)
1109         return;
1110
1111     /* get this early so we have it for debugging */
1112     client_update_title(self);
1113
1114     /* save the values of the variables used for app rule matching */
1115     client_save_app_rule_values(self);
1116
1117     client_update_protocols(self);
1118
1119     client_update_wmhints(self);
1120     /* this may have already been called from client_update_wmhints */
1121     if (!self->parents && !self->transient_for_group)
1122         client_update_transient_for(self);
1123
1124     client_get_startup_id(self);
1125     client_get_desktop(self);/* uses transient data/group/startup id if a
1126                                 desktop is not specified */
1127     client_get_shaped(self);
1128
1129     {
1130         /* a couple type-based defaults for new windows */
1131
1132         /* this makes sure that these windows appear on all desktops */
1133         if (self->type == OB_CLIENT_TYPE_DESKTOP)
1134             self->desktop = DESKTOP_ALL;
1135     }
1136
1137 #ifdef SYNC
1138     client_update_sync_request_counter(self);
1139 #endif
1140
1141     client_get_colormap(self);
1142     client_update_strut(self);
1143     client_update_icons(self);
1144     client_update_icon_geometry(self);
1145 }
1146
1147 static void client_get_startup_id(ObClient *self)
1148 {
1149     if (!(OBT_PROP_GETS(self->window, NET_STARTUP_ID, utf8,
1150                         &self->startup_id)))
1151         if (self->group)
1152             OBT_PROP_GETS(self->group->leader,
1153                           NET_STARTUP_ID, utf8, &self->startup_id);
1154 }
1155
1156 static void client_get_area(ObClient *self)
1157 {
1158     XWindowAttributes wattrib;
1159     Status ret;
1160
1161     ret = XGetWindowAttributes(obt_display, self->window, &wattrib);
1162     g_assert(ret != BadWindow);
1163
1164     RECT_SET(self->area, wattrib.x, wattrib.y, wattrib.width, wattrib.height);
1165     POINT_SET(self->root_pos, wattrib.x, wattrib.y);
1166     self->border_width = wattrib.border_width;
1167
1168     ob_debug("client area: %d %d  %d %d  bw %d", wattrib.x, wattrib.y,
1169              wattrib.width, wattrib.height, wattrib.border_width);
1170 }
1171
1172 static void client_get_desktop(ObClient *self)
1173 {
1174     guint32 d = screen_num_desktops; /* an always-invalid value */
1175
1176     if (OBT_PROP_GET32(self->window, NET_WM_DESKTOP, CARDINAL, &d)) {
1177         if (d >= screen_num_desktops && d != DESKTOP_ALL)
1178             self->desktop = screen_num_desktops - 1;
1179         else
1180             self->desktop = d;
1181         ob_debug("client requested desktop 0x%x", self->desktop);
1182     } else {
1183         GSList *it;
1184         gboolean first = TRUE;
1185         guint all = screen_num_desktops; /* not a valid value */
1186
1187         /* if they are all on one desktop, then open it on the
1188            same desktop */
1189         for (it = self->parents; it; it = g_slist_next(it)) {
1190             ObClient *c = it->data;
1191
1192             if (c->desktop == DESKTOP_ALL) continue;
1193
1194             if (first) {
1195                 all = c->desktop;
1196                 first = FALSE;
1197             }
1198             else if (all != c->desktop)
1199                 all = screen_num_desktops; /* make it invalid */
1200         }
1201         if (all != screen_num_desktops) {
1202             self->desktop = all;
1203
1204             ob_debug("client desktop set from parents: 0x%x",
1205                      self->desktop);
1206         }
1207         /* try get from the startup-notification protocol */
1208         else if (sn_get_desktop(self->startup_id, &self->desktop)) {
1209             if (self->desktop >= screen_num_desktops &&
1210                 self->desktop != DESKTOP_ALL)
1211                 self->desktop = screen_num_desktops - 1;
1212             ob_debug("client desktop set from startup-notification: 0x%x",
1213                      self->desktop);
1214         }
1215         /* defaults to the current desktop */
1216         else {
1217             self->desktop = screen_desktop;
1218             ob_debug("client desktop set to the current desktop: %d",
1219                      self->desktop);
1220         }
1221     }
1222 }
1223
1224 static void client_get_state(ObClient *self)
1225 {
1226     guint32 *state;
1227     guint num;
1228
1229     if (OBT_PROP_GETA32(self->window, NET_WM_STATE, ATOM, &state, &num)) {
1230         gulong i;
1231         for (i = 0; i < num; ++i) {
1232             if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_MODAL))
1233                 self->modal = TRUE;
1234             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_SHADED))
1235                 self->shaded = TRUE;
1236             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_HIDDEN))
1237                 self->iconic = TRUE;
1238             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_SKIP_TASKBAR))
1239                 self->skip_taskbar = TRUE;
1240             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_SKIP_PAGER))
1241                 self->skip_pager = TRUE;
1242             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_FULLSCREEN))
1243                 self->fullscreen = TRUE;
1244             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_MAXIMIZED_VERT))
1245                 self->max_vert = TRUE;
1246             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_MAXIMIZED_HORZ))
1247                 self->max_horz = TRUE;
1248             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_ABOVE))
1249                 self->above = TRUE;
1250             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_BELOW))
1251                 self->below = TRUE;
1252             else if (state[i] == OBT_PROP_ATOM(NET_WM_STATE_DEMANDS_ATTENTION))
1253                 self->demands_attention = TRUE;
1254             else if (state[i] == OBT_PROP_ATOM(OB_WM_STATE_UNDECORATED))
1255                 self->undecorated = TRUE;
1256         }
1257
1258         g_free(state);
1259     }
1260 }
1261
1262 static void client_get_shaped(ObClient *self)
1263 {
1264     self->shaped = FALSE;
1265 #ifdef SHAPE
1266     if (obt_display_extension_shape) {
1267         gint foo;
1268         guint ufoo;
1269         gint s;
1270
1271         XShapeSelectInput(obt_display, self->window, ShapeNotifyMask);
1272
1273         XShapeQueryExtents(obt_display, self->window, &s, &foo,
1274                            &foo, &ufoo, &ufoo, &foo, &foo, &foo, &ufoo,
1275                            &ufoo);
1276         self->shaped = !!s;
1277     }
1278 #endif
1279 }
1280
1281 void client_update_transient_for(ObClient *self)
1282 {
1283     Window t = None;
1284     ObClient *target = NULL;
1285     gboolean trangroup = FALSE;
1286
1287     if (XGetTransientForHint(obt_display, self->window, &t)) {
1288         if (t != self->window) { /* can't be transient to itself! */
1289             ObWindow *tw = window_find(t);
1290             /* if this happens then we need to check for it */
1291             g_assert(tw != CLIENT_AS_WINDOW(self));
1292             if (tw && WINDOW_IS_CLIENT(tw)) {
1293                 /* watch out for windows with a parent that is something
1294                    different, like a dockapp for example */
1295                 target = WINDOW_AS_CLIENT(tw);
1296             }
1297         }
1298
1299         /* Setting the transient_for to Root is actually illegal, however
1300            applications from time have done this to specify transient for
1301            their group */
1302         if (!target && self->group && t == obt_root(ob_screen))
1303             trangroup = TRUE;
1304     } else if (self->group && self->transient)
1305         trangroup = TRUE;
1306
1307     client_update_transient_tree(self, self->group, self->group,
1308                                  self->transient_for_group, trangroup,
1309                                  client_direct_parent(self), target);
1310     self->transient_for_group = trangroup;
1311
1312 }
1313
1314 static void client_update_transient_tree(ObClient *self,
1315                                          ObGroup *oldgroup, ObGroup *newgroup,
1316                                          gboolean oldgtran, gboolean newgtran,
1317                                          ObClient* oldparent,
1318                                          ObClient *newparent)
1319 {
1320     GSList *it, *next;
1321     ObClient *c;
1322
1323     g_assert(!oldgtran || oldgroup);
1324     g_assert(!newgtran || newgroup);
1325     g_assert((!oldgtran && !oldparent) ||
1326              (oldgtran && !oldparent) ||
1327              (!oldgtran && oldparent));
1328     g_assert((!newgtran && !newparent) ||
1329              (newgtran && !newparent) ||
1330              (!newgtran && newparent));
1331
1332     /* * *
1333       Group transient windows are not allowed to have other group
1334       transient windows as their children.
1335       * * */
1336
1337     /* No change has occured */
1338     if (oldgroup == newgroup &&
1339         oldgtran == newgtran &&
1340         oldparent == newparent) return;
1341
1342     /** Remove the client from the transient tree **/
1343
1344     for (it = self->transients; it; it = next) {
1345         next = g_slist_next(it);
1346         c = it->data;
1347         self->transients = g_slist_delete_link(self->transients, it);
1348         c->parents = g_slist_remove(c->parents, self);
1349     }
1350     for (it = self->parents; it; it = next) {
1351         next = g_slist_next(it);
1352         c = it->data;
1353         self->parents = g_slist_delete_link(self->parents, it);
1354         c->transients = g_slist_remove(c->transients, self);
1355     }
1356
1357     /** Re-add the client to the transient tree **/
1358
1359     /* If we're transient for a group then we need to add ourselves to all our
1360        parents */
1361     if (newgtran) {
1362         for (it = newgroup->members; it; it = g_slist_next(it)) {
1363             c = it->data;
1364             if (c != self &&
1365                 !client_search_top_direct_parent(c)->transient_for_group &&
1366                 client_normal(c))
1367             {
1368                 c->transients = g_slist_prepend(c->transients, self);
1369                 self->parents = g_slist_prepend(self->parents, c);
1370             }
1371         }
1372     }
1373
1374     /* If we are now transient for a single window we need to add ourselves to
1375        its children
1376
1377        WARNING: Cyclical transient-ness is possible if two windows are
1378        transient for eachother.
1379     */
1380     else if (newparent &&
1381              /* don't make ourself its child if it is already our child */
1382              !client_is_direct_child(self, newparent) &&
1383              client_normal(newparent))
1384     {
1385         newparent->transients = g_slist_prepend(newparent->transients, self);
1386         self->parents = g_slist_prepend(self->parents, newparent);
1387     }
1388
1389     /* Add any group transient windows to our children. But if we're transient
1390        for the group, then other group transients are not our children.
1391
1392        WARNING: Cyclical transient-ness is possible. For e.g. if:
1393        A is transient for the group
1394        B is transient for A
1395        C is transient for B
1396        A can't be transient for C or we have a cycle
1397     */
1398     if (!newgtran && newgroup &&
1399         (!newparent ||
1400          !client_search_top_direct_parent(newparent)->transient_for_group) &&
1401         client_normal(self))
1402     {
1403         for (it = newgroup->members; it; it = g_slist_next(it)) {
1404             c = it->data;
1405             if (c != self && c->transient_for_group &&
1406                 /* Don't make it our child if it is already our parent */
1407                 !client_is_direct_child(c, self))
1408             {
1409                 self->transients = g_slist_prepend(self->transients, c);
1410                 c->parents = g_slist_prepend(c->parents, self);
1411             }
1412         }
1413     }
1414
1415     /** If we change our group transient-ness, our children change their
1416         effective group transient-ness, which affects how they relate to other
1417         group windows **/
1418
1419     for (it = self->transients; it; it = g_slist_next(it)) {
1420         c = it->data;
1421         if (!c->transient_for_group)
1422             client_update_transient_tree(c, c->group, c->group,
1423                                          c->transient_for_group,
1424                                          c->transient_for_group,
1425                                          client_direct_parent(c),
1426                                          client_direct_parent(c));
1427     }
1428 }
1429
1430 void client_get_mwm_hints(ObClient *self)
1431 {
1432     guint num;
1433     guint32 *hints;
1434
1435     self->mwmhints.flags = 0; /* default to none */
1436
1437     if (OBT_PROP_GETA32(self->window, MOTIF_WM_HINTS, MOTIF_WM_HINTS,
1438                         &hints, &num)) {
1439         if (num >= OB_MWM_ELEMENTS) {
1440             self->mwmhints.flags = hints[0];
1441             self->mwmhints.functions = hints[1];
1442             self->mwmhints.decorations = hints[2];
1443         }
1444         g_free(hints);
1445     }
1446 }
1447
1448 void client_get_type_and_transientness(ObClient *self)
1449 {
1450     guint num, i;
1451     guint32 *val;
1452     Window t;
1453
1454     self->type = -1;
1455     self->transient = FALSE;
1456
1457     if (OBT_PROP_GETA32(self->window, NET_WM_WINDOW_TYPE, ATOM, &val, &num)) {
1458         /* use the first value that we know about in the array */
1459         for (i = 0; i < num; ++i) {
1460             if (val[i] == OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_DESKTOP))
1461                 self->type = OB_CLIENT_TYPE_DESKTOP;
1462             else if (val[i] == OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_DOCK))
1463                 self->type = OB_CLIENT_TYPE_DOCK;
1464             else if (val[i] == OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_TOOLBAR))
1465                 self->type = OB_CLIENT_TYPE_TOOLBAR;
1466             else if (val[i] == OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_MENU))
1467                 self->type = OB_CLIENT_TYPE_MENU;
1468             else if (val[i] == OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_UTILITY))
1469                 self->type = OB_CLIENT_TYPE_UTILITY;
1470             else if (val[i] == OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_SPLASH))
1471                 self->type = OB_CLIENT_TYPE_SPLASH;
1472             else if (val[i] == OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_DIALOG))
1473                 self->type = OB_CLIENT_TYPE_DIALOG;
1474             else if (val[i] == OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_NORMAL))
1475                 self->type = OB_CLIENT_TYPE_NORMAL;
1476             else if (val[i] == OBT_PROP_ATOM(KDE_NET_WM_WINDOW_TYPE_OVERRIDE))
1477             {
1478                 /* prevent this window from getting any decor or
1479                    functionality */
1480                 self->mwmhints.flags &= (OB_MWM_FLAG_FUNCTIONS |
1481                                          OB_MWM_FLAG_DECORATIONS);
1482                 self->mwmhints.decorations = 0;
1483                 self->mwmhints.functions = 0;
1484             }
1485             if (self->type != (ObClientType) -1)
1486                 break; /* grab the first legit type */
1487         }
1488         g_free(val);
1489     }
1490
1491     if (XGetTransientForHint(obt_display, self->window, &t))
1492         self->transient = TRUE;
1493
1494     if (self->type == (ObClientType) -1) {
1495         /*the window type hint was not set, which means we either classify
1496           ourself as a normal window or a dialog, depending on if we are a
1497           transient. */
1498         if (self->transient)
1499             self->type = OB_CLIENT_TYPE_DIALOG;
1500         else
1501             self->type = OB_CLIENT_TYPE_NORMAL;
1502     }
1503
1504     /* then, based on our type, we can update our transientness.. */
1505     if (self->type == OB_CLIENT_TYPE_DIALOG ||
1506         self->type == OB_CLIENT_TYPE_TOOLBAR ||
1507         self->type == OB_CLIENT_TYPE_MENU ||
1508         self->type == OB_CLIENT_TYPE_UTILITY)
1509     {
1510         self->transient = TRUE;
1511     }
1512 }
1513
1514 void client_update_protocols(ObClient *self)
1515 {
1516     guint32 *proto;
1517     guint num_ret, i;
1518
1519     self->focus_notify = FALSE;
1520     self->delete_window = FALSE;
1521
1522     if (OBT_PROP_GETA32(self->window, WM_PROTOCOLS, ATOM, &proto, &num_ret)) {
1523         for (i = 0; i < num_ret; ++i) {
1524             if (proto[i] == OBT_PROP_ATOM(WM_DELETE_WINDOW))
1525                 /* this means we can request the window to close */
1526                 self->delete_window = TRUE;
1527             else if (proto[i] == OBT_PROP_ATOM(WM_TAKE_FOCUS))
1528                 /* if this protocol is requested, then the window will be
1529                    notified whenever we want it to receive focus */
1530                 self->focus_notify = TRUE;
1531             else if (proto[i] == OBT_PROP_ATOM(NET_WM_PING))
1532                 /* if this protocol is requested, then the window will allow
1533                    pings to determine if it is still alive */
1534                 self->ping = TRUE;
1535 #ifdef SYNC
1536             else if (proto[i] == OBT_PROP_ATOM(NET_WM_SYNC_REQUEST))
1537                 /* if this protocol is requested, then resizing the
1538                    window will be synchronized between the frame and the
1539                    client */
1540                 self->sync_request = TRUE;
1541 #endif
1542         }
1543         g_free(proto);
1544     }
1545 }
1546
1547 #ifdef SYNC
1548 void client_update_sync_request_counter(ObClient *self)
1549 {
1550     guint32 i;
1551
1552     if (OBT_PROP_GET32(self->window, NET_WM_SYNC_REQUEST_COUNTER, CARDINAL,&i))
1553     {
1554         XSyncValue val;
1555
1556         self->sync_counter = i;
1557
1558         /* this must be set when managing a new window according to EWMH */
1559         XSyncIntToValue(&val, 0);
1560         XSyncSetCounter(obt_display, self->sync_counter, val);
1561     } else
1562         self->sync_counter = None;
1563 }
1564 #endif
1565
1566 static void client_get_colormap(ObClient *self)
1567 {
1568     XWindowAttributes wa;
1569
1570     if (XGetWindowAttributes(obt_display, self->window, &wa))
1571         client_update_colormap(self, wa.colormap);
1572 }
1573
1574 void client_update_colormap(ObClient *self, Colormap colormap)
1575 {
1576     if (colormap == self->colormap) return;
1577
1578     ob_debug("Setting client %s colormap: 0x%x", self->title, colormap);
1579
1580     if (client_focused(self)) {
1581         screen_install_colormap(self, FALSE); /* uninstall old one */
1582         self->colormap = colormap;
1583         screen_install_colormap(self, TRUE); /* install new one */
1584     } else
1585         self->colormap = colormap;
1586 }
1587
1588 void client_update_normal_hints(ObClient *self)
1589 {
1590     XSizeHints size;
1591     glong ret;
1592
1593     /* defaults */
1594     self->min_ratio = 0.0f;
1595     self->max_ratio = 0.0f;
1596     SIZE_SET(self->size_inc, 1, 1);
1597     SIZE_SET(self->base_size, -1, -1);
1598     SIZE_SET(self->min_size, 0, 0);
1599     SIZE_SET(self->max_size, G_MAXINT, G_MAXINT);
1600
1601     /* get the hints from the window */
1602     if (XGetWMNormalHints(obt_display, self->window, &size, &ret)) {
1603         /* normal windows can't request placement! har har
1604         if (!client_normal(self))
1605         */
1606         self->positioned = (size.flags & (PPosition|USPosition));
1607         self->sized = (size.flags & (PSize|USSize));
1608
1609         if (size.flags & PWinGravity)
1610             self->gravity = size.win_gravity;
1611
1612         if (size.flags & PAspect) {
1613             if (size.min_aspect.y)
1614                 self->min_ratio =
1615                     (gfloat) size.min_aspect.x / size.min_aspect.y;
1616             if (size.max_aspect.y)
1617                 self->max_ratio =
1618                     (gfloat) size.max_aspect.x / size.max_aspect.y;
1619         }
1620
1621         if (size.flags & PMinSize)
1622             SIZE_SET(self->min_size, size.min_width, size.min_height);
1623
1624         if (size.flags & PMaxSize)
1625             SIZE_SET(self->max_size, size.max_width, size.max_height);
1626
1627         if (size.flags & PBaseSize)
1628             SIZE_SET(self->base_size, size.base_width, size.base_height);
1629
1630         if (size.flags & PResizeInc && size.width_inc && size.height_inc)
1631             SIZE_SET(self->size_inc, size.width_inc, size.height_inc);
1632
1633         ob_debug("Normal hints: min size (%d %d) max size (%d %d)",
1634                  self->min_size.width, self->min_size.height,
1635                  self->max_size.width, self->max_size.height);
1636         ob_debug("size inc (%d %d) base size (%d %d)",
1637                  self->size_inc.width, self->size_inc.height,
1638                  self->base_size.width, self->base_size.height);
1639     }
1640     else
1641         ob_debug("Normal hints: not set");
1642 }
1643
1644 void client_setup_decor_and_functions(ObClient *self, gboolean reconfig)
1645 {
1646     /* start with everything (cept fullscreen) */
1647     self->decorations =
1648         (OB_FRAME_DECOR_TITLEBAR |
1649          OB_FRAME_DECOR_HANDLE |
1650          OB_FRAME_DECOR_GRIPS |
1651          OB_FRAME_DECOR_BORDER |
1652          OB_FRAME_DECOR_ICON |
1653          OB_FRAME_DECOR_ALLDESKTOPS |
1654          OB_FRAME_DECOR_ICONIFY |
1655          OB_FRAME_DECOR_MAXIMIZE |
1656          OB_FRAME_DECOR_SHADE |
1657          OB_FRAME_DECOR_CLOSE);
1658     self->functions =
1659         (OB_CLIENT_FUNC_RESIZE |
1660          OB_CLIENT_FUNC_MOVE |
1661          OB_CLIENT_FUNC_ICONIFY |
1662          OB_CLIENT_FUNC_MAXIMIZE |
1663          OB_CLIENT_FUNC_SHADE |
1664          OB_CLIENT_FUNC_CLOSE |
1665          OB_CLIENT_FUNC_BELOW |
1666          OB_CLIENT_FUNC_ABOVE |
1667          OB_CLIENT_FUNC_UNDECORATE);
1668
1669     if (!(self->min_size.width < self->max_size.width ||
1670           self->min_size.height < self->max_size.height))
1671         self->functions &= ~OB_CLIENT_FUNC_RESIZE;
1672
1673     switch (self->type) {
1674     case OB_CLIENT_TYPE_NORMAL:
1675         /* normal windows retain all of the possible decorations and
1676            functionality, and can be fullscreen */
1677         self->functions |= OB_CLIENT_FUNC_FULLSCREEN;
1678         break;
1679
1680     case OB_CLIENT_TYPE_DIALOG:
1681         /* sometimes apps make dialog windows fullscreen for some reason (for
1682            e.g. kpdf does this..) */
1683         self->functions |= OB_CLIENT_FUNC_FULLSCREEN;
1684         break;
1685
1686     case OB_CLIENT_TYPE_UTILITY:
1687         /* these windows don't have anything added or removed by default */
1688         break;
1689
1690     case OB_CLIENT_TYPE_MENU:
1691     case OB_CLIENT_TYPE_TOOLBAR:
1692         /* these windows can't iconify or maximize */
1693         self->decorations &= ~(OB_FRAME_DECOR_ICONIFY |
1694                                OB_FRAME_DECOR_MAXIMIZE);
1695         self->functions &= ~(OB_CLIENT_FUNC_ICONIFY |
1696                              OB_CLIENT_FUNC_MAXIMIZE);
1697         break;
1698
1699     case OB_CLIENT_TYPE_SPLASH:
1700         /* these don't get get any decorations, and the only thing you can
1701            do with them is move them */
1702         self->decorations = 0;
1703         self->functions = OB_CLIENT_FUNC_MOVE;
1704         break;
1705
1706     case OB_CLIENT_TYPE_DESKTOP:
1707         /* these windows are not manipulated by the window manager */
1708         self->decorations = 0;
1709         self->functions = 0;
1710         break;
1711
1712     case OB_CLIENT_TYPE_DOCK:
1713         /* these windows are not manipulated by the window manager, but they
1714            can set below layer which has a special meaning */
1715         self->decorations = 0;
1716         self->functions = OB_CLIENT_FUNC_BELOW;
1717         break;
1718     }
1719
1720     /* Mwm Hints are applied subtractively to what has already been chosen for
1721        decor and functionality */
1722     if (self->mwmhints.flags & OB_MWM_FLAG_DECORATIONS) {
1723         if (! (self->mwmhints.decorations & OB_MWM_DECOR_ALL)) {
1724             if (! ((self->mwmhints.decorations & OB_MWM_DECOR_HANDLE) ||
1725                    (self->mwmhints.decorations & OB_MWM_DECOR_TITLE)))
1726             {
1727                 /* if the mwm hints request no handle or title, then all
1728                    decorations are disabled, but keep the border if that's
1729                    specified */
1730                 if (self->mwmhints.decorations & OB_MWM_DECOR_BORDER)
1731                     self->decorations = OB_FRAME_DECOR_BORDER;
1732                 else
1733                     self->decorations = 0;
1734             }
1735         }
1736     }
1737
1738     if (self->mwmhints.flags & OB_MWM_FLAG_FUNCTIONS) {
1739         if (! (self->mwmhints.functions & OB_MWM_FUNC_ALL)) {
1740             if (! (self->mwmhints.functions & OB_MWM_FUNC_RESIZE))
1741                 self->functions &= ~OB_CLIENT_FUNC_RESIZE;
1742             if (! (self->mwmhints.functions & OB_MWM_FUNC_MOVE))
1743                 self->functions &= ~OB_CLIENT_FUNC_MOVE;
1744             /* dont let mwm hints kill any buttons
1745                if (! (self->mwmhints.functions & OB_MWM_FUNC_ICONIFY))
1746                self->functions &= ~OB_CLIENT_FUNC_ICONIFY;
1747                if (! (self->mwmhints.functions & OB_MWM_FUNC_MAXIMIZE))
1748                self->functions &= ~OB_CLIENT_FUNC_MAXIMIZE;
1749             */
1750             /* dont let mwm hints kill the close button
1751                if (! (self->mwmhints.functions & MwmFunc_Close))
1752                self->functions &= ~OB_CLIENT_FUNC_CLOSE; */
1753         }
1754     }
1755
1756     if (!(self->functions & OB_CLIENT_FUNC_SHADE))
1757         self->decorations &= ~OB_FRAME_DECOR_SHADE;
1758     if (!(self->functions & OB_CLIENT_FUNC_ICONIFY))
1759         self->decorations &= ~OB_FRAME_DECOR_ICONIFY;
1760     if (!(self->functions & OB_CLIENT_FUNC_RESIZE))
1761         self->decorations &= ~(OB_FRAME_DECOR_GRIPS | OB_FRAME_DECOR_HANDLE);
1762
1763     /* can't maximize without moving/resizing */
1764     if (!((self->functions & OB_CLIENT_FUNC_MAXIMIZE) &&
1765           (self->functions & OB_CLIENT_FUNC_MOVE) &&
1766           (self->functions & OB_CLIENT_FUNC_RESIZE))) {
1767         self->functions &= ~OB_CLIENT_FUNC_MAXIMIZE;
1768         self->decorations &= ~OB_FRAME_DECOR_MAXIMIZE;
1769     }
1770
1771     if (self->max_horz && self->max_vert) {
1772         /* you can't resize fully maximized windows */
1773         self->functions &= ~OB_CLIENT_FUNC_RESIZE;
1774         /* kill the handle on fully maxed windows */
1775         self->decorations &= ~(OB_FRAME_DECOR_HANDLE | OB_FRAME_DECOR_GRIPS);
1776     }
1777
1778     /* If there are no decorations to remove, don't allow the user to try
1779        toggle the state */
1780     if (self->decorations == 0)
1781         self->functions &= ~OB_CLIENT_FUNC_UNDECORATE;
1782
1783     /* finally, the user can have requested no decorations, which overrides
1784        everything (but doesnt give it a border if it doesnt have one) */
1785     if (self->undecorated)
1786         self->decorations &= (config_theme_keepborder ?
1787                               OB_FRAME_DECOR_BORDER : 0);
1788
1789     /* if we don't have a titlebar, then we cannot shade! */
1790     if (!(self->decorations & OB_FRAME_DECOR_TITLEBAR))
1791         self->functions &= ~OB_CLIENT_FUNC_SHADE;
1792
1793     /* now we need to check against rules for the client's current state */
1794     if (self->fullscreen) {
1795         self->functions &= (OB_CLIENT_FUNC_CLOSE |
1796                             OB_CLIENT_FUNC_FULLSCREEN |
1797                             OB_CLIENT_FUNC_ICONIFY);
1798         self->decorations = 0;
1799     }
1800
1801     client_change_allowed_actions(self);
1802
1803     if (reconfig)
1804         /* force reconfigure to make sure decorations are updated */
1805         client_reconfigure(self, TRUE);
1806 }
1807
1808 static void client_change_allowed_actions(ObClient *self)
1809 {
1810     gulong actions[12];
1811     gint num = 0;
1812
1813     /* desktop windows are kept on all desktops */
1814     if (self->type != OB_CLIENT_TYPE_DESKTOP)
1815         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_CHANGE_DESKTOP);
1816
1817     if (self->functions & OB_CLIENT_FUNC_SHADE)
1818         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_SHADE);
1819     if (self->functions & OB_CLIENT_FUNC_CLOSE)
1820         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_CLOSE);
1821     if (self->functions & OB_CLIENT_FUNC_MOVE)
1822         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_MOVE);
1823     if (self->functions & OB_CLIENT_FUNC_ICONIFY)
1824         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_MINIMIZE);
1825     if (self->functions & OB_CLIENT_FUNC_RESIZE)
1826         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_RESIZE);
1827     if (self->functions & OB_CLIENT_FUNC_FULLSCREEN)
1828         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_FULLSCREEN);
1829     if (self->functions & OB_CLIENT_FUNC_MAXIMIZE) {
1830         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_MAXIMIZE_HORZ);
1831         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_MAXIMIZE_VERT);
1832     }
1833     if (self->functions & OB_CLIENT_FUNC_ABOVE)
1834         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_ABOVE);
1835     if (self->functions & OB_CLIENT_FUNC_BELOW)
1836         actions[num++] = OBT_PROP_ATOM(NET_WM_ACTION_BELOW);
1837     if (self->functions & OB_CLIENT_FUNC_UNDECORATE)
1838         actions[num++] = OBT_PROP_ATOM(OB_WM_ACTION_UNDECORATE);
1839
1840     OBT_PROP_SETA32(self->window, NET_WM_ALLOWED_ACTIONS, ATOM, actions, num);
1841
1842     /* make sure the window isn't breaking any rules now
1843
1844        don't check ICONIFY here.  just cuz a window can't iconify doesnt mean
1845        it can't be iconified with its parent
1846     */
1847
1848     if (!(self->functions & OB_CLIENT_FUNC_SHADE) && self->shaded) {
1849         if (self->frame) client_shade(self, FALSE);
1850         else self->shaded = FALSE;
1851     }
1852     if (!(self->functions & OB_CLIENT_FUNC_FULLSCREEN) && self->fullscreen) {
1853         if (self->frame) client_fullscreen(self, FALSE);
1854         else self->fullscreen = FALSE;
1855     }
1856     if (!(self->functions & OB_CLIENT_FUNC_MAXIMIZE) && (self->max_horz ||
1857                                                          self->max_vert)) {
1858         if (self->frame) client_maximize(self, FALSE, 0);
1859         else self->max_vert = self->max_horz = FALSE;
1860     }
1861 }
1862
1863 void client_update_wmhints(ObClient *self)
1864 {
1865     XWMHints *hints;
1866
1867     /* assume a window takes input if it doesn't specify */
1868     self->can_focus = TRUE;
1869
1870     if ((hints = XGetWMHints(obt_display, self->window)) != NULL) {
1871         gboolean ur;
1872
1873         if (hints->flags & InputHint)
1874             self->can_focus = hints->input;
1875
1876         /* only do this when first managing the window *AND* when we aren't
1877            starting up! */
1878         if (ob_state() != OB_STATE_STARTING && self->frame == NULL)
1879             if (hints->flags & StateHint)
1880                 self->iconic = hints->initial_state == IconicState;
1881
1882         ur = self->urgent;
1883         self->urgent = (hints->flags & XUrgencyHint);
1884         if (self->urgent && !ur)
1885             client_hilite(self, TRUE);
1886         else if (!self->urgent && ur && self->demands_attention)
1887             client_hilite(self, FALSE);
1888
1889         if (!(hints->flags & WindowGroupHint))
1890             hints->window_group = None;
1891
1892         /* did the group state change? */
1893         if (hints->window_group !=
1894             (self->group ? self->group->leader : None))
1895         {
1896             ObGroup *oldgroup = self->group;
1897
1898             /* remove from the old group if there was one */
1899             if (self->group) {
1900                 group_remove(self->group, self);
1901                 self->group = NULL;
1902             }
1903
1904             /* add ourself to the group if we have one */
1905             if (hints->window_group != None) {
1906                 self->group = group_add(hints->window_group, self);
1907             }
1908
1909             /* Put ourselves into the new group's transient tree, and remove
1910                ourselves from the old group's */
1911             client_update_transient_tree(self, oldgroup, self->group,
1912                                          self->transient_for_group,
1913                                          self->transient_for_group,
1914                                          client_direct_parent(self),
1915                                          client_direct_parent(self));
1916
1917             /* Lastly, being in a group, or not, can change if the window is
1918                transient for anything.
1919
1920                The logic for this is:
1921                self->transient = TRUE always if the window wants to be
1922                transient for something, even if transient_for was NULL because
1923                it wasn't in a group before.
1924
1925                If parents was NULL and oldgroup was NULL we can assume
1926                that when we add the new group, it will become transient for
1927                something.
1928
1929                If transient_for_group is TRUE, then it must have already
1930                had a group. If it is getting a new group, the above call to
1931                client_update_transient_tree has already taken care of
1932                everything ! If it is losing all group status then it will
1933                no longer be transient for anything and that needs to be
1934                updated.
1935             */
1936             if (self->transient &&
1937                 ((self->parents == NULL && oldgroup == NULL) ||
1938                  (self->transient_for_group && !self->group)))
1939                 client_update_transient_for(self);
1940         }
1941
1942         /* the WM_HINTS can contain an icon */
1943         if (hints->flags & IconPixmapHint)
1944             client_update_icons(self);
1945
1946         XFree(hints);
1947     }
1948
1949     focus_cycle_addremove(self, TRUE);
1950 }
1951
1952 void client_update_title(ObClient *self)
1953 {
1954     gchar *data = NULL;
1955     gchar *visible = NULL;
1956
1957     g_free(self->title);
1958     g_free(self->original_title);
1959
1960     /* try netwm */
1961     if (!OBT_PROP_GETS(self->window, NET_WM_NAME, utf8, &data)) {
1962         /* try old x stuff */
1963         if (!(OBT_PROP_GETS(self->window, WM_NAME, locale, &data)
1964               || OBT_PROP_GETS(self->window, WM_NAME, utf8, &data))) {
1965             if (self->transient) {
1966     /*
1967     GNOME alert windows are not given titles:
1968     http://developer.gnome.org/projects/gup/hig/draft_hig_new/windows-alert.html
1969     */
1970                 data = g_strdup("");
1971             } else
1972                 data = g_strdup(_("Unnamed Window"));
1973         }
1974     }
1975     self->original_title = g_strdup(data);
1976
1977     if (self->client_machine) {
1978         visible = g_strdup_printf("%s (%s)", data, self->client_machine);
1979         g_free(data);
1980     } else
1981         visible = data;
1982
1983     if (self->not_responding) {
1984         data = visible;
1985         if (self->kill_level > 0)
1986             visible = g_strdup_printf("%s - [%s]", data, _("Killing..."));
1987         else
1988             visible = g_strdup_printf("%s - [%s]", data, _("Not Responding"));
1989         g_free(data);
1990     }
1991
1992     OBT_PROP_SETS(self->window, NET_WM_VISIBLE_NAME, utf8, visible);
1993     self->title = visible;
1994
1995     if (self->frame)
1996         frame_adjust_title(self->frame);
1997
1998     /* update the icon title */
1999     data = NULL;
2000     g_free(self->icon_title);
2001
2002     /* try netwm */
2003     if (!OBT_PROP_GETS(self->window, NET_WM_ICON_NAME, utf8, &data))
2004         /* try old x stuff */
2005         if (!(OBT_PROP_GETS(self->window, WM_ICON_NAME, locale, &data) ||
2006               OBT_PROP_GETS(self->window, WM_ICON_NAME, utf8, &data)))
2007             data = g_strdup(self->title);
2008
2009     if (self->client_machine) {
2010         visible = g_strdup_printf("%s (%s)", data, self->client_machine);
2011         g_free(data);
2012     } else
2013         visible = data;
2014
2015     if (self->not_responding) {
2016         data = visible;
2017         if (self->kill_level > 0)
2018             visible = g_strdup_printf("%s - [%s]", data, _("Killing..."));
2019         else
2020             visible = g_strdup_printf("%s - [%s]", data, _("Not Responding"));
2021         g_free(data);
2022     }
2023
2024     OBT_PROP_SETS(self->window, NET_WM_VISIBLE_ICON_NAME, utf8, visible);
2025     self->icon_title = visible;
2026 }
2027
2028 void client_update_strut(ObClient *self)
2029 {
2030     guint num;
2031     guint32 *data;
2032     gboolean got = FALSE;
2033     StrutPartial strut;
2034
2035     if (OBT_PROP_GETA32(self->window, NET_WM_STRUT_PARTIAL, CARDINAL,
2036                         &data, &num))
2037     {
2038         if (num == 12) {
2039             got = TRUE;
2040             STRUT_PARTIAL_SET(strut,
2041                               data[0], data[2], data[1], data[3],
2042                               data[4], data[5], data[8], data[9],
2043                               data[6], data[7], data[10], data[11]);
2044         }
2045         g_free(data);
2046     }
2047
2048     if (!got &&
2049         OBT_PROP_GETA32(self->window, NET_WM_STRUT, CARDINAL, &data, &num)) {
2050         if (num == 4) {
2051             const Rect *a;
2052
2053             got = TRUE;
2054
2055             /* use the screen's width/height */
2056             a = screen_physical_area_all_monitors();
2057
2058             STRUT_PARTIAL_SET(strut,
2059                               data[0], data[2], data[1], data[3],
2060                               a->y, a->y + a->height - 1,
2061                               a->x, a->x + a->width - 1,
2062                               a->y, a->y + a->height - 1,
2063                               a->x, a->x + a->width - 1);
2064         }
2065         g_free(data);
2066     }
2067
2068     if (!got)
2069         STRUT_PARTIAL_SET(strut, 0, 0, 0, 0,
2070                           0, 0, 0, 0, 0, 0, 0, 0);
2071
2072     if (!PARTIAL_STRUT_EQUAL(strut, self->strut)) {
2073         self->strut = strut;
2074
2075         /* updating here is pointless while we're being mapped cuz we're not in
2076            the client list yet */
2077         if (self->frame)
2078             screen_update_areas();
2079     }
2080 }
2081
2082 void client_update_icons(ObClient *self)
2083 {
2084     guint num;
2085     guint32 *data;
2086     guint w, h, i, j;
2087     guint num_seen;  /* number of icons present */
2088     RrImage *img;
2089
2090     img = NULL;
2091
2092     /* grab the server, because we might be setting the window's icon and
2093        we don't want them to set it in between and we overwrite their own
2094        icon */
2095     grab_server(TRUE);
2096
2097     if (OBT_PROP_GETA32(self->window, NET_WM_ICON, CARDINAL, &data, &num)) {
2098         /* figure out how many valid icons are in here */
2099         i = 0;
2100         num_seen = 0;
2101         while (i + 2 < num) { /* +2 is to make sure there is a w and h */
2102             w = data[i++];
2103             h = data[i++];
2104             /* watch for the data being too small for the specified size,
2105                or for zero sized icons. */
2106             if (i + w*h > num || w == 0 || h == 0) break;
2107
2108             /* convert it to the right bit order for ObRender */
2109             for (j = 0; j < w*h; ++j)
2110                 data[i+j] =
2111                     (((data[i+j] >> 24) & 0xff) << RrDefaultAlphaOffset) +
2112                     (((data[i+j] >> 16) & 0xff) << RrDefaultRedOffset)   +
2113                     (((data[i+j] >>  8) & 0xff) << RrDefaultGreenOffset) +
2114                     (((data[i+j] >>  0) & 0xff) << RrDefaultBlueOffset);
2115
2116             /* is it in the cache? */
2117             img = RrImageCacheFind(ob_rr_icons, &data[i], w, h);
2118             if (img) RrImageRef(img); /* own it */
2119
2120             i += w*h;
2121             ++num_seen;
2122
2123             /* don't bother looping anymore if we already found it in the cache
2124                since we'll just use that! */
2125             if (img) break;
2126         }
2127
2128         /* if it's not in the cache yet, then add it to the cache now.
2129            we have already converted it to the correct bit order above */
2130         if (!img && num_seen > 0) {
2131             img = RrImageNew(ob_rr_icons);
2132             i = 0;
2133             for (j = 0; j < num_seen; ++j) {
2134                 w = data[i++];
2135                 h = data[i++];
2136                 RrImageAddPicture(img, &data[i], w, h);
2137                 i += w*h;
2138             }
2139         }
2140
2141         g_free(data);
2142     }
2143
2144     /* if we didn't find an image from the NET_WM_ICON stuff, then try the
2145        legacy X hints */
2146     if (!img) {
2147         XWMHints *hints;
2148
2149         if ((hints = XGetWMHints(obt_display, self->window))) {
2150             if (hints->flags & IconPixmapHint) {
2151                 gboolean xicon;
2152                 obt_display_ignore_errors(TRUE);
2153                 xicon = RrPixmapToRGBA(ob_rr_inst,
2154                                        hints->icon_pixmap,
2155                                        (hints->flags & IconMaskHint ?
2156                                         hints->icon_mask : None),
2157                                        (gint*)&w, (gint*)&h, &data);
2158                 obt_display_ignore_errors(FALSE);
2159
2160                 if (xicon) {
2161                     if (w > 0 && h > 0) {
2162                         /* is this icon in the cache yet? */
2163                         img = RrImageCacheFind(ob_rr_icons, data, w, h);
2164                         if (img) RrImageRef(img); /* own it */
2165
2166                         /* if not, then add it */
2167                         if (!img) {
2168                             img = RrImageNew(ob_rr_icons);
2169                             RrImageAddPicture(img, data, w, h);
2170                         }
2171                     }
2172
2173                     g_free(data);
2174                 }
2175             }
2176             XFree(hints);
2177         }
2178     }
2179
2180     /* set the client's icons to be whatever we found */
2181     RrImageUnref(self->icon_set);
2182     self->icon_set = img;
2183
2184     /* if the client has no icon at all, then we set a default icon onto it.
2185        but, if it has parents, then one of them will have an icon already
2186     */
2187     if (!self->icon_set && !self->parents) {
2188         RrPixel32 *icon = ob_rr_theme->def_win_icon;
2189         gulong *ldata; /* use a long here to satisfy OBT_PROP_SETA32 */
2190
2191         w = ob_rr_theme->def_win_icon_w;
2192         h = ob_rr_theme->def_win_icon_h;
2193         ldata = g_new(gulong, w*h+2);
2194         ldata[0] = w;
2195         ldata[1] = h;
2196         for (i = 0; i < w*h; ++i)
2197             ldata[i+2] = (((icon[i] >> RrDefaultAlphaOffset) & 0xff) << 24) +
2198                 (((icon[i] >> RrDefaultRedOffset) & 0xff) << 16) +
2199                 (((icon[i] >> RrDefaultGreenOffset) & 0xff) << 8) +
2200                 (((icon[i] >> RrDefaultBlueOffset) & 0xff) << 0);
2201         OBT_PROP_SETA32(self->window, NET_WM_ICON, CARDINAL, ldata, w*h+2);
2202         g_free(ldata);
2203     } else if (self->frame)
2204         /* don't draw the icon empty if we're just setting one now anyways,
2205            we'll get the property change any second */
2206         frame_adjust_icon(self->frame);
2207
2208     grab_server(FALSE);
2209 }
2210
2211 void client_update_icon_geometry(ObClient *self)
2212 {
2213     guint num;
2214     guint32 *data;
2215
2216     RECT_SET(self->icon_geometry, 0, 0, 0, 0);
2217
2218     if (OBT_PROP_GETA32(self->window, NET_WM_ICON_GEOMETRY, CARDINAL,
2219                         &data, &num))
2220     {
2221         if (num == 4)
2222             /* don't let them set it with an area < 0 */
2223             RECT_SET(self->icon_geometry, data[0], data[1],
2224                      MAX(data[2],0), MAX(data[3],0));
2225         g_free(data);
2226     }
2227 }
2228
2229 static void client_get_session_ids(ObClient *self)
2230 {
2231     guint32 leader;
2232     gboolean got;
2233     gchar *s;
2234     gchar **ss;
2235
2236     if (!OBT_PROP_GET32(self->window, WM_CLIENT_LEADER, WINDOW, &leader))
2237         leader = None;
2238
2239     /* get the SM_CLIENT_ID */
2240     got = FALSE;
2241     if (leader)
2242         got = OBT_PROP_GETS(leader, SM_CLIENT_ID, locale, &self->sm_client_id);
2243     if (!got)
2244         OBT_PROP_GETS(self->window, SM_CLIENT_ID, locale, &self->sm_client_id);
2245
2246     /* get the WM_CLASS (name and class). make them "" if they are not
2247        provided */
2248     got = FALSE;
2249     if (leader)
2250         got = OBT_PROP_GETSS(leader, WM_CLASS, locale, &ss);
2251     if (!got)
2252         got = OBT_PROP_GETSS(self->window, WM_CLASS, locale, &ss);
2253
2254     if (got) {
2255         if (ss[0]) {
2256             self->name = g_strdup(ss[0]);
2257             if (ss[1])
2258                 self->class = g_strdup(ss[1]);
2259         }
2260         g_strfreev(ss);
2261     }
2262
2263     if (self->name == NULL) self->name = g_strdup("");
2264     if (self->class == NULL) self->class = g_strdup("");
2265
2266     /* get the WM_WINDOW_ROLE. make it "" if it is not provided */
2267     got = FALSE;
2268     if (leader)
2269         got = OBT_PROP_GETS(leader, WM_WINDOW_ROLE, locale, &s);
2270     if (!got)
2271         got = OBT_PROP_GETS(self->window, WM_WINDOW_ROLE, locale, &s);
2272
2273     if (got)
2274         self->role = s;
2275     else
2276         self->role = g_strdup("");
2277
2278     /* get the WM_COMMAND */
2279     got = FALSE;
2280
2281     if (leader)
2282         got = OBT_PROP_GETSS(leader, WM_COMMAND, locale, &ss);
2283     if (!got)
2284         got = OBT_PROP_GETSS(self->window, WM_COMMAND, locale, &ss);
2285
2286     if (got) {
2287         /* merge/mash them all together */
2288         gchar *merge = NULL;
2289         gint i;
2290
2291         for (i = 0; ss[i]; ++i) {
2292             gchar *tmp = merge;
2293             if (merge)
2294                 merge = g_strconcat(merge, ss[i], NULL);
2295             else
2296                 merge = g_strconcat(ss[i], NULL);
2297             g_free(tmp);
2298         }
2299         g_strfreev(ss);
2300
2301         self->wm_command = merge;
2302     }
2303
2304     /* get the WM_CLIENT_MACHINE */
2305     got = FALSE;
2306     if (leader)
2307         got = OBT_PROP_GETS(leader, WM_CLIENT_MACHINE, locale, &s);
2308     if (!got)
2309         got = OBT_PROP_GETS(self->window, WM_CLIENT_MACHINE, locale, &s);
2310
2311     if (got) {
2312         gchar localhost[128];
2313         guint32 pid;
2314
2315         gethostname(localhost, 127);
2316         localhost[127] = '\0';
2317         if (strcmp(localhost, s) != 0)
2318             self->client_machine = s;
2319         else
2320             g_free(s);
2321
2322         /* see if it has the PID set too (the PID requires that the
2323            WM_CLIENT_MACHINE be set) */
2324         if (OBT_PROP_GET32(self->window, NET_WM_PID, CARDINAL, &pid))
2325             self->pid = pid;
2326     }
2327 }
2328
2329 /*! Save the properties used for app matching rules, as seen by Openbox when
2330   the window mapped, so that users can still access them later if the app
2331   changes them */
2332 static void client_save_app_rule_values(ObClient *self)
2333 {
2334     const gchar *type;
2335
2336     OBT_PROP_SETS(self->window, OB_APP_ROLE, utf8, self->role);
2337     OBT_PROP_SETS(self->window, OB_APP_NAME, utf8, self->name);
2338     OBT_PROP_SETS(self->window, OB_APP_CLASS, utf8, self->class);
2339     OBT_PROP_SETS(self->window, OB_APP_TITLE, utf8, self->original_title);
2340
2341     switch (self->type) {
2342     case OB_CLIENT_TYPE_NORMAL:
2343         type = "normal"; break;
2344     case OB_CLIENT_TYPE_DIALOG:
2345         type = "dialog"; break;
2346     case OB_CLIENT_TYPE_UTILITY:
2347         type = "utility"; break;
2348     case OB_CLIENT_TYPE_MENU:
2349         type = "menu"; break;
2350     case OB_CLIENT_TYPE_TOOLBAR:
2351         type = "toolbar"; break;
2352     case OB_CLIENT_TYPE_SPLASH:
2353         type = "splash"; break;
2354     case OB_CLIENT_TYPE_DESKTOP:
2355         type = "desktop"; break;
2356     case OB_CLIENT_TYPE_DOCK:
2357         type = "dock"; break;
2358     }
2359     OBT_PROP_SETS(self->window, OB_APP_TYPE, utf8, type);
2360 }
2361
2362 static void client_change_wm_state(ObClient *self)
2363 {
2364     gulong state[2];
2365     glong old;
2366
2367     old = self->wmstate;
2368
2369     if (self->shaded || self->iconic ||
2370         (self->desktop != DESKTOP_ALL && self->desktop != screen_desktop))
2371     {
2372         self->wmstate = IconicState;
2373     } else
2374         self->wmstate = NormalState;
2375
2376     if (old != self->wmstate) {
2377         OBT_PROP_MSG(ob_screen, self->window, KDE_WM_CHANGE_STATE,
2378                      self->wmstate, 1, 0, 0, 0);
2379
2380         state[0] = self->wmstate;
2381         state[1] = None;
2382         OBT_PROP_SETA32(self->window, WM_STATE, WM_STATE, state, 2);
2383     }
2384 }
2385
2386 static void client_change_state(ObClient *self)
2387 {
2388     gulong netstate[12];
2389     guint num;
2390
2391     num = 0;
2392     if (self->modal)
2393         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_MODAL);
2394     if (self->shaded)
2395         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_SHADED);
2396     if (self->iconic)
2397         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_HIDDEN);
2398     if (self->skip_taskbar)
2399         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_SKIP_TASKBAR);
2400     if (self->skip_pager)
2401         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_SKIP_PAGER);
2402     if (self->fullscreen)
2403         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_FULLSCREEN);
2404     if (self->max_vert)
2405         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_MAXIMIZED_VERT);
2406     if (self->max_horz)
2407         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_MAXIMIZED_HORZ);
2408     if (self->above)
2409         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_ABOVE);
2410     if (self->below)
2411         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_BELOW);
2412     if (self->demands_attention)
2413         netstate[num++] = OBT_PROP_ATOM(NET_WM_STATE_DEMANDS_ATTENTION);
2414     if (self->undecorated)
2415         netstate[num++] = OBT_PROP_ATOM(OB_WM_STATE_UNDECORATED);
2416     OBT_PROP_SETA32(self->window, NET_WM_STATE, ATOM, netstate, num);
2417
2418     if (self->frame)
2419         frame_adjust_state(self->frame);
2420 }
2421
2422 ObClient *client_search_focus_tree(ObClient *self)
2423 {
2424     GSList *it;
2425     ObClient *ret;
2426
2427     for (it = self->transients; it; it = g_slist_next(it)) {
2428         if (client_focused(it->data)) return it->data;
2429         if ((ret = client_search_focus_tree(it->data))) return ret;
2430     }
2431     return NULL;
2432 }
2433
2434 ObClient *client_search_focus_tree_full(ObClient *self)
2435 {
2436     if (self->parents) {
2437         GSList *it;
2438
2439         for (it = self->parents; it; it = g_slist_next(it)) {
2440             ObClient *c = it->data;
2441             if ((c = client_search_focus_tree_full(c))) return c;
2442         }
2443
2444         return NULL;
2445     }
2446     else {
2447         /* this function checks the whole tree, the client_search_focus_tree
2448            does not, so we need to check this window */
2449         if (client_focused(self))
2450             return self;
2451         return client_search_focus_tree(self);
2452     }
2453 }
2454
2455 ObClient *client_search_focus_group_full(ObClient *self)
2456 {
2457     GSList *it;
2458
2459     if (self->group) {
2460         for (it = self->group->members; it; it = g_slist_next(it)) {
2461             ObClient *c = it->data;
2462
2463             if (client_focused(c)) return c;
2464             if ((c = client_search_focus_tree(it->data))) return c;
2465         }
2466     } else
2467         if (client_focused(self)) return self;
2468     return NULL;
2469 }
2470
2471 gboolean client_has_parent(ObClient *self)
2472 {
2473     return self->parents != NULL;
2474 }
2475
2476 gboolean client_is_oldfullscreen(const ObClient *self,
2477                                  const Rect *area)
2478 {
2479     const Rect *monitor, *allmonitors;
2480
2481     /* No decorations and fills the monitor = oldskool fullscreen.
2482        But not for maximized windows.
2483     */
2484
2485     if (self->decorations || self->max_horz || self->max_vert) return FALSE;
2486
2487     monitor = screen_physical_area_monitor(screen_find_monitor(area));
2488     allmonitors = screen_physical_area_all_monitors();
2489
2490     return (RECT_EQUAL(*area, *monitor) ||
2491             RECT_EQUAL(*area, *allmonitors));
2492 }
2493
2494 static ObStackingLayer calc_layer(ObClient *self)
2495 {
2496     ObStackingLayer l;
2497
2498     if (self->type == OB_CLIENT_TYPE_DESKTOP)
2499         l = OB_STACKING_LAYER_DESKTOP;
2500     else if (self->type == OB_CLIENT_TYPE_DOCK) {
2501         if (self->below) l = OB_STACKING_LAYER_NORMAL;
2502         else l = OB_STACKING_LAYER_ABOVE;
2503     }
2504     else if ((self->fullscreen ||
2505               client_is_oldfullscreen(self, &self->area)) &&
2506              /* you are fullscreen while you or your children are focused.. */
2507              (client_focused(self) || client_search_focus_tree(self) ||
2508               /* you can be fullscreen if you're on another desktop */
2509               (self->desktop != screen_desktop &&
2510                self->desktop != DESKTOP_ALL) ||
2511               /* and you can also be fullscreen if the focused client is on
2512                  another monitor, or nothing else is focused */
2513               (!focus_client ||
2514                client_monitor(focus_client) != client_monitor(self))))
2515         l = OB_STACKING_LAYER_FULLSCREEN;
2516     else if (self->above) l = OB_STACKING_LAYER_ABOVE;
2517     else if (self->below) l = OB_STACKING_LAYER_BELOW;
2518     else l = OB_STACKING_LAYER_NORMAL;
2519
2520     return l;
2521 }
2522
2523 static void client_calc_layer_recursive(ObClient *self, ObClient *orig,
2524                                         ObStackingLayer min)
2525 {
2526     ObStackingLayer old, own;
2527     GSList *it;
2528
2529     old = self->layer;
2530     own = calc_layer(self);
2531     self->layer = MAX(own, min);
2532
2533     if (self->layer != old) {
2534         stacking_remove(CLIENT_AS_WINDOW(self));
2535         stacking_add_nonintrusive(CLIENT_AS_WINDOW(self));
2536     }
2537
2538     /* we've been restacked */
2539     self->visited = TRUE;
2540
2541     for (it = self->transients; it; it = g_slist_next(it))
2542         client_calc_layer_recursive(it->data, orig,
2543                                     self->layer);
2544 }
2545
2546 static void client_calc_layer_internal(ObClient *self)
2547 {
2548     GSList *sit;
2549
2550     /* transients take on the layer of their parents */
2551     sit = client_search_all_top_parents(self);
2552
2553     for (; sit; sit = g_slist_next(sit))
2554         client_calc_layer_recursive(sit->data, self, 0);
2555 }
2556
2557 void client_calc_layer(ObClient *self)
2558 {
2559     GList *it;
2560
2561     /* skip over stuff above fullscreen layer */
2562     for (it = stacking_list; it; it = g_list_next(it))
2563         if (window_layer(it->data) <= OB_STACKING_LAYER_FULLSCREEN) break;
2564
2565     /* find the windows in the fullscreen layer, and mark them not-visited */
2566     for (; it; it = g_list_next(it)) {
2567         if (window_layer(it->data) < OB_STACKING_LAYER_FULLSCREEN) break;
2568         else if (WINDOW_IS_CLIENT(it->data))
2569             WINDOW_AS_CLIENT(it->data)->visited = FALSE;
2570     }
2571
2572     client_calc_layer_internal(self);
2573
2574     /* skip over stuff above fullscreen layer */
2575     for (it = stacking_list; it; it = g_list_next(it))
2576         if (window_layer(it->data) <= OB_STACKING_LAYER_FULLSCREEN) break;
2577
2578     /* now recalc any windows in the fullscreen layer which have not
2579        had their layer recalced already */
2580     for (; it; it = g_list_next(it)) {
2581         if (window_layer(it->data) < OB_STACKING_LAYER_FULLSCREEN) break;
2582         else if (WINDOW_IS_CLIENT(it->data) &&
2583                  !WINDOW_AS_CLIENT(it->data)->visited)
2584             client_calc_layer_internal(it->data);
2585     }
2586 }
2587
2588 gboolean client_should_show(ObClient *self)
2589 {
2590     if (self->iconic)
2591         return FALSE;
2592     if (client_normal(self) && screen_showing_desktop)
2593         return FALSE;
2594     if (self->desktop == screen_desktop || self->desktop == DESKTOP_ALL)
2595         return TRUE;
2596
2597     return FALSE;
2598 }
2599
2600 gboolean client_show(ObClient *self)
2601 {
2602     gboolean show = FALSE;
2603
2604     if (client_should_show(self)) {
2605         /* replay pending pointer event before showing the window, in case it
2606            should be going to something under the window */
2607         mouse_replay_pointer();
2608
2609         frame_show(self->frame);
2610         show = TRUE;
2611
2612         /* According to the ICCCM (sec 4.1.3.1) when a window is not visible,
2613            it needs to be in IconicState. This includes when it is on another
2614            desktop!
2615         */
2616         client_change_wm_state(self);
2617     }
2618     return show;
2619 }
2620
2621 gboolean client_hide(ObClient *self)
2622 {
2623     gboolean hide = FALSE;
2624
2625     if (!client_should_show(self)) {
2626         /* We don't need to ignore enter events here.
2627            The window can hide/iconify in 3 different ways:
2628            1 - through an x message. in this case we ignore all enter events
2629                caused by responding to the x message (unless underMouse)
2630            2 - by a keyboard action. in this case we ignore all enter events
2631                caused by the action
2632            3 - by a mouse action. in this case they are doing stuff with the
2633                mouse and focus _should_ move.
2634
2635            Also in action_end, we simulate an enter event that can't be ignored
2636            so trying to ignore them is futile in case 3 anyways
2637         */
2638
2639         /* replay pending pointer event before hiding the window, in case it
2640            should be going to the window */
2641         mouse_replay_pointer();
2642
2643         frame_hide(self->frame);
2644         hide = TRUE;
2645
2646         /* According to the ICCCM (sec 4.1.3.1) when a window is not visible,
2647            it needs to be in IconicState. This includes when it is on another
2648            desktop!
2649         */
2650         client_change_wm_state(self);
2651     }
2652     return hide;
2653 }
2654
2655 void client_showhide(ObClient *self)
2656 {
2657     if (!client_show(self))
2658         client_hide(self);
2659 }
2660
2661 gboolean client_normal(ObClient *self) {
2662     return ! (self->type == OB_CLIENT_TYPE_DESKTOP ||
2663               self->type == OB_CLIENT_TYPE_DOCK ||
2664               self->type == OB_CLIENT_TYPE_SPLASH);
2665 }
2666
2667 gboolean client_helper(ObClient *self)
2668 {
2669     return (self->type == OB_CLIENT_TYPE_UTILITY ||
2670             self->type == OB_CLIENT_TYPE_MENU ||
2671             self->type == OB_CLIENT_TYPE_TOOLBAR);
2672 }
2673
2674 gboolean client_mouse_focusable(ObClient *self)
2675 {
2676     return !(self->type == OB_CLIENT_TYPE_MENU ||
2677              self->type == OB_CLIENT_TYPE_TOOLBAR ||
2678              self->type == OB_CLIENT_TYPE_SPLASH ||
2679              self->type == OB_CLIENT_TYPE_DOCK);
2680 }
2681
2682 gboolean client_enter_focusable(ObClient *self)
2683 {
2684     /* you can focus desktops but it shouldn't on enter */
2685     return (client_mouse_focusable(self) &&
2686             self->type != OB_CLIENT_TYPE_DESKTOP);
2687 }
2688
2689 static void client_apply_startup_state(ObClient *self,
2690                                        gint x, gint y, gint w, gint h)
2691 {
2692     /* save the states that we are going to apply */
2693     gboolean iconic = self->iconic;
2694     gboolean fullscreen = self->fullscreen;
2695     gboolean undecorated = self->undecorated;
2696     gboolean shaded = self->shaded;
2697     gboolean demands_attention = self->demands_attention;
2698     gboolean max_horz = self->max_horz;
2699     gboolean max_vert = self->max_vert;
2700     Rect oldarea;
2701     gint l;
2702
2703     /* turn them all off in the client, so they won't affect the window
2704        being placed */
2705     self->iconic = self->fullscreen = self->undecorated = self->shaded =
2706         self->demands_attention = self->max_horz = self->max_vert = FALSE;
2707
2708     /* move the client to its placed position, or it it's already there,
2709        generate a ConfigureNotify telling the client where it is.
2710
2711        do this after adjusting the frame. otherwise it gets all weird and
2712        clients don't work right
2713
2714        do this before applying the states so they have the correct
2715        pre-max/pre-fullscreen values
2716     */
2717     client_try_configure(self, &x, &y, &w, &h, &l, &l, FALSE);
2718     ob_debug("placed window 0x%x at %d, %d with size %d x %d",
2719              self->window, x, y, w, h);
2720     /* save the area, and make it where it should be for the premax stuff */
2721     oldarea = self->area;
2722     RECT_SET(self->area, x, y, w, h);
2723
2724     /* apply the states. these are in a carefully crafted order.. */
2725
2726     if (iconic)
2727         client_iconify(self, TRUE, FALSE, TRUE);
2728     if (fullscreen)
2729         client_fullscreen(self, TRUE);
2730     if (undecorated)
2731         client_set_undecorated(self, TRUE);
2732     if (shaded)
2733         client_shade(self, TRUE);
2734     if (demands_attention)
2735         client_hilite(self, TRUE);
2736
2737     if (max_vert && max_horz)
2738         client_maximize(self, TRUE, 0);
2739     else if (max_vert)
2740         client_maximize(self, TRUE, 2);
2741     else if (max_horz)
2742         client_maximize(self, TRUE, 1);
2743
2744     /* if the window hasn't been configured yet, then do so now, in fact the
2745        x,y,w,h may _not_ be the same as the area rect, which can end up
2746        meaning that the client isn't properly moved/resized by the fullscreen
2747        function
2748        pho can cause this because it maps at size of the screen but not 0,0
2749        so openbox moves it on screen to 0,0 (thus x,y=0,0 and area.x,y don't).
2750        then fullscreen'ing makes it go to 0,0 which it thinks it already is at
2751        cuz thats where the pre-fullscreen will be. however the actual area is
2752        not, so this needs to be called even if we have fullscreened/maxed
2753     */
2754     self->area = oldarea;
2755     client_configure(self, x, y, w, h, FALSE, TRUE, FALSE);
2756
2757     /* set the desktop hint, to make sure that it always exists */
2758     OBT_PROP_SET32(self->window, NET_WM_DESKTOP, CARDINAL, self->desktop);
2759
2760     /* nothing to do for the other states:
2761        skip_taskbar
2762        skip_pager
2763        modal
2764        above
2765        below
2766     */
2767 }
2768
2769 void client_gravity_resize_w(ObClient *self, gint *x, gint oldw, gint neww)
2770 {
2771     /* these should be the current values. this is for when you're not moving,
2772        just resizing */
2773     g_assert(*x == self->area.x);
2774     g_assert(oldw == self->area.width);
2775
2776     /* horizontal */
2777     switch (self->gravity) {
2778     default:
2779     case NorthWestGravity:
2780     case WestGravity:
2781     case SouthWestGravity:
2782     case StaticGravity:
2783     case ForgetGravity:
2784         break;
2785     case NorthGravity:
2786     case CenterGravity:
2787     case SouthGravity:
2788         *x -= (neww - oldw) / 2;
2789         break;
2790     case NorthEastGravity:
2791     case EastGravity:
2792     case SouthEastGravity:
2793         *x -= neww - oldw;
2794         break;
2795     }
2796 }
2797
2798 void client_gravity_resize_h(ObClient *self, gint *y, gint oldh, gint newh)
2799 {
2800     /* these should be the current values. this is for when you're not moving,
2801        just resizing */
2802     g_assert(*y == self->area.y);
2803     g_assert(oldh == self->area.height);
2804
2805     /* vertical */
2806     switch (self->gravity) {
2807     default:
2808     case NorthWestGravity:
2809     case NorthGravity:
2810     case NorthEastGravity:
2811     case StaticGravity:
2812     case ForgetGravity:
2813         break;
2814     case WestGravity:
2815     case CenterGravity:
2816     case EastGravity:
2817         *y -= (newh - oldh) / 2;
2818         break;
2819     case SouthWestGravity:
2820     case SouthGravity:
2821     case SouthEastGravity:
2822         *y -= newh - oldh;
2823         break;
2824     }
2825 }
2826
2827 void client_try_configure(ObClient *self, gint *x, gint *y, gint *w, gint *h,
2828                           gint *logicalw, gint *logicalh,
2829                           gboolean user)
2830 {
2831     Rect desired = {*x, *y, *w, *h};
2832     frame_rect_to_frame(self->frame, &desired);
2833
2834     /* make the frame recalculate its dimensions n shit without changing
2835        anything visible for real, this way the constraints below can work with
2836        the updated frame dimensions. */
2837     frame_adjust_area(self->frame, FALSE, TRUE, TRUE);
2838
2839     /* gets the frame's position */
2840     frame_client_gravity(self->frame, x, y);
2841
2842     /* these positions are frame positions, not client positions */
2843
2844     /* set the size and position if fullscreen */
2845     if (self->fullscreen) {
2846         const Rect *a;
2847         guint i;
2848
2849         i = screen_find_monitor(&desired);
2850         a = screen_physical_area_monitor(i);
2851
2852         *x = a->x;
2853         *y = a->y;
2854         *w = a->width;
2855         *h = a->height;
2856
2857         user = FALSE; /* ignore if the client can't be moved/resized when it
2858                          is fullscreening */
2859     } else if (self->max_horz || self->max_vert) {
2860         Rect *a;
2861         guint i;
2862
2863         /* use all possible struts when maximizing to the full screen */
2864         i = screen_find_monitor(&desired);
2865         a = screen_area(self->desktop, i,
2866                         (self->max_horz && self->max_vert ? NULL : &desired));
2867
2868         /* set the size and position if maximized */
2869         if (self->max_horz) {
2870             *x = a->x;
2871             *w = a->width - self->frame->size.left - self->frame->size.right;
2872         }
2873         if (self->max_vert) {
2874             *y = a->y;
2875             *h = a->height - self->frame->size.top - self->frame->size.bottom;
2876         }
2877
2878         user = FALSE; /* ignore if the client can't be moved/resized when it
2879                          is maximizing */
2880
2881         g_slice_free(Rect, a);
2882     }
2883
2884     /* gets the client's position */
2885     frame_frame_gravity(self->frame, x, y);
2886
2887     /* work within the preferred sizes given by the window, these may have
2888        changed rather than it's requested width and height, so always run
2889        through this code */
2890     {
2891         gint basew, baseh, minw, minh;
2892         gint incw, inch;
2893         gfloat minratio, maxratio;
2894
2895         incw = self->fullscreen || self->max_horz ? 1 : self->size_inc.width;
2896         inch = self->fullscreen || self->max_vert ? 1 : self->size_inc.height;
2897         minratio = self->fullscreen || (self->max_horz && self->max_vert) ?
2898             0 : self->min_ratio;
2899         maxratio = self->fullscreen || (self->max_horz && self->max_vert) ?
2900             0 : self->max_ratio;
2901
2902         /* base size is substituted with min size if not specified */
2903         if (self->base_size.width >= 0 || self->base_size.height >= 0) {
2904             basew = self->base_size.width;
2905             baseh = self->base_size.height;
2906         } else {
2907             basew = self->min_size.width;
2908             baseh = self->min_size.height;
2909         }
2910         /* min size is substituted with base size if not specified */
2911         if (self->min_size.width || self->min_size.height) {
2912             minw = self->min_size.width;
2913             minh = self->min_size.height;
2914         } else {
2915             minw = self->base_size.width;
2916             minh = self->base_size.height;
2917         }
2918
2919         /* This comment is no longer true */
2920         /* if this is a user-requested resize, then check against min/max
2921            sizes */
2922
2923         /* smaller than min size or bigger than max size? */
2924         if (*w > self->max_size.width) *w = self->max_size.width;
2925         if (*w < minw) *w = minw;
2926         if (*h > self->max_size.height) *h = self->max_size.height;
2927         if (*h < minh) *h = minh;
2928
2929         *w -= basew;
2930         *h -= baseh;
2931
2932         /* keep to the increments */
2933         *w /= incw;
2934         *h /= inch;
2935
2936         /* you cannot resize to nothing */
2937         if (basew + *w < 1) *w = 1 - basew;
2938         if (baseh + *h < 1) *h = 1 - baseh;
2939
2940         /* save the logical size */
2941         *logicalw = incw > 1 ? *w : *w + basew;
2942         *logicalh = inch > 1 ? *h : *h + baseh;
2943
2944         *w *= incw;
2945         *h *= inch;
2946
2947         *w += basew;
2948         *h += baseh;
2949
2950         /* adjust the height to match the width for the aspect ratios.
2951            for this, min size is not substituted for base size ever. */
2952         *w -= self->base_size.width;
2953         *h -= self->base_size.height;
2954
2955         if (minratio)
2956             if (*h * minratio > *w) {
2957                 *h = (gint)(*w / minratio);
2958
2959                 /* you cannot resize to nothing */
2960                 if (*h < 1) {
2961                     *h = 1;
2962                     *w = (gint)(*h * minratio);
2963                 }
2964             }
2965         if (maxratio)
2966             if (*h * maxratio < *w) {
2967                 *h = (gint)(*w / maxratio);
2968
2969                 /* you cannot resize to nothing */
2970                 if (*h < 1) {
2971                     *h = 1;
2972                     *w = (gint)(*h * minratio);
2973                 }
2974             }
2975
2976         *w += self->base_size.width;
2977         *h += self->base_size.height;
2978     }
2979
2980     /* these override the above states! if you cant move you can't move! */
2981     if (user) {
2982         if (!(self->functions & OB_CLIENT_FUNC_MOVE)) {
2983             *x = self->area.x;
2984             *y = self->area.y;
2985         }
2986         if (!(self->functions & OB_CLIENT_FUNC_RESIZE)) {
2987             *w = self->area.width;
2988             *h = self->area.height;
2989         }
2990     }
2991
2992     g_assert(*w > 0);
2993     g_assert(*h > 0);
2994 }
2995
2996 void client_configure(ObClient *self, gint x, gint y, gint w, gint h,
2997                       gboolean user, gboolean final, gboolean force_reply)
2998 {
2999     Rect oldframe, oldclient;
3000     gboolean send_resize_client;
3001     gboolean moved = FALSE, resized = FALSE, rootmoved = FALSE;
3002     gboolean fmoved, fresized;
3003     guint fdecor = self->frame->decorations;
3004     gboolean fhorz = self->frame->max_horz;
3005     gboolean fvert = self->frame->max_vert;
3006     gint logicalw, logicalh;
3007
3008     /* find the new x, y, width, and height (and logical size) */
3009     client_try_configure(self, &x, &y, &w, &h, &logicalw, &logicalh, user);
3010
3011     /* set the logical size if things changed */
3012     if (!(w == self->area.width && h == self->area.height))
3013         SIZE_SET(self->logical_size, logicalw, logicalh);
3014
3015     /* figure out if we moved or resized or what */
3016     moved = (x != self->area.x || y != self->area.y);
3017     resized = (w != self->area.width || h != self->area.height);
3018
3019     oldframe = self->frame->area;
3020     oldclient = self->area;
3021     RECT_SET(self->area, x, y, w, h);
3022
3023     /* for app-requested resizes, always resize if 'resized' is true.
3024        for user-requested ones, only resize if final is true, or when
3025        resizing in redraw mode */
3026     send_resize_client = ((!user && resized) ||
3027                           (user && (final ||
3028                                     (resized && config_resize_redraw))));
3029
3030     /* if the client is enlarging, then resize the client before the frame */
3031     if (send_resize_client && (w > oldclient.width || h > oldclient.height)) {
3032         XMoveResizeWindow(obt_display, self->window,
3033                           self->frame->size.left, self->frame->size.top,
3034                           MAX(w, oldclient.width), MAX(h, oldclient.height));
3035         frame_adjust_client_area(self->frame);
3036     }
3037
3038     /* find the frame's dimensions and move/resize it */
3039     fmoved = moved;
3040     fresized = resized;
3041
3042     /* if decorations changed, then readjust everything for the frame */
3043     if (self->decorations != fdecor ||
3044         self->max_horz != fhorz || self->max_vert != fvert)
3045     {
3046         fmoved = fresized = TRUE;
3047     }
3048
3049     /* adjust the frame */
3050     if (fmoved || fresized) {
3051         gulong ignore_start;
3052         if (!user)
3053             ignore_start = event_start_ignore_all_enters();
3054
3055         /* replay pending pointer event before move the window, in case it
3056            would change what window gets the event */
3057         mouse_replay_pointer();
3058
3059         frame_adjust_area(self->frame, fmoved, fresized, FALSE);
3060
3061         if (!user)
3062             event_end_ignore_all_enters(ignore_start);
3063     }
3064
3065     if (!user || final) {
3066         gint oldrx = self->root_pos.x;
3067         gint oldry = self->root_pos.y;
3068         /* we have reset the client to 0 border width, so don't include
3069            it in these coords */
3070         POINT_SET(self->root_pos,
3071                   self->frame->area.x + self->frame->size.left -
3072                   self->border_width,
3073                   self->frame->area.y + self->frame->size.top -
3074                   self->border_width);
3075         if (self->root_pos.x != oldrx || self->root_pos.y != oldry)
3076             rootmoved = TRUE;
3077     }
3078
3079     /* This is kinda tricky and should not be changed.. let me explain!
3080
3081        When user = FALSE, then the request is coming from the application
3082        itself, and we are more strict about when to send a synthetic
3083        ConfigureNotify.  We strictly follow the rules of the ICCCM sec 4.1.5
3084        in this case (if force_reply is true)
3085
3086        When user = TRUE, then the request is coming from "us", like when we
3087        maximize a window or something.  In this case we are more lenient.  We
3088        used to follow the same rules as above, but _Java_ Swing can't handle
3089        this. So just to appease Swing, when user = TRUE, we always send
3090        a synthetic ConfigureNotify to give the window its root coordinates.
3091        Lastly, if force_reply is TRUE, we always send a
3092        ConfigureNotify, which is needed during a resize with XSYNCronization.
3093     */
3094     if ((!user && !resized && (rootmoved || force_reply)) ||
3095         (user && ((!resized && force_reply) || (final && rootmoved))))
3096     {
3097         XEvent event;
3098
3099         event.type = ConfigureNotify;
3100         event.xconfigure.display = obt_display;
3101         event.xconfigure.event = self->window;
3102         event.xconfigure.window = self->window;
3103
3104         ob_debug("Sending ConfigureNotify to %s for %d,%d %dx%d",
3105                  self->title, self->root_pos.x, self->root_pos.y, w, h);
3106
3107         /* root window real coords */
3108         event.xconfigure.x = self->root_pos.x;
3109         event.xconfigure.y = self->root_pos.y;
3110         event.xconfigure.width = w;
3111         event.xconfigure.height = h;
3112         event.xconfigure.border_width = self->border_width;
3113         event.xconfigure.above = None;
3114         event.xconfigure.override_redirect = FALSE;
3115         XSendEvent(event.xconfigure.display, event.xconfigure.window,
3116                    FALSE, StructureNotifyMask, &event);
3117     }
3118
3119     /* if the client is shrinking, then resize the frame before the client.
3120
3121        both of these resize sections may run, because the top one only resizes
3122        in the direction that is growing
3123      */
3124     if (send_resize_client && (w <= oldclient.width || h <= oldclient.height))
3125     {
3126         frame_adjust_client_area(self->frame);
3127         XMoveResizeWindow(obt_display, self->window,
3128                           self->frame->size.left, self->frame->size.top, w, h);
3129     }
3130
3131     XFlush(obt_display);
3132
3133     /* if it moved between monitors, then this can affect the stacking
3134        layer of this window or others - for fullscreen windows.
3135        also if it changed to/from oldschool fullscreen then its layer may
3136        change
3137
3138        watch out tho, don't try change stacking stuff if the window is no
3139        longer being managed !
3140     */
3141     if (self->managed &&
3142         (screen_find_monitor(&self->frame->area) !=
3143          screen_find_monitor(&oldframe) ||
3144          (final && (client_is_oldfullscreen(self, &oldclient) !=
3145                     client_is_oldfullscreen(self, &self->area)))))
3146     {
3147         client_calc_layer(self);
3148     }
3149 }
3150
3151 void client_fullscreen(ObClient *self, gboolean fs)
3152 {
3153     gint x, y, w, h;
3154
3155     if (!(self->functions & OB_CLIENT_FUNC_FULLSCREEN) || /* can't */
3156         self->fullscreen == fs) return;                   /* already done */
3157
3158     self->fullscreen = fs;
3159     client_change_state(self); /* change the state hints on the client */
3160
3161     if (fs) {
3162         self->pre_fullscreen_area = self->area;
3163         self->pre_fullscreen_max_horz = self->max_horz;
3164         self->pre_fullscreen_max_vert = self->max_vert;
3165
3166         /* if the window is maximized, its area isn't all that meaningful.
3167            save its premax area instead. */
3168         if (self->max_horz) {
3169             self->pre_fullscreen_area.x = self->pre_max_area.x;
3170             self->pre_fullscreen_area.width = self->pre_max_area.width;
3171         }
3172         if (self->max_vert) {
3173             self->pre_fullscreen_area.y = self->pre_max_area.y;
3174             self->pre_fullscreen_area.height = self->pre_max_area.height;
3175         }
3176
3177         /* these will help configure_full figure out where to fullscreen
3178            the window */
3179         x = self->area.x;
3180         y = self->area.y;
3181         w = self->area.width;
3182         h = self->area.height;
3183     } else {
3184         g_assert(self->pre_fullscreen_area.width > 0 &&
3185                  self->pre_fullscreen_area.height > 0);
3186
3187         self->max_horz = self->pre_fullscreen_max_horz;
3188         self->max_vert = self->pre_fullscreen_max_vert;
3189         if (self->max_horz) {
3190             self->pre_max_area.x = self->pre_fullscreen_area.x;
3191             self->pre_max_area.width = self->pre_fullscreen_area.width;
3192         }
3193         if (self->max_vert) {
3194             self->pre_max_area.y = self->pre_fullscreen_area.y;
3195             self->pre_max_area.height = self->pre_fullscreen_area.height;
3196         }
3197
3198         x = self->pre_fullscreen_area.x;
3199         y = self->pre_fullscreen_area.y;
3200         w = self->pre_fullscreen_area.width;
3201         h = self->pre_fullscreen_area.height;
3202         RECT_SET(self->pre_fullscreen_area, 0, 0, 0, 0);
3203     }
3204
3205     ob_debug("Window %s going fullscreen (%d)",
3206              self->title, self->fullscreen);
3207
3208     if (fs) {
3209         /* make sure the window is on some monitor */
3210         client_find_onscreen(self, &x, &y, w, h, FALSE);
3211     }
3212
3213     client_setup_decor_and_functions(self, FALSE);
3214     client_move_resize(self, x, y, w, h);
3215
3216     /* and adjust our layer/stacking. do this after resizing the window,
3217        and applying decorations, because windows which fill the screen are
3218        considered "fullscreen" and it affects their layer */
3219     client_calc_layer(self);
3220
3221     if (fs) {
3222         /* try focus us when we go into fullscreen mode */
3223         client_focus(self);
3224     }
3225 }
3226
3227 static void client_iconify_recursive(ObClient *self,
3228                                      gboolean iconic, gboolean curdesk,
3229                                      gboolean hide_animation)
3230 {
3231     GSList *it;
3232     gboolean changed = FALSE;
3233
3234     if (self->iconic != iconic) {
3235         ob_debug("%sconifying window: 0x%lx", (iconic ? "I" : "Uni"),
3236                  self->window);
3237
3238         if (iconic) {
3239             /* don't let non-normal windows iconify along with their parents
3240                or whatever */
3241             if (client_normal(self)) {
3242                 self->iconic = iconic;
3243
3244                 /* update the focus lists.. iconic windows go to the bottom of
3245                    the list. this will also call focus_cycle_addremove(). */
3246                 focus_order_to_bottom(self);
3247
3248                 changed = TRUE;
3249             }
3250         } else {
3251             self->iconic = iconic;
3252
3253             if (curdesk && self->desktop != screen_desktop &&
3254                 self->desktop != DESKTOP_ALL)
3255                 client_set_desktop(self, screen_desktop, FALSE, FALSE);
3256
3257             /* this puts it after the current focused window, this will
3258                also cause focus_cycle_addremove() to be called for the
3259                client */
3260             focus_order_like_new(self);
3261
3262             changed = TRUE;
3263         }
3264     }
3265
3266     if (changed) {
3267         client_change_state(self);
3268         if (config_animate_iconify && !hide_animation)
3269             frame_begin_iconify_animation(self->frame, iconic);
3270         /* do this after starting the animation so it doesn't flash */
3271         client_showhide(self);
3272     }
3273
3274     /* iconify all direct transients, and deiconify all transients
3275        (non-direct too) */
3276     for (it = self->transients; it; it = g_slist_next(it))
3277         if (it->data != self)
3278             if (client_is_direct_child(self, it->data) || !iconic)
3279                 client_iconify_recursive(it->data, iconic, curdesk,
3280                                          hide_animation);
3281 }
3282
3283 void client_iconify(ObClient *self, gboolean iconic, gboolean curdesk,
3284                     gboolean hide_animation)
3285 {
3286     if (self->functions & OB_CLIENT_FUNC_ICONIFY || !iconic) {
3287         /* move up the transient chain as far as possible first */
3288         self = client_search_top_direct_parent(self);
3289         client_iconify_recursive(self, iconic, curdesk, hide_animation);
3290     }
3291 }
3292
3293 void client_maximize(ObClient *self, gboolean max, gint dir)
3294 {
3295     gint x, y, w, h;
3296
3297     g_assert(dir == 0 || dir == 1 || dir == 2);
3298     if (!(self->functions & OB_CLIENT_FUNC_MAXIMIZE) && max) return;/* can't */
3299
3300     /* check if already done */
3301     if (max) {
3302         if (dir == 0 && self->max_horz && self->max_vert) return;
3303         if (dir == 1 && self->max_horz) return;
3304         if (dir == 2 && self->max_vert) return;
3305     } else {
3306         if (dir == 0 && !self->max_horz && !self->max_vert) return;
3307         if (dir == 1 && !self->max_horz) return;
3308         if (dir == 2 && !self->max_vert) return;
3309     }
3310
3311     /* these will help configure_full figure out which screen to fill with
3312        the window */
3313     x = self->area.x;
3314     y = self->area.y;
3315     w = self->area.width;
3316     h = self->area.height;
3317
3318     if (max) {
3319         if ((dir == 0 || dir == 1) && !self->max_horz) { /* horz */
3320             RECT_SET(self->pre_max_area,
3321                      self->area.x, self->pre_max_area.y,
3322                      self->area.width, self->pre_max_area.height);
3323         }
3324         if ((dir == 0 || dir == 2) && !self->max_vert) { /* vert */
3325             RECT_SET(self->pre_max_area,
3326                      self->pre_max_area.x, self->area.y,
3327                      self->pre_max_area.width, self->area.height);
3328         }
3329     } else {
3330         if ((dir == 0 || dir == 1) && self->max_horz) { /* horz */
3331             g_assert(self->pre_max_area.width > 0);
3332
3333             x = self->pre_max_area.x;
3334             w = self->pre_max_area.width;
3335
3336             RECT_SET(self->pre_max_area, 0, self->pre_max_area.y,
3337                      0, self->pre_max_area.height);
3338         }
3339         if ((dir == 0 || dir == 2) && self->max_vert) { /* vert */
3340             g_assert(self->pre_max_area.height > 0);
3341
3342             y = self->pre_max_area.y;
3343             h = self->pre_max_area.height;
3344
3345             RECT_SET(self->pre_max_area, self->pre_max_area.x, 0,
3346                      self->pre_max_area.width, 0);
3347         }
3348     }
3349
3350     if (dir == 0 || dir == 1) /* horz */
3351         self->max_horz = max;
3352     if (dir == 0 || dir == 2) /* vert */
3353         self->max_vert = max;
3354
3355     if (max) {
3356         /* make sure the window is on some monitor */
3357         client_find_onscreen(self, &x, &y, w, h, FALSE);
3358     }
3359
3360     client_change_state(self); /* change the state hints on the client */
3361
3362     client_setup_decor_and_functions(self, FALSE);
3363     client_move_resize(self, x, y, w, h);
3364 }
3365
3366 void client_shade(ObClient *self, gboolean shade)
3367 {
3368     if ((!(self->functions & OB_CLIENT_FUNC_SHADE) &&
3369          shade) ||                         /* can't shade */
3370         self->shaded == shade) return;     /* already done */
3371
3372     self->shaded = shade;
3373     client_change_state(self);
3374     client_change_wm_state(self); /* the window is being hidden/shown */
3375     /* resize the frame to just the titlebar */
3376     frame_adjust_area(self->frame, FALSE, TRUE, FALSE);
3377 }
3378
3379 static void client_ping_event(ObClient *self, gboolean dead)
3380 {
3381     if (self->not_responding != dead) {
3382         self->not_responding = dead;
3383         client_update_title(self);
3384
3385         if (dead)
3386             /* the client isn't responding, so ask to kill it */
3387             client_prompt_kill(self);
3388         else {
3389             /* it came back to life ! */
3390
3391             if (self->kill_prompt) {
3392                 prompt_unref(self->kill_prompt);
3393                 self->kill_prompt = NULL;
3394             }
3395
3396             self->kill_level = 0;
3397         }
3398     }
3399 }
3400
3401 void client_close(ObClient *self)
3402 {
3403     if (!(self->functions & OB_CLIENT_FUNC_CLOSE)) return;
3404
3405     /* if closing an internal obprompt, that is just cancelling it */
3406     if (self->prompt) {
3407         prompt_cancel(self->prompt);
3408         return;
3409     }
3410
3411     /* in the case that the client provides no means to requesting that it
3412        close, we just kill it */
3413     if (!self->delete_window)
3414         /* don't use client_kill(), we should only kill based on PID in
3415            response to a lack of PING replies */
3416         XKillClient(obt_display, self->window);
3417     else {
3418         /* request the client to close with WM_DELETE_WINDOW */
3419         OBT_PROP_MSG_TO(self->window, self->window, WM_PROTOCOLS,
3420                         OBT_PROP_ATOM(WM_DELETE_WINDOW), event_time(),
3421                         0, 0, 0, NoEventMask);
3422
3423         /* we're trying to close the window, so see if it is responding. if it
3424            is not, then we will let them kill the window */
3425         if (self->ping)
3426             ping_start(self, client_ping_event);
3427
3428         /* if we already know the window isn't responding (maybe they clicked
3429            no in the kill dialog but it hasn't come back to life), then show
3430            the kill dialog */
3431         if (self->not_responding)
3432             client_prompt_kill(self);
3433     }
3434 }
3435
3436 #define OB_KILL_RESULT_NO 0
3437 #define OB_KILL_RESULT_YES 1
3438
3439 static gboolean client_kill_requested(ObPrompt *p, gint result, gpointer data)
3440 {
3441     ObClient *self = data;
3442
3443     if (result == OB_KILL_RESULT_YES)
3444         client_kill(self);
3445     return TRUE; /* call the cleanup func */
3446 }
3447
3448 static void client_kill_cleanup(ObPrompt *p, gpointer data)
3449 {
3450     ObClient *self = data;
3451
3452     g_assert(p == self->kill_prompt);
3453
3454     prompt_unref(self->kill_prompt);
3455     self->kill_prompt = NULL;
3456 }
3457
3458 static void client_prompt_kill(ObClient *self)
3459 {
3460     /* check if we're already prompting */
3461     if (!self->kill_prompt) {
3462         ObPromptAnswer answers[] = {
3463             { 0, OB_KILL_RESULT_NO },
3464             { 0, OB_KILL_RESULT_YES }
3465         };
3466         gchar *m;
3467         const gchar *y, *title;
3468
3469         title = self->original_title;
3470         if (title[0] == '\0') {
3471             /* empty string, so use its parent */
3472             ObClient *p = client_search_top_direct_parent(self);
3473             if (p) title = p->original_title;
3474         }
3475
3476         if (client_on_localhost(self)) {
3477             const gchar *sig;
3478
3479             if (self->kill_level == 0)
3480                 sig = "terminate";
3481             else
3482                 sig = "kill";
3483
3484             m = g_strdup_printf
3485                 (_("The window \"%s\" does not seem to be responding.  Do you want to force it to exit by sending the %s signal?"),
3486                  title, sig);
3487             y = _("End Process");
3488         }
3489         else {
3490             m = g_strdup_printf
3491                 (_("The window \"%s\" does not seem to be responding.  Do you want to disconnect it from the X server?"),
3492                  title);
3493             y = _("Disconnect");
3494         }
3495         /* set the dialog buttons' text */
3496         answers[0].text = _("Cancel");  /* "no" */
3497         answers[1].text = y;            /* "yes" */
3498
3499         self->kill_prompt = prompt_new(m, NULL, answers,
3500                                        sizeof(answers)/sizeof(answers[0]),
3501                                        OB_KILL_RESULT_NO, /* default = no */
3502                                        OB_KILL_RESULT_NO, /* cancel = no */
3503                                        client_kill_requested,
3504                                        client_kill_cleanup,
3505                                        self);
3506         g_free(m);
3507     }
3508
3509     prompt_show(self->kill_prompt, self, TRUE);
3510 }
3511
3512 void client_kill(ObClient *self)
3513 {
3514     /* don't kill our own windows */
3515     if (self->prompt) return;
3516
3517     if (client_on_localhost(self) && self->pid) {
3518         /* running on the local host */
3519         if (self->kill_level == 0) {
3520             ob_debug("killing window 0x%x with pid %lu, with SIGTERM",
3521                      self->window, self->pid);
3522             kill(self->pid, SIGTERM);
3523             ++self->kill_level;
3524
3525             /* show that we're trying to kill it */
3526             client_update_title(self);
3527         }
3528         else {
3529             ob_debug("killing window 0x%x with pid %lu, with SIGKILL",
3530                      self->window, self->pid);
3531             kill(self->pid, SIGKILL); /* kill -9 */
3532         }
3533     }
3534     else {
3535         /* running on a remote host */
3536         XKillClient(obt_display, self->window);
3537     }
3538 }
3539
3540 void client_hilite(ObClient *self, gboolean hilite)
3541 {
3542     if (self->demands_attention == hilite)
3543         return; /* no change */
3544
3545     /* don't allow focused windows to hilite */
3546     self->demands_attention = hilite && !client_focused(self);
3547     if (self->frame != NULL) { /* if we're mapping, just set the state */
3548         if (self->demands_attention) {
3549             frame_flash_start(self->frame);
3550
3551             /* if the window is on another desktop then raise it and make it
3552                the most recently used window */
3553             if (self->desktop != screen_desktop &&
3554                 self->desktop != DESKTOP_ALL)
3555             {
3556                 stacking_raise(CLIENT_AS_WINDOW(self));
3557                 focus_order_to_top(self);
3558             }
3559         }
3560         else
3561             frame_flash_stop(self->frame);
3562         client_change_state(self);
3563     }
3564 }
3565
3566 static void client_set_desktop_recursive(ObClient *self,
3567                                          guint target,
3568                                          gboolean donthide,
3569                                          gboolean dontraise)
3570 {
3571     guint old;
3572     GSList *it;
3573
3574     if (target != self->desktop && self->type != OB_CLIENT_TYPE_DESKTOP) {
3575
3576         ob_debug("Setting desktop %u", target+1);
3577
3578         g_assert(target < screen_num_desktops || target == DESKTOP_ALL);
3579
3580         old = self->desktop;
3581         self->desktop = target;
3582         OBT_PROP_SET32(self->window, NET_WM_DESKTOP, CARDINAL, target);
3583         /* the frame can display the current desktop state */
3584         frame_adjust_state(self->frame);
3585         /* 'move' the window to the new desktop */
3586         if (!donthide)
3587             client_hide(self);
3588         client_show(self);
3589         /* raise if it was not already on the desktop */
3590         if (old != DESKTOP_ALL && !dontraise)
3591             stacking_raise(CLIENT_AS_WINDOW(self));
3592         if (STRUT_EXISTS(self->strut))
3593             screen_update_areas();
3594         else
3595             /* the new desktop's geometry may be different, so we may need to
3596                resize, for example if we are maximized */
3597             client_reconfigure(self, FALSE);
3598
3599         focus_cycle_addremove(self, FALSE);
3600     }
3601
3602     /* move all transients */
3603     for (it = self->transients; it; it = g_slist_next(it))
3604         if (it->data != self)
3605             if (client_is_direct_child(self, it->data))
3606                 client_set_desktop_recursive(it->data, target,
3607                                              donthide, dontraise);
3608 }
3609
3610 void client_set_desktop(ObClient *self, guint target,
3611                         gboolean donthide, gboolean dontraise)
3612 {
3613     self = client_search_top_direct_parent(self);
3614     client_set_desktop_recursive(self, target, donthide, dontraise);
3615
3616     focus_cycle_addremove(NULL, TRUE);
3617 }
3618
3619 gboolean client_is_direct_child(ObClient *parent, ObClient *child)
3620 {
3621     while (child != parent && (child = client_direct_parent(child)));
3622     return child == parent;
3623 }
3624
3625 ObClient *client_search_modal_child(ObClient *self)
3626 {
3627     GSList *it;
3628     ObClient *ret;
3629
3630     for (it = self->transients; it; it = g_slist_next(it)) {
3631         ObClient *c = it->data;
3632         if ((ret = client_search_modal_child(c))) return ret;
3633         if (c->modal) return c;
3634     }
3635     return NULL;
3636 }
3637
3638 struct ObClientFindDestroyUnmap {
3639     Window window;
3640     gint ignore_unmaps;
3641 };
3642
3643 static gboolean find_destroy_unmap(XEvent *e, gpointer data)
3644 {
3645     struct ObClientFindDestroyUnmap *find = data;
3646     if (e->type == DestroyNotify)
3647         return e->xdestroywindow.window == find->window;
3648     if (e->type == UnmapNotify && e->xunmap.window == find->window)
3649         /* ignore the first $find->ignore_unmaps$ many unmap events */
3650         return --find->ignore_unmaps < 0;
3651     return FALSE;
3652 }
3653
3654 gboolean client_validate(ObClient *self)
3655 {
3656     struct ObClientFindDestroyUnmap find;
3657
3658     XSync(obt_display, FALSE); /* get all events on the server */
3659
3660     find.window = self->window;
3661     find.ignore_unmaps = self->ignore_unmaps;
3662     if (xqueue_exists_local(find_destroy_unmap, &find))
3663         return FALSE;
3664
3665     return TRUE;
3666 }
3667
3668 void client_set_wm_state(ObClient *self, glong state)
3669 {
3670     if (state == self->wmstate) return; /* no change */
3671
3672     switch (state) {
3673     case IconicState:
3674         client_iconify(self, TRUE, TRUE, FALSE);
3675         break;
3676     case NormalState:
3677         client_iconify(self, FALSE, TRUE, FALSE);
3678         break;
3679     }
3680 }
3681
3682 void client_set_state(ObClient *self, Atom action, glong data1, glong data2)
3683 {
3684     gboolean shaded = self->shaded;
3685     gboolean fullscreen = self->fullscreen;
3686     gboolean undecorated = self->undecorated;
3687     gboolean max_horz = self->max_horz;
3688     gboolean max_vert = self->max_vert;
3689     gboolean modal = self->modal;
3690     gboolean iconic = self->iconic;
3691     gboolean demands_attention = self->demands_attention;
3692     gboolean above = self->above;
3693     gboolean below = self->below;
3694     gint i;
3695     gboolean value;
3696
3697     if (!(action == OBT_PROP_ATOM(NET_WM_STATE_ADD) ||
3698           action == OBT_PROP_ATOM(NET_WM_STATE_REMOVE) ||
3699           action == OBT_PROP_ATOM(NET_WM_STATE_TOGGLE)))
3700         /* an invalid action was passed to the client message, ignore it */
3701         return;
3702
3703     for (i = 0; i < 2; ++i) {
3704         Atom state = i == 0 ? data1 : data2;
3705
3706         if (!state) continue;
3707
3708         /* if toggling, then pick whether we're adding or removing */
3709         if (action == OBT_PROP_ATOM(NET_WM_STATE_TOGGLE)) {
3710             if (state == OBT_PROP_ATOM(NET_WM_STATE_MODAL))
3711                 value = modal;
3712             else if (state == OBT_PROP_ATOM(NET_WM_STATE_MAXIMIZED_VERT))
3713                 value = self->max_vert;
3714             else if (state == OBT_PROP_ATOM(NET_WM_STATE_MAXIMIZED_HORZ))
3715                 value = self->max_horz;
3716             else if (state == OBT_PROP_ATOM(NET_WM_STATE_SHADED))
3717                 value = shaded;
3718             else if (state == OBT_PROP_ATOM(NET_WM_STATE_SKIP_TASKBAR))
3719                 value = self->skip_taskbar;
3720             else if (state == OBT_PROP_ATOM(NET_WM_STATE_SKIP_PAGER))
3721                 value = self->skip_pager;
3722             else if (state == OBT_PROP_ATOM(NET_WM_STATE_HIDDEN))
3723                 value = self->iconic;
3724             else if (state == OBT_PROP_ATOM(NET_WM_STATE_FULLSCREEN))
3725                 value = fullscreen;
3726             else if (state == OBT_PROP_ATOM(NET_WM_STATE_ABOVE))
3727                 value = self->above;
3728             else if (state == OBT_PROP_ATOM(NET_WM_STATE_BELOW))
3729                 value = self->below;
3730             else if (state == OBT_PROP_ATOM(NET_WM_STATE_DEMANDS_ATTENTION))
3731                 value = self->demands_attention;
3732             else if (state == OBT_PROP_ATOM(OB_WM_STATE_UNDECORATED))
3733                 value = undecorated;
3734             else
3735                 g_assert_not_reached();
3736             action = value ? OBT_PROP_ATOM(NET_WM_STATE_REMOVE) :
3737                              OBT_PROP_ATOM(NET_WM_STATE_ADD);
3738         }
3739
3740         value = action == OBT_PROP_ATOM(NET_WM_STATE_ADD);
3741         if (state == OBT_PROP_ATOM(NET_WM_STATE_MODAL)) {
3742             modal = value;
3743         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_MAXIMIZED_VERT)) {
3744             max_vert = value;
3745         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_MAXIMIZED_HORZ)) {
3746             max_horz = value;
3747         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_SHADED)) {
3748             shaded = value;
3749         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_SKIP_TASKBAR)) {
3750             self->skip_taskbar = value;
3751         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_SKIP_PAGER)) {
3752             self->skip_pager = value;
3753         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_HIDDEN)) {
3754             iconic = value;
3755         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_FULLSCREEN)) {
3756             fullscreen = value;
3757         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_ABOVE)) {
3758             above = value;
3759             /* only unset below when setting above, otherwise you can't get to
3760                the normal layer */
3761             if (value)
3762                 below = FALSE;
3763         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_BELOW)) {
3764             /* and vice versa */
3765             if (value)
3766                 above = FALSE;
3767             below = value;
3768         } else if (state == OBT_PROP_ATOM(NET_WM_STATE_DEMANDS_ATTENTION)){
3769             demands_attention = value;
3770         } else if (state == OBT_PROP_ATOM(OB_WM_STATE_UNDECORATED)) {
3771             undecorated = value;
3772         }
3773     }
3774
3775     if (max_horz != self->max_horz || max_vert != self->max_vert) {
3776         if (max_horz != self->max_horz && max_vert != self->max_vert) {
3777             /* toggling both */
3778             if (max_horz == max_vert) { /* both going the same way */
3779                 client_maximize(self, max_horz, 0);
3780             } else {
3781                 client_maximize(self, max_horz, 1);
3782                 client_maximize(self, max_vert, 2);
3783             }
3784         } else {
3785             /* toggling one */
3786             if (max_horz != self->max_horz)
3787                 client_maximize(self, max_horz, 1);
3788             else
3789                 client_maximize(self, max_vert, 2);
3790         }
3791     }
3792     /* change fullscreen state before shading, as it will affect if the window
3793        can shade or not */
3794     if (fullscreen != self->fullscreen)
3795         client_fullscreen(self, fullscreen);
3796     if (shaded != self->shaded)
3797         client_shade(self, shaded);
3798     if (undecorated != self->undecorated)
3799         client_set_undecorated(self, undecorated);
3800     if (above != self->above || below != self->below) {
3801         self->above = above;
3802         self->below = below;
3803         client_calc_layer(self);
3804     }
3805
3806     if (modal != self->modal) {
3807         self->modal = modal;
3808         /* when a window changes modality, then its stacking order with its
3809            transients needs to change */
3810         stacking_raise(CLIENT_AS_WINDOW(self));
3811
3812         /* it also may get focused. if something is focused that shouldn't
3813            be focused anymore, then move the focus */
3814         if (focus_client && client_focus_target(focus_client) != focus_client)
3815             client_focus(focus_client);
3816     }
3817
3818     if (iconic != self->iconic)
3819         client_iconify(self, iconic, FALSE, FALSE);
3820
3821     if (demands_attention != self->demands_attention)
3822         client_hilite(self, demands_attention);
3823
3824     client_change_state(self); /* change the hint to reflect these changes */
3825
3826     focus_cycle_addremove(self, TRUE);
3827 }
3828
3829 ObClient *client_focus_target(ObClient *self)
3830 {
3831     ObClient *child = NULL;
3832
3833     child = client_search_modal_child(self);
3834     if (child) return child;
3835     return self;
3836 }
3837
3838 gboolean client_can_focus(ObClient *self)
3839 {
3840     /* choose the correct target */
3841     self = client_focus_target(self);
3842
3843     if (!self->frame->visible)
3844         return FALSE;
3845
3846     if (!(self->can_focus || self->focus_notify))
3847         return FALSE;
3848
3849     return TRUE;
3850 }
3851
3852 gboolean client_focus(ObClient *self)
3853 {
3854     if (!client_validate(self)) return FALSE;
3855
3856     /* we might not focus this window, so if we have modal children which would
3857        be focused instead, bring them to this desktop */
3858     client_bring_modal_windows(self);
3859
3860     /* choose the correct target */
3861     self = client_focus_target(self);
3862
3863     if (!client_can_focus(self)) {
3864         ob_debug_type(OB_DEBUG_FOCUS,
3865                       "Client %s can't be focused", self->title);
3866         return FALSE;
3867     }
3868
3869     ob_debug_type(OB_DEBUG_FOCUS,
3870                   "Focusing client \"%s\" (0x%x) at time %u",
3871                   self->title, self->window, event_time());
3872
3873     /* if using focus_delay, stop the timer now so that focus doesn't
3874        go moving on us */
3875     event_halt_focus_delay();
3876
3877     obt_display_ignore_errors(TRUE);
3878
3879     if (self->can_focus) {
3880         /* This can cause a BadMatch error with CurrentTime, or if an app
3881            passed in a bad time for _NET_WM_ACTIVE_WINDOW. */
3882         XSetInputFocus(obt_display, self->window, RevertToPointerRoot,
3883                        event_time());
3884     }
3885
3886     if (self->focus_notify) {
3887         XEvent ce;
3888         ce.xclient.type = ClientMessage;
3889         ce.xclient.message_type = OBT_PROP_ATOM(WM_PROTOCOLS);
3890         ce.xclient.display = obt_display;
3891         ce.xclient.window = self->window;
3892         ce.xclient.format = 32;
3893         ce.xclient.data.l[0] = OBT_PROP_ATOM(WM_TAKE_FOCUS);
3894         ce.xclient.data.l[1] = event_time();
3895         ce.xclient.data.l[2] = 0l;
3896         ce.xclient.data.l[3] = 0l;
3897         ce.xclient.data.l[4] = 0l;
3898         XSendEvent(obt_display, self->window, FALSE, NoEventMask, &ce);
3899     }
3900
3901     obt_display_ignore_errors(FALSE);
3902
3903     ob_debug_type(OB_DEBUG_FOCUS, "Error focusing? %d",
3904                   obt_display_error_occured);
3905     return !obt_display_error_occured;
3906 }
3907
3908 static void client_present(ObClient *self, gboolean here, gboolean raise,
3909                            gboolean unshade)
3910 {
3911     if (client_normal(self) && screen_showing_desktop)
3912         screen_show_desktop(FALSE, self);
3913     if (self->iconic)
3914         client_iconify(self, FALSE, here, FALSE);
3915     if (self->desktop != DESKTOP_ALL &&
3916         self->desktop != screen_desktop)
3917     {
3918         if (here)
3919             client_set_desktop(self, screen_desktop, FALSE, TRUE);
3920         else
3921             screen_set_desktop(self->desktop, FALSE);
3922     } else if (!self->frame->visible)
3923         /* if its not visible for other reasons, then don't mess
3924            with it */
3925         return;
3926     if (self->shaded && unshade)
3927         client_shade(self, FALSE);
3928     if (raise)
3929         stacking_raise(CLIENT_AS_WINDOW(self));
3930
3931     client_focus(self);
3932 }
3933
3934 /* this function exists to map to the net_active_window message in the ewmh */
3935 void client_activate(ObClient *self, gboolean desktop,
3936                      gboolean here, gboolean raise,
3937                      gboolean unshade, gboolean user)
3938 {
3939     if ((user && (desktop ||
3940                   self->desktop == DESKTOP_ALL ||
3941                   self->desktop == screen_desktop)) ||
3942         client_can_steal_focus(self, event_time(), CurrentTime))
3943     {
3944         client_present(self, here, raise, unshade);
3945     }
3946     else
3947         client_hilite(self, TRUE);
3948 }
3949
3950 static void client_bring_windows_recursive(ObClient *self,
3951                                            guint desktop,
3952                                            gboolean helpers,
3953                                            gboolean modals,
3954                                            gboolean iconic)
3955 {
3956     GSList *it;
3957
3958     for (it = self->transients; it; it = g_slist_next(it))
3959         client_bring_windows_recursive(it->data, desktop,
3960                                        helpers, modals, iconic);
3961
3962     if (((helpers && client_helper(self)) ||
3963          (modals && self->modal)) &&
3964         ((self->desktop != desktop && self->desktop != DESKTOP_ALL) ||
3965          (iconic && self->iconic)))
3966     {
3967         if (iconic && self->iconic)
3968             client_iconify(self, FALSE, TRUE, FALSE);
3969         else
3970             client_set_desktop(self, desktop, FALSE, FALSE);
3971     }
3972 }
3973
3974 void client_bring_helper_windows(ObClient *self)
3975 {
3976     client_bring_windows_recursive(self, self->desktop, TRUE, FALSE, FALSE);
3977 }
3978
3979 void client_bring_modal_windows(ObClient *self)
3980 {
3981     client_bring_windows_recursive(self, self->desktop, FALSE, TRUE, TRUE);
3982 }
3983
3984 gboolean client_focused(ObClient *self)
3985 {
3986     return self == focus_client;
3987 }
3988
3989 RrImage* client_icon(ObClient *self)
3990 {
3991     RrImage *ret = NULL;
3992
3993     if (self->icon_set)
3994         ret = self->icon_set;
3995     else if (self->parents) {
3996         GSList *it;
3997         for (it = self->parents; it && !ret; it = g_slist_next(it))
3998             ret = client_icon(it->data);
3999     }
4000     if (!ret)
4001         ret = client_default_icon;
4002     return ret;
4003 }
4004
4005 void client_set_layer(ObClient *self, gint layer)
4006 {
4007     if (layer < 0) {
4008         self->below = TRUE;
4009         self->above = FALSE;
4010     } else if (layer == 0) {
4011         self->below = self->above = FALSE;
4012     } else {
4013         self->below = FALSE;
4014         self->above = TRUE;
4015     }
4016     client_calc_layer(self);
4017     client_change_state(self); /* reflect this in the state hints */
4018 }
4019
4020 void client_set_undecorated(ObClient *self, gboolean undecorated)
4021 {
4022     if (self->undecorated != undecorated &&
4023         /* don't let it undecorate if the function is missing, but let
4024            it redecorate */
4025         (self->functions & OB_CLIENT_FUNC_UNDECORATE || !undecorated))
4026     {
4027         self->undecorated = undecorated;
4028         client_setup_decor_and_functions(self, TRUE);
4029         client_change_state(self); /* reflect this in the state hints */
4030     }
4031 }
4032
4033 guint client_monitor(ObClient *self)
4034 {
4035     return screen_find_monitor(&self->frame->area);
4036 }
4037
4038 ObClient *client_direct_parent(ObClient *self)
4039 {
4040     if (!self->parents) return NULL;
4041     if (self->transient_for_group) return NULL;
4042     return self->parents->data;
4043 }
4044
4045 ObClient *client_search_top_direct_parent(ObClient *self)
4046 {
4047     ObClient *p;
4048     while ((p = client_direct_parent(self))) self = p;
4049     return self;
4050 }
4051
4052 static GSList *client_search_all_top_parents_internal(ObClient *self,
4053                                                       gboolean bylayer,
4054                                                       ObStackingLayer layer)
4055 {
4056     GSList *ret;
4057     ObClient *p;
4058
4059     /* move up the direct transient chain as far as possible */
4060     while ((p = client_direct_parent(self)) &&
4061            (!bylayer || p->layer == layer))
4062         self = p;
4063
4064     if (!self->parents)
4065         ret = g_slist_prepend(NULL, self);
4066     else
4067         ret = g_slist_copy(self->parents);
4068
4069     return ret;
4070 }
4071
4072 GSList *client_search_all_top_parents(ObClient *self)
4073 {
4074     return client_search_all_top_parents_internal(self, FALSE, 0);
4075 }
4076
4077 GSList *client_search_all_top_parents_layer(ObClient *self)
4078 {
4079     return client_search_all_top_parents_internal(self, TRUE, self->layer);
4080 }
4081
4082 ObClient *client_search_focus_parent(ObClient *self)
4083 {
4084     GSList *it;
4085
4086     for (it = self->parents; it; it = g_slist_next(it))
4087         if (client_focused(it->data)) return it->data;
4088
4089     return NULL;
4090 }
4091
4092 ObClient *client_search_focus_parent_full(ObClient *self)
4093 {
4094     GSList *it;
4095     ObClient *ret = NULL;
4096
4097     for (it = self->parents; it; it = g_slist_next(it)) {
4098         if (client_focused(it->data))
4099             ret = it->data;
4100         else
4101             ret = client_search_focus_parent_full(it->data);
4102         if (ret) break;
4103     }
4104     return ret;
4105 }
4106
4107 ObClient *client_search_parent(ObClient *self, ObClient *search)
4108 {
4109     GSList *it;
4110
4111     for (it = self->parents; it; it = g_slist_next(it))
4112         if (it->data == search) return search;
4113
4114     return NULL;
4115 }
4116
4117 ObClient *client_search_transient(ObClient *self, ObClient *search)
4118 {
4119     GSList *sit;
4120
4121     for (sit = self->transients; sit; sit = g_slist_next(sit)) {
4122         if (sit->data == search)
4123             return search;
4124         if (client_search_transient(sit->data, search))
4125             return search;
4126     }
4127     return NULL;
4128 }
4129
4130 static void detect_edge(Rect area, ObDirection dir,
4131                         gint my_head, gint my_size,
4132                         gint my_edge_start, gint my_edge_size,
4133                         gint *dest, gboolean *near_edge)
4134 {
4135     gint edge_start, edge_size, head, tail;
4136     gboolean skip_head = FALSE, skip_tail = FALSE;
4137
4138     switch (dir) {
4139         case OB_DIRECTION_NORTH:
4140         case OB_DIRECTION_SOUTH:
4141             edge_start = area.x;
4142             edge_size = area.width;
4143             break;
4144         case OB_DIRECTION_EAST:
4145         case OB_DIRECTION_WEST:
4146             edge_start = area.y;
4147             edge_size = area.height;
4148             break;
4149         default:
4150             g_assert_not_reached();
4151     }
4152
4153     /* do we collide with this window? */
4154     if (!RANGES_INTERSECT(my_edge_start, my_edge_size,
4155                 edge_start, edge_size))
4156         return;
4157
4158     switch (dir) {
4159         case OB_DIRECTION_NORTH:
4160             head = RECT_BOTTOM(area);
4161             tail = RECT_TOP(area);
4162             break;
4163         case OB_DIRECTION_SOUTH:
4164             head = RECT_TOP(area);
4165             tail = RECT_BOTTOM(area);
4166             break;
4167         case OB_DIRECTION_WEST:
4168             head = RECT_RIGHT(area);
4169             tail = RECT_LEFT(area);
4170             break;
4171         case OB_DIRECTION_EAST:
4172             head = RECT_LEFT(area);
4173             tail = RECT_RIGHT(area);
4174             break;
4175         default:
4176             g_assert_not_reached();
4177     }
4178     switch (dir) {
4179         case OB_DIRECTION_NORTH:
4180         case OB_DIRECTION_WEST:
4181             /* check if our window is past the head of this window */
4182             if (my_head <= head + 1)
4183                 skip_head = TRUE;
4184             /* check if our window's tail is past the tail of this window */
4185             if (my_head + my_size - 1 <= tail)
4186                 skip_tail = TRUE;
4187             /* check if the head of this window is closer than the previously
4188                chosen edge (take into account that the previously chosen
4189                edge might have been a tail, not a head) */
4190             if (head + (*near_edge ? 0 : my_size) <= *dest)
4191                 skip_head = TRUE;
4192             /* check if the tail of this window is closer than the previously
4193                chosen edge (take into account that the previously chosen
4194                edge might have been a head, not a tail) */
4195             if (tail - (!*near_edge ? 0 : my_size) <= *dest)
4196                 skip_tail = TRUE;
4197             break;
4198         case OB_DIRECTION_SOUTH:
4199         case OB_DIRECTION_EAST:
4200             /* check if our window is past the head of this window */
4201             if (my_head >= head - 1)
4202                 skip_head = TRUE;
4203             /* check if our window's tail is past the tail of this window */
4204             if (my_head - my_size + 1 >= tail)
4205                 skip_tail = TRUE;
4206             /* check if the head of this window is closer than the previously
4207                chosen edge (take into account that the previously chosen
4208                edge might have been a tail, not a head) */
4209             if (head - (*near_edge ? 0 : my_size) >= *dest)
4210                 skip_head = TRUE;
4211             /* check if the tail of this window is closer than the previously
4212                chosen edge (take into account that the previously chosen
4213                edge might have been a head, not a tail) */
4214             if (tail + (!*near_edge ? 0 : my_size) >= *dest)
4215                 skip_tail = TRUE;
4216             break;
4217         default:
4218             g_assert_not_reached();
4219     }
4220
4221     ob_debug("my head %d size %d", my_head, my_size);
4222     ob_debug("head %d tail %d dest %d", head, tail, *dest);
4223     if (!skip_head) {
4224         ob_debug("using near edge %d", head);
4225         *dest = head;
4226         *near_edge = TRUE;
4227     }
4228     else if (!skip_tail) {
4229         ob_debug("using far edge %d", tail);
4230         *dest = tail;
4231         *near_edge = FALSE;
4232     }
4233 }
4234
4235 void client_find_edge_directional(ObClient *self, ObDirection dir,
4236                                   gint my_head, gint my_size,
4237                                   gint my_edge_start, gint my_edge_size,
4238                                   gint *dest, gboolean *near_edge)
4239 {
4240     GList *it;
4241     Rect *a;
4242     Rect dock_area;
4243     gint edge;
4244     guint i;
4245
4246     a = screen_area(self->desktop, SCREEN_AREA_ALL_MONITORS,
4247                     &self->frame->area);
4248
4249     switch (dir) {
4250     case OB_DIRECTION_NORTH:
4251         edge = RECT_TOP(*a) - 1;
4252         break;
4253     case OB_DIRECTION_SOUTH:
4254         edge = RECT_BOTTOM(*a) + 1;
4255         break;
4256     case OB_DIRECTION_EAST:
4257         edge = RECT_RIGHT(*a) + 1;
4258         break;
4259     case OB_DIRECTION_WEST:
4260         edge = RECT_LEFT(*a) - 1;
4261         break;
4262     default:
4263         g_assert_not_reached();
4264     }
4265     /* default to the far edge, then narrow it down */
4266     *dest = edge;
4267     *near_edge = TRUE;
4268
4269     /* search for edges of monitors */
4270     for (i = 0; i < screen_num_monitors; ++i) {
4271         Rect *area = screen_area(self->desktop, i, NULL);
4272         detect_edge(*area, dir, my_head, my_size, my_edge_start,
4273                     my_edge_size, dest, near_edge);
4274         g_slice_free(Rect, area);
4275     }
4276
4277     /* search for edges of clients */
4278     if (((dir == OB_DIRECTION_NORTH || dir == OB_DIRECTION_SOUTH) &&
4279          !self->max_vert) ||
4280         ((dir == OB_DIRECTION_EAST || dir == OB_DIRECTION_WEST) &&
4281          !self->max_horz))
4282     {
4283         for (it = client_list; it; it = g_list_next(it)) {
4284             ObClient *cur = it->data;
4285
4286             /* skip windows to not bump into */
4287             if (cur == self)
4288                 continue;
4289             if (cur->iconic)
4290                 continue;
4291             if (self->desktop != cur->desktop && cur->desktop != DESKTOP_ALL &&
4292                 cur->desktop != screen_desktop)
4293                 continue;
4294
4295             ob_debug("trying window %s", cur->title);
4296
4297             detect_edge(cur->frame->area, dir, my_head, my_size, my_edge_start,
4298                         my_edge_size, dest, near_edge);
4299         }
4300         dock_get_area(&dock_area);
4301         detect_edge(dock_area, dir, my_head, my_size, my_edge_start,
4302                     my_edge_size, dest, near_edge);
4303     }
4304
4305     g_slice_free(Rect, a);
4306 }
4307
4308 void client_find_move_directional(ObClient *self, ObDirection dir,
4309                                   gint *x, gint *y)
4310 {
4311     gint head, size;
4312     gint e, e_start, e_size;
4313     gboolean near;
4314
4315     switch (dir) {
4316     case OB_DIRECTION_EAST:
4317         head = RECT_RIGHT(self->frame->area);
4318         size = self->frame->area.width;
4319         e_start = RECT_TOP(self->frame->area);
4320         e_size = self->frame->area.height;
4321         break;
4322     case OB_DIRECTION_WEST:
4323         head = RECT_LEFT(self->frame->area);
4324         size = self->frame->area.width;
4325         e_start = RECT_TOP(self->frame->area);
4326         e_size = self->frame->area.height;
4327         break;
4328     case OB_DIRECTION_NORTH:
4329         head = RECT_TOP(self->frame->area);
4330         size = self->frame->area.height;
4331         e_start = RECT_LEFT(self->frame->area);
4332         e_size = self->frame->area.width;
4333         break;
4334     case OB_DIRECTION_SOUTH:
4335         head = RECT_BOTTOM(self->frame->area);
4336         size = self->frame->area.height;
4337         e_start = RECT_LEFT(self->frame->area);
4338         e_size = self->frame->area.width;
4339         break;
4340     default:
4341         g_assert_not_reached();
4342     }
4343
4344     client_find_edge_directional(self, dir, head, size,
4345                                  e_start, e_size, &e, &near);
4346     *x = self->frame->area.x;
4347     *y = self->frame->area.y;
4348     switch (dir) {
4349     case OB_DIRECTION_EAST:
4350         if (near) e -= self->frame->area.width;
4351         else      e++;
4352         *x = e;
4353         break;
4354     case OB_DIRECTION_WEST:
4355         if (near) e++;
4356         else      e -= self->frame->area.width;
4357         *x = e;
4358         break;
4359     case OB_DIRECTION_NORTH:
4360         if (near) e++;
4361         else      e -= self->frame->area.height;
4362         *y = e;
4363         break;
4364     case OB_DIRECTION_SOUTH:
4365         if (near) e -= self->frame->area.height;
4366         else      e++;
4367         *y = e;
4368         break;
4369     default:
4370         g_assert_not_reached();
4371     }
4372     frame_frame_gravity(self->frame, x, y);
4373 }
4374
4375 void client_find_resize_directional(ObClient *self, ObDirection side,
4376                                     gboolean grow,
4377                                     gint *x, gint *y, gint *w, gint *h)
4378 {
4379     gint head;
4380     gint e, e_start, e_size, delta;
4381     gboolean near;
4382     ObDirection dir;
4383
4384     switch (side) {
4385     case OB_DIRECTION_EAST:
4386         head = RECT_RIGHT(self->frame->area) +
4387             (self->size_inc.width - 1) * (grow ? 1 : 0);
4388         e_start = RECT_TOP(self->frame->area);
4389         e_size = self->frame->area.height;
4390         dir = grow ? OB_DIRECTION_EAST : OB_DIRECTION_WEST;
4391         break;
4392     case OB_DIRECTION_WEST:
4393         head = RECT_LEFT(self->frame->area) -
4394             (self->size_inc.width - 1) * (grow ? 1 : 0);
4395         e_start = RECT_TOP(self->frame->area);
4396         e_size = self->frame->area.height;
4397         dir = grow ? OB_DIRECTION_WEST : OB_DIRECTION_EAST;
4398         break;
4399     case OB_DIRECTION_NORTH:
4400         head = RECT_TOP(self->frame->area) -
4401             (self->size_inc.height - 1) * (grow ? 1 : 0);
4402         e_start = RECT_LEFT(self->frame->area);
4403         e_size = self->frame->area.width;
4404         dir = grow ? OB_DIRECTION_NORTH : OB_DIRECTION_SOUTH;
4405         break;
4406     case OB_DIRECTION_SOUTH:
4407         head = RECT_BOTTOM(self->frame->area) +
4408             (self->size_inc.height - 1) * (grow ? 1 : 0);
4409         e_start = RECT_LEFT(self->frame->area);
4410         e_size = self->frame->area.width;
4411         dir = grow ? OB_DIRECTION_SOUTH : OB_DIRECTION_NORTH;
4412         break;
4413     default:
4414         g_assert_not_reached();
4415     }
4416
4417     ob_debug("head %d dir %d", head, dir);
4418     client_find_edge_directional(self, dir, head, 1,
4419                                  e_start, e_size, &e, &near);
4420     ob_debug("edge %d", e);
4421     *x = self->frame->area.x;
4422     *y = self->frame->area.y;
4423     *w = self->frame->area.width;
4424     *h = self->frame->area.height;
4425     switch (side) {
4426     case OB_DIRECTION_EAST:
4427         if (grow == near) --e;
4428         delta = e - RECT_RIGHT(self->frame->area);
4429         *w += delta;
4430         break;
4431     case OB_DIRECTION_WEST:
4432         if (grow == near) ++e;
4433         delta = RECT_LEFT(self->frame->area) - e;
4434         *x -= delta;
4435         *w += delta;
4436         break;
4437     case OB_DIRECTION_NORTH:
4438         if (grow == near) ++e;
4439         delta = RECT_TOP(self->frame->area) - e;
4440         *y -= delta;
4441         *h += delta;
4442         break;
4443     case OB_DIRECTION_SOUTH:
4444         if (grow == near) --e;
4445         delta = e - RECT_BOTTOM(self->frame->area);
4446         *h += delta;
4447         break;
4448     default:
4449         g_assert_not_reached();
4450     }
4451     frame_frame_gravity(self->frame, x, y);
4452     *w -= self->frame->size.left + self->frame->size.right;
4453     *h -= self->frame->size.top + self->frame->size.bottom;
4454 }
4455
4456 ObClient* client_under_pointer(void)
4457 {
4458     gint x, y;
4459     GList *it;
4460     ObClient *ret = NULL;
4461
4462     if (screen_pointer_pos(&x, &y)) {
4463         for (it = stacking_list; it; it = g_list_next(it)) {
4464             if (WINDOW_IS_CLIENT(it->data)) {
4465                 ObClient *c = WINDOW_AS_CLIENT(it->data);
4466                 if (c->frame->visible &&
4467                     /* check the desktop, this is done during desktop
4468                        switching and windows are shown/hidden status is not
4469                        reliable */
4470                     (c->desktop == screen_desktop ||
4471                      c->desktop == DESKTOP_ALL) &&
4472                     /* ignore all animating windows */
4473                     !frame_iconify_animating(c->frame) &&
4474                     RECT_CONTAINS(c->frame->area, x, y))
4475                 {
4476                     ret = c;
4477                     break;
4478                 }
4479             }
4480         }
4481     }
4482     return ret;
4483 }
4484
4485 gboolean client_has_group_siblings(ObClient *self)
4486 {
4487     return self->group && self->group->members->next;
4488 }
4489
4490 /*! Returns TRUE if the client is running on the same machine as Openbox */
4491 gboolean client_on_localhost(ObClient *self)
4492 {
4493     return self->client_machine == NULL;
4494 }