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