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