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