make focus cycle target fallback work right by going to the next prev window
[dana/openbox.git] / openbox / client.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2
3    client.c for the Openbox window manager
4    Copyright (c) 2006        Mikael Magnusson
5    Copyright (c) 2003-2007   Dana Jansens
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    See the COPYING file for a copy of the GNU General Public License.
18 */
19
20 #include "client.h"
21 #include "debug.h"
22 #include "startupnotify.h"
23 #include "dock.h"
24 #include "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 new 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 OBT_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         /* if the window is maximized, its area isn't all that meaningful.
3198            save its premax area instead. */
3199         if (self->max_horz) {
3200             self->pre_fullscreen_area.x = self->pre_max_area.x;
3201             self->pre_fullscreen_area.width = self->pre_max_area.width;
3202         }
3203         if (self->max_vert) {
3204             self->pre_fullscreen_area.y = self->pre_max_area.y;
3205             self->pre_fullscreen_area.height = self->pre_max_area.height;
3206         }
3207
3208         /* these will help configure_full figure out where to fullscreen
3209            the window */
3210         x = self->area.x;
3211         y = self->area.y;
3212         w = self->area.width;
3213         h = self->area.height;
3214     } else {
3215         g_assert(self->pre_fullscreen_area.width > 0 &&
3216                  self->pre_fullscreen_area.height > 0);
3217
3218         x = self->pre_fullscreen_area.x;
3219         y = self->pre_fullscreen_area.y;
3220         w = self->pre_fullscreen_area.width;
3221         h = self->pre_fullscreen_area.height;
3222         RECT_SET(self->pre_fullscreen_area, 0, 0, 0, 0);
3223     }
3224
3225     ob_debug("Window %s going fullscreen (%d)\n",
3226              self->title, self->fullscreen);
3227
3228     client_setup_decor_and_functions(self, FALSE);
3229     client_move_resize(self, x, y, w, h);
3230
3231     /* and adjust our layer/stacking. do this after resizing the window,
3232        and applying decorations, because windows which fill the screen are
3233        considered "fullscreen" and it affects their layer */
3234     client_calc_layer(self);
3235
3236     if (fs) {
3237         /* try focus us when we go into fullscreen mode */
3238         client_focus(self);
3239     }
3240 }
3241
3242 static void client_iconify_recursive(ObClient *self,
3243                                      gboolean iconic, gboolean curdesk,
3244                                      gboolean hide_animation)
3245 {
3246     GSList *it;
3247     gboolean changed = FALSE;
3248
3249     if (self->iconic != iconic) {
3250         ob_debug("%sconifying window: 0x%lx\n", (iconic ? "I" : "Uni"),
3251                  self->window);
3252
3253         if (iconic) {
3254             /* don't let non-normal windows iconify along with their parents
3255                or whatever */
3256             if (client_normal(self)) {
3257                 self->iconic = iconic;
3258
3259                 /* update the focus lists.. iconic windows go to the bottom of
3260                    the list. this will also call focus_cycle_addremove(). */
3261                 focus_order_to_bottom(self);
3262
3263                 changed = TRUE;
3264             }
3265         } else {
3266             self->iconic = iconic;
3267
3268             if (curdesk && self->desktop != screen_desktop &&
3269                 self->desktop != DESKTOP_ALL)
3270                 client_set_desktop(self, screen_desktop, FALSE, FALSE);
3271
3272             /* this puts it after the current focused window, this will
3273                also cause focus_cycle_addremove() to be called for the
3274                client */
3275             focus_order_like_new(self);
3276
3277             changed = TRUE;
3278         }
3279     }
3280
3281     if (changed) {
3282         client_change_state(self);
3283         if (config_animate_iconify && !hide_animation)
3284             frame_begin_iconify_animation(self->frame, iconic);
3285         /* do this after starting the animation so it doesn't flash */
3286         client_showhide(self);
3287     }
3288
3289     /* iconify all direct transients, and deiconify all transients
3290        (non-direct too) */
3291     for (it = self->transients; it; it = g_slist_next(it))
3292         if (it->data != self)
3293             if (client_is_direct_child(self, it->data) || !iconic)
3294                 client_iconify_recursive(it->data, iconic, curdesk,
3295                                          hide_animation);
3296 }
3297
3298 void client_iconify(ObClient *self, gboolean iconic, gboolean curdesk,
3299                     gboolean hide_animation)
3300 {
3301     if (self->functions & OB_CLIENT_FUNC_ICONIFY || !iconic) {
3302         /* move up the transient chain as far as possible first */
3303         self = client_search_top_direct_parent(self);
3304         client_iconify_recursive(self, iconic, curdesk, hide_animation);
3305     }
3306 }
3307
3308 void client_maximize(ObClient *self, gboolean max, gint dir)
3309 {
3310     gint x, y, w, h;
3311
3312     g_assert(dir == 0 || dir == 1 || dir == 2);
3313     if (!(self->functions & OB_CLIENT_FUNC_MAXIMIZE) && max) return;/* can't */
3314
3315     /* check if already done */
3316     if (max) {
3317         if (dir == 0 && self->max_horz && self->max_vert) return;
3318         if (dir == 1 && self->max_horz) return;
3319         if (dir == 2 && self->max_vert) return;
3320     } else {
3321         if (dir == 0 && !self->max_horz && !self->max_vert) return;
3322         if (dir == 1 && !self->max_horz) return;
3323         if (dir == 2 && !self->max_vert) return;
3324     }
3325
3326     /* these will help configure_full figure out which screen to fill with
3327        the window */
3328     x = self->area.x;
3329     y = self->area.y;
3330     w = self->area.width;
3331     h = self->area.height;
3332
3333     if (max) {
3334         if ((dir == 0 || dir == 1) && !self->max_horz) { /* horz */
3335             RECT_SET(self->pre_max_area,
3336                      self->area.x, self->pre_max_area.y,
3337                      self->area.width, self->pre_max_area.height);
3338         }
3339         if ((dir == 0 || dir == 2) && !self->max_vert) { /* vert */
3340             RECT_SET(self->pre_max_area,
3341                      self->pre_max_area.x, self->area.y,
3342                      self->pre_max_area.width, self->area.height);
3343         }
3344     } else {
3345         if ((dir == 0 || dir == 1) && self->max_horz) { /* horz */
3346             g_assert(self->pre_max_area.width > 0);
3347
3348             x = self->pre_max_area.x;
3349             w = self->pre_max_area.width;
3350
3351             RECT_SET(self->pre_max_area, 0, self->pre_max_area.y,
3352                      0, self->pre_max_area.height);
3353         }
3354         if ((dir == 0 || dir == 2) && self->max_vert) { /* vert */
3355             g_assert(self->pre_max_area.height > 0);
3356
3357             y = self->pre_max_area.y;
3358             h = self->pre_max_area.height;
3359
3360             RECT_SET(self->pre_max_area, self->pre_max_area.x, 0,
3361                      self->pre_max_area.width, 0);
3362         }
3363     }
3364
3365     if (dir == 0 || dir == 1) /* horz */
3366         self->max_horz = max;
3367     if (dir == 0 || dir == 2) /* vert */
3368         self->max_vert = max;
3369
3370     client_change_state(self); /* change the state hints on the client */
3371
3372     client_setup_decor_and_functions(self, FALSE);
3373     client_move_resize(self, x, y, w, h);
3374 }
3375
3376 void client_shade(ObClient *self, gboolean shade)
3377 {
3378     if ((!(self->functions & OB_CLIENT_FUNC_SHADE) &&
3379          shade) ||                         /* can't shade */
3380         self->shaded == shade) return;     /* already done */
3381
3382     self->shaded = shade;
3383     client_change_state(self);
3384     client_change_wm_state(self); /* the window is being hidden/shown */
3385     /* resize the frame to just the titlebar */
3386     frame_adjust_area(self->frame, FALSE, TRUE, FALSE);
3387 }
3388
3389 static void client_ping_event(ObClient *self, gboolean dead)
3390 {
3391     if (self->not_responding != dead) {
3392         self->not_responding = dead;
3393         client_update_title(self);
3394
3395         if (dead)
3396             /* the client isn't responding, so ask to kill it */
3397             client_prompt_kill(self);
3398         else {
3399             /* it came back to life ! */
3400
3401             if (self->kill_prompt) {
3402                 prompt_unref(self->kill_prompt);
3403                 self->kill_prompt = NULL;
3404             }
3405
3406             self->kill_level = 0;
3407         }
3408     }
3409 }
3410
3411 void client_close(ObClient *self)
3412 {
3413     if (!(self->functions & OB_CLIENT_FUNC_CLOSE)) return;
3414
3415     /* if closing an internal obprompt, that is just cancelling it */
3416     if (self->prompt) {
3417         prompt_cancel(self->prompt);
3418         return;
3419     }
3420
3421     /* in the case that the client provides no means to requesting that it
3422        close, we just kill it */
3423     if (!self->delete_window)
3424         /* don't use client_kill(), we should only kill based on PID in
3425            response to a lack of PING replies */
3426         XKillClient(ob_display, self->window);
3427     else {
3428         /* request the client to close with WM_DELETE_WINDOW */
3429         PROP_MSG_TO(self->window, self->window, wm_protocols,
3430                     prop_atoms.wm_delete_window, event_curtime, 0, 0, 0,
3431                     NoEventMask);
3432
3433         /* we're trying to close the window, so see if it is responding. if it
3434            is not, then we will let them kill the window */
3435         if (self->ping)
3436             ping_start(self, client_ping_event);
3437
3438         /* if we already know the window isn't responding (maybe they clicked
3439            no in the kill dialog but it hasn't come back to life), then show
3440            the kill dialog */
3441         if (self->not_responding)
3442             client_prompt_kill(self);
3443     }
3444 }
3445
3446 #define OB_KILL_RESULT_NO 0
3447 #define OB_KILL_RESULT_YES 1
3448
3449 static gboolean client_kill_requested(ObPrompt *p, gint result, gpointer data)
3450 {
3451     ObClient *self = data;
3452
3453     if (result == OB_KILL_RESULT_YES)
3454         client_kill(self);
3455     return TRUE; /* call the cleanup func */
3456 }
3457
3458 static void client_kill_cleanup(ObPrompt *p, gpointer data)
3459 {
3460     ObClient *self = data;
3461
3462     g_assert(p == self->kill_prompt);
3463
3464     prompt_unref(self->kill_prompt);
3465     self->kill_prompt = NULL;
3466 }
3467
3468 static void client_prompt_kill(ObClient *self)
3469 {
3470     /* check if we're already prompting */
3471     if (!self->kill_prompt) {
3472         ObPromptAnswer answers[] = {
3473             { 0, OB_KILL_RESULT_NO },
3474             { 0, OB_KILL_RESULT_YES }
3475         };
3476         gchar *m;
3477         const gchar *y, *title;
3478
3479         title = self->original_title;
3480         if (title[0] == '\0') {
3481             /* empty string, so use its parent */
3482             ObClient *p = client_search_top_direct_parent(self);
3483             if (p) title = p->original_title;
3484         }
3485
3486         if (client_on_localhost(self)) {
3487             const gchar *sig;
3488
3489             if (self->kill_level == 0)
3490                 sig = "terminate";
3491             else
3492                 sig = "kill";
3493
3494             m = g_strdup_printf
3495                 (_("The window \"%s\" does not seem to be responding.  Do you want to force it to exit by sending the %s signal?"),
3496                  title, sig);
3497             y = _("End Process");
3498         }
3499         else {
3500             m = g_strdup_printf
3501                 (_("The window \"%s\" does not seem to be responding.  Do you want to disconnect it from the X server?"),
3502                  title);
3503             y = _("Disconnect");
3504         }
3505         /* set the dialog buttons' text */
3506         answers[0].text = _("Cancel");  /* "no" */
3507         answers[1].text = y;            /* "yes" */
3508
3509         self->kill_prompt = prompt_new(m, NULL, answers,
3510                                        sizeof(answers)/sizeof(answers[0]),
3511                                        OB_KILL_RESULT_NO, /* default = no */
3512                                        OB_KILL_RESULT_NO, /* cancel = no */
3513                                        client_kill_requested,
3514                                        client_kill_cleanup,
3515                                        self);
3516         g_free(m);
3517     }
3518
3519     prompt_show(self->kill_prompt, self, TRUE);
3520 }
3521
3522 void client_kill(ObClient *self)
3523 {
3524     /* don't kill our own windows */
3525     if (self->prompt) return;
3526
3527     if (client_on_localhost(self) && self->pid) {
3528         /* running on the local host */
3529         if (self->kill_level == 0) {
3530             ob_debug("killing window 0x%x with pid %lu, with SIGTERM",
3531                      self->window, self->pid);
3532             kill(self->pid, SIGTERM);
3533             ++self->kill_level;
3534
3535             /* show that we're trying to kill it */
3536             client_update_title(self);
3537         }
3538         else {
3539             ob_debug("killing window 0x%x with pid %lu, with SIGKILL\n",
3540                      self->window, self->pid);
3541             kill(self->pid, SIGKILL); /* kill -9 */
3542         }
3543     }
3544     else {
3545         /* running on a remote host */
3546         XKillClient(ob_display, self->window);
3547     }
3548 }
3549
3550 void client_hilite(ObClient *self, gboolean hilite)
3551 {
3552     if (self->demands_attention == hilite)
3553         return; /* no change */
3554
3555     /* don't allow focused windows to hilite */
3556     self->demands_attention = hilite && !client_focused(self);
3557     if (self->frame != NULL) { /* if we're mapping, just set the state */
3558         if (self->demands_attention) {
3559             frame_flash_start(self->frame);
3560
3561             /* if the window is on another desktop then raise it and make it
3562                the most recently used window */
3563             if (self->desktop != screen_desktop &&
3564                 self->desktop != DESKTOP_ALL)
3565             {
3566                 stacking_raise(CLIENT_AS_WINDOW(self));
3567                 focus_order_to_top(self);
3568             }
3569         }
3570         else
3571             frame_flash_stop(self->frame);
3572         client_change_state(self);
3573     }
3574 }
3575
3576 static void client_set_desktop_recursive(ObClient *self,
3577                                          guint target,
3578                                          gboolean donthide,
3579                                          gboolean dontraise)
3580 {
3581     guint old;
3582     GSList *it;
3583
3584     if (target != self->desktop && self->type != OB_CLIENT_TYPE_DESKTOP) {
3585
3586         ob_debug("Setting desktop %u\n", target+1);
3587
3588         g_assert(target < screen_num_desktops || target == DESKTOP_ALL);
3589
3590         old = self->desktop;
3591         self->desktop = target;
3592         PROP_SET32(self->window, net_wm_desktop, cardinal, target);
3593         /* the frame can display the current desktop state */
3594         frame_adjust_state(self->frame);
3595         /* 'move' the window to the new desktop */
3596         if (!donthide)
3597             client_hide(self);
3598         client_show(self);
3599         /* raise if it was not already on the desktop */
3600         if (old != DESKTOP_ALL && !dontraise)
3601             stacking_raise(CLIENT_AS_WINDOW(self));
3602         if (STRUT_EXISTS(self->strut))
3603             screen_update_areas();
3604         else
3605             /* the new desktop's geometry may be different, so we may need to
3606                resize, for example if we are maximized */
3607             client_reconfigure(self, FALSE);
3608
3609         focus_cycle_addremove(self, FALSE);
3610     }
3611
3612     /* move all transients */
3613     for (it = self->transients; it; it = g_slist_next(it))
3614         if (it->data != self)
3615             if (client_is_direct_child(self, it->data))
3616                 client_set_desktop_recursive(it->data, target,
3617                                              donthide, dontraise);
3618 }
3619
3620 void client_set_desktop(ObClient *self, guint target,
3621                         gboolean donthide, gboolean dontraise)
3622 {
3623     self = client_search_top_direct_parent(self);
3624     client_set_desktop_recursive(self, target, donthide, dontraise);
3625
3626     focus_cycle_addremove(NULL, TRUE);
3627 }
3628
3629 gboolean client_is_direct_child(ObClient *parent, ObClient *child)
3630 {
3631     while (child != parent && (child = client_direct_parent(child)));
3632     return child == parent;
3633 }
3634
3635 ObClient *client_search_modal_child(ObClient *self)
3636 {
3637     GSList *it;
3638     ObClient *ret;
3639
3640     for (it = self->transients; it; it = g_slist_next(it)) {
3641         ObClient *c = it->data;
3642         if ((ret = client_search_modal_child(c))) return ret;
3643         if (c->modal) return c;
3644     }
3645     return NULL;
3646 }
3647
3648 static gboolean client_validate_unmap(ObClient *self, int n)
3649 {
3650     XEvent e;
3651     gboolean ret = TRUE;
3652
3653     if (XCheckTypedWindowEvent(ob_display, self->window, UnmapNotify, &e)) {
3654         if (n < self->ignore_unmaps) // ignore this one, but look for more
3655             ret = client_validate_unmap(self, n+1);
3656         else
3657             ret = FALSE; // the window is going to become unmanaged
3658
3659         /* put them back on the event stack so they end up in the same order */
3660         XPutBackEvent(ob_display, &e);
3661     }
3662
3663     return ret;
3664 }
3665
3666 gboolean client_validate(ObClient *self)
3667 {
3668     XEvent e;
3669
3670     XSync(ob_display, FALSE); /* get all events on the server */
3671
3672     if (XCheckTypedWindowEvent(ob_display, self->window, DestroyNotify, &e)) {
3673         XPutBackEvent(ob_display, &e);
3674         return FALSE;
3675     }
3676
3677     if (!client_validate_unmap(self, 0))
3678         return FALSE;
3679
3680     return TRUE;
3681 }
3682
3683 void client_set_wm_state(ObClient *self, glong state)
3684 {
3685     if (state == self->wmstate) return; /* no change */
3686
3687     switch (state) {
3688     case IconicState:
3689         client_iconify(self, TRUE, TRUE, FALSE);
3690         break;
3691     case NormalState:
3692         client_iconify(self, FALSE, TRUE, FALSE);
3693         break;
3694     }
3695 }
3696
3697 void client_set_state(ObClient *self, Atom action, glong data1, glong data2)
3698 {
3699     gboolean shaded = self->shaded;
3700     gboolean fullscreen = self->fullscreen;
3701     gboolean undecorated = self->undecorated;
3702     gboolean max_horz = self->max_horz;
3703     gboolean max_vert = self->max_vert;
3704     gboolean modal = self->modal;
3705     gboolean iconic = self->iconic;
3706     gboolean demands_attention = self->demands_attention;
3707     gboolean above = self->above;
3708     gboolean below = self->below;
3709     gint i;
3710
3711     if (!(action == prop_atoms.net_wm_state_add ||
3712           action == prop_atoms.net_wm_state_remove ||
3713           action == prop_atoms.net_wm_state_toggle))
3714         /* an invalid action was passed to the client message, ignore it */
3715         return;
3716
3717     for (i = 0; i < 2; ++i) {
3718         Atom state = i == 0 ? data1 : data2;
3719
3720         if (!state) continue;
3721
3722         /* if toggling, then pick whether we're adding or removing */
3723         if (action == prop_atoms.net_wm_state_toggle) {
3724             if (state == prop_atoms.net_wm_state_modal)
3725                 action = modal ? prop_atoms.net_wm_state_remove :
3726                     prop_atoms.net_wm_state_add;
3727             else if (state == prop_atoms.net_wm_state_maximized_vert)
3728                 action = self->max_vert ? prop_atoms.net_wm_state_remove :
3729                     prop_atoms.net_wm_state_add;
3730             else if (state == prop_atoms.net_wm_state_maximized_horz)
3731                 action = self->max_horz ? prop_atoms.net_wm_state_remove :
3732                     prop_atoms.net_wm_state_add;
3733             else if (state == prop_atoms.net_wm_state_shaded)
3734                 action = shaded ? prop_atoms.net_wm_state_remove :
3735                     prop_atoms.net_wm_state_add;
3736             else if (state == prop_atoms.net_wm_state_skip_taskbar)
3737                 action = self->skip_taskbar ?
3738                     prop_atoms.net_wm_state_remove :
3739                     prop_atoms.net_wm_state_add;
3740             else if (state == prop_atoms.net_wm_state_skip_pager)
3741                 action = self->skip_pager ?
3742                     prop_atoms.net_wm_state_remove :
3743                     prop_atoms.net_wm_state_add;
3744             else if (state == prop_atoms.net_wm_state_hidden)
3745                 action = self->iconic ?
3746                     prop_atoms.net_wm_state_remove :
3747                     prop_atoms.net_wm_state_add;
3748             else if (state == prop_atoms.net_wm_state_fullscreen)
3749                 action = fullscreen ?
3750                     prop_atoms.net_wm_state_remove :
3751                     prop_atoms.net_wm_state_add;
3752             else if (state == prop_atoms.net_wm_state_above)
3753                 action = self->above ? prop_atoms.net_wm_state_remove :
3754                     prop_atoms.net_wm_state_add;
3755             else if (state == prop_atoms.net_wm_state_below)
3756                 action = self->below ? prop_atoms.net_wm_state_remove :
3757                     prop_atoms.net_wm_state_add;
3758             else if (state == prop_atoms.net_wm_state_demands_attention)
3759                 action = self->demands_attention ?
3760                     prop_atoms.net_wm_state_remove :
3761                     prop_atoms.net_wm_state_add;
3762             else if (state == prop_atoms.ob_wm_state_undecorated)
3763                 action = undecorated ? prop_atoms.net_wm_state_remove :
3764                     prop_atoms.net_wm_state_add;
3765         }
3766
3767         if (action == prop_atoms.net_wm_state_add) {
3768             if (state == prop_atoms.net_wm_state_modal) {
3769                 modal = TRUE;
3770             } else if (state == prop_atoms.net_wm_state_maximized_vert) {
3771                 max_vert = TRUE;
3772             } else if (state == prop_atoms.net_wm_state_maximized_horz) {
3773                 max_horz = TRUE;
3774             } else if (state == prop_atoms.net_wm_state_shaded) {
3775                 shaded = TRUE;
3776             } else if (state == prop_atoms.net_wm_state_skip_taskbar) {
3777                 self->skip_taskbar = TRUE;
3778             } else if (state == prop_atoms.net_wm_state_skip_pager) {
3779                 self->skip_pager = TRUE;
3780             } else if (state == prop_atoms.net_wm_state_hidden) {
3781                 iconic = TRUE;
3782             } else if (state == prop_atoms.net_wm_state_fullscreen) {
3783                 fullscreen = TRUE;
3784             } else if (state == prop_atoms.net_wm_state_above) {
3785                 above = TRUE;
3786                 below = FALSE;
3787             } else if (state == prop_atoms.net_wm_state_below) {
3788                 above = FALSE;
3789                 below = TRUE;
3790             } else if (state == prop_atoms.net_wm_state_demands_attention) {
3791                 demands_attention = TRUE;
3792             } else if (state == prop_atoms.ob_wm_state_undecorated) {
3793                 undecorated = TRUE;
3794             }
3795
3796         } else { /* action == prop_atoms.net_wm_state_remove */
3797             if (state == prop_atoms.net_wm_state_modal) {
3798                 modal = FALSE;
3799             } else if (state == prop_atoms.net_wm_state_maximized_vert) {
3800                 max_vert = FALSE;
3801             } else if (state == prop_atoms.net_wm_state_maximized_horz) {
3802                 max_horz = FALSE;
3803             } else if (state == prop_atoms.net_wm_state_shaded) {
3804                 shaded = FALSE;
3805             } else if (state == prop_atoms.net_wm_state_skip_taskbar) {
3806                 self->skip_taskbar = FALSE;
3807             } else if (state == prop_atoms.net_wm_state_skip_pager) {
3808                 self->skip_pager = FALSE;
3809             } else if (state == prop_atoms.net_wm_state_hidden) {
3810                 iconic = FALSE;
3811             } else if (state == prop_atoms.net_wm_state_fullscreen) {
3812                 fullscreen = FALSE;
3813             } else if (state == prop_atoms.net_wm_state_above) {
3814                 above = FALSE;
3815             } else if (state == prop_atoms.net_wm_state_below) {
3816                 below = FALSE;
3817             } else if (state == prop_atoms.net_wm_state_demands_attention) {
3818                 demands_attention = FALSE;
3819             } else if (state == prop_atoms.ob_wm_state_undecorated) {
3820                 undecorated = FALSE;
3821             }
3822         }
3823     }
3824
3825     if (max_horz != self->max_horz || max_vert != self->max_vert) {
3826         if (max_horz != self->max_horz && max_vert != self->max_vert) {
3827             /* toggling both */
3828             if (max_horz == max_vert) { /* both going the same way */
3829                 client_maximize(self, max_horz, 0);
3830             } else {
3831                 client_maximize(self, max_horz, 1);
3832                 client_maximize(self, max_vert, 2);
3833             }
3834         } else {
3835             /* toggling one */
3836             if (max_horz != self->max_horz)
3837                 client_maximize(self, max_horz, 1);
3838             else
3839                 client_maximize(self, max_vert, 2);
3840         }
3841     }
3842     /* change fullscreen state before shading, as it will affect if the window
3843        can shade or not */
3844     if (fullscreen != self->fullscreen)
3845         client_fullscreen(self, fullscreen);
3846     if (shaded != self->shaded)
3847         client_shade(self, shaded);
3848     if (undecorated != self->undecorated)
3849         client_set_undecorated(self, undecorated);
3850     if (above != self->above || below != self->below) {
3851         self->above = above;
3852         self->below = below;
3853         client_calc_layer(self);
3854     }
3855
3856     if (modal != self->modal) {
3857         self->modal = modal;
3858         /* when a window changes modality, then its stacking order with its
3859            transients needs to change */
3860         stacking_raise(CLIENT_AS_WINDOW(self));
3861
3862         /* it also may get focused. if something is focused that shouldn't
3863            be focused anymore, then move the focus */
3864         if (focus_client && client_focus_target(focus_client) != focus_client)
3865             client_focus(focus_client);
3866     }
3867
3868     if (iconic != self->iconic)
3869         client_iconify(self, iconic, FALSE, FALSE);
3870
3871     if (demands_attention != self->demands_attention)
3872         client_hilite(self, demands_attention);
3873
3874     client_change_state(self); /* change the hint to reflect these changes */
3875
3876     focus_cycle_addremove(self, TRUE);
3877 }
3878
3879 ObClient *client_focus_target(ObClient *self)
3880 {
3881     ObClient *child = NULL;
3882
3883     child = client_search_modal_child(self);
3884     if (child) return child;
3885     return self;
3886 }
3887
3888 gboolean client_can_focus(ObClient *self)
3889 {
3890     /* choose the correct target */
3891     self = client_focus_target(self);
3892
3893     if (!self->frame->visible)
3894         return FALSE;
3895
3896     if (!(self->can_focus || self->focus_notify))
3897         return FALSE;
3898
3899     return TRUE;
3900 }
3901
3902 gboolean client_focus(ObClient *self)
3903 {
3904     /* we might not focus this window, so if we have modal children which would
3905        be focused instead, bring them to this desktop */
3906     client_bring_modal_windows(self);
3907
3908     /* choose the correct target */
3909     self = client_focus_target(self);
3910
3911     if (!client_can_focus(self)) {
3912         ob_debug_type(OB_DEBUG_FOCUS,
3913                       "Client %s can't be focused\n", self->title);
3914         return FALSE;
3915     }
3916
3917     ob_debug_type(OB_DEBUG_FOCUS,
3918                   "Focusing client \"%s\" (0x%x) at time %u\n",
3919                   self->title, self->window, event_curtime);
3920
3921     /* if using focus_delay, stop the timer now so that focus doesn't
3922        go moving on us */
3923     event_halt_focus_delay();
3924
3925     xerror_set_ignore(TRUE);
3926     xerror_occured = FALSE;
3927
3928     if (self->can_focus) {
3929         /* This can cause a BadMatch error with CurrentTime, or if an app
3930            passed in a bad time for _NET_WM_ACTIVE_WINDOW. */
3931         XSetInputFocus(ob_display, self->window, RevertToPointerRoot,
3932                        event_curtime);
3933     }
3934
3935     if (self->focus_notify) {
3936         XEvent ce;
3937         ce.xclient.type = ClientMessage;
3938         ce.xclient.message_type = prop_atoms.wm_protocols;
3939         ce.xclient.display = ob_display;
3940         ce.xclient.window = self->window;
3941         ce.xclient.format = 32;
3942         ce.xclient.data.l[0] = prop_atoms.wm_take_focus;
3943         ce.xclient.data.l[1] = event_curtime;
3944         ce.xclient.data.l[2] = 0l;
3945         ce.xclient.data.l[3] = 0l;
3946         ce.xclient.data.l[4] = 0l;
3947         XSendEvent(ob_display, self->window, FALSE, NoEventMask, &ce);
3948     }
3949
3950     xerror_set_ignore(FALSE);
3951
3952     ob_debug_type(OB_DEBUG_FOCUS, "Error focusing? %d\n", xerror_occured);
3953     return !xerror_occured;
3954 }
3955
3956 static void client_present(ObClient *self, gboolean here, gboolean raise,
3957                            gboolean unshade)
3958 {
3959     if (client_normal(self) && screen_showing_desktop)
3960         screen_show_desktop(FALSE, self);
3961     if (self->iconic)
3962         client_iconify(self, FALSE, here, FALSE);
3963     if (self->desktop != DESKTOP_ALL &&
3964         self->desktop != screen_desktop)
3965     {
3966         if (here)
3967             client_set_desktop(self, screen_desktop, FALSE, TRUE);
3968         else
3969             screen_set_desktop(self->desktop, FALSE);
3970     } else if (!self->frame->visible)
3971         /* if its not visible for other reasons, then don't mess
3972            with it */
3973         return;
3974     if (self->shaded && unshade)
3975         client_shade(self, FALSE);
3976     if (raise)
3977         stacking_raise(CLIENT_AS_WINDOW(self));
3978
3979     client_focus(self);
3980 }
3981
3982 /* this function exists to map to the net_active_window message in the ewmh */
3983 void client_activate(ObClient *self, gboolean desktop,
3984                      gboolean here, gboolean raise,
3985                      gboolean unshade, gboolean user)
3986 {
3987     if ((user && (desktop ||
3988                   self->desktop == DESKTOP_ALL ||
3989                   self->desktop == screen_desktop)) ||
3990         client_can_steal_focus(self, event_curtime, CurrentTime))
3991     {
3992         client_present(self, here, raise, unshade);
3993     }
3994     else
3995         client_hilite(self, TRUE);
3996 }
3997
3998 static void client_bring_windows_recursive(ObClient *self,
3999                                            guint desktop,
4000                                            gboolean helpers,
4001                                            gboolean modals,
4002                                            gboolean iconic)
4003 {
4004     GSList *it;
4005
4006     for (it = self->transients; it; it = g_slist_next(it))
4007         client_bring_windows_recursive(it->data, desktop,
4008                                        helpers, modals, iconic);
4009
4010     if (((helpers && client_helper(self)) ||
4011          (modals && self->modal)) &&
4012         ((self->desktop != desktop && self->desktop != DESKTOP_ALL) ||
4013          (iconic && self->iconic)))
4014     {
4015         if (iconic && self->iconic)
4016             client_iconify(self, FALSE, TRUE, FALSE);
4017         else
4018             client_set_desktop(self, desktop, FALSE, FALSE);
4019     }
4020 }
4021
4022 void client_bring_helper_windows(ObClient *self)
4023 {
4024     client_bring_windows_recursive(self, self->desktop, TRUE, FALSE, FALSE);
4025 }
4026
4027 void client_bring_modal_windows(ObClient *self)
4028 {
4029     client_bring_windows_recursive(self, self->desktop, FALSE, TRUE, TRUE);
4030 }
4031
4032 gboolean client_focused(ObClient *self)
4033 {
4034     return self == focus_client;
4035 }
4036
4037 RrImage* client_icon(ObClient *self)
4038 {
4039     RrImage *ret = NULL;
4040
4041     if (self->icon_set)
4042         ret = self->icon_set;
4043     else if (self->parents) {
4044         GSList *it;
4045         for (it = self->parents; it && !ret; it = g_slist_next(it))
4046             ret = client_icon(it->data);
4047     }
4048     if (!ret)
4049         ret = client_default_icon;
4050     return ret;
4051 }
4052
4053 void client_set_layer(ObClient *self, gint layer)
4054 {
4055     if (layer < 0) {
4056         self->below = TRUE;
4057         self->above = FALSE;
4058     } else if (layer == 0) {
4059         self->below = self->above = FALSE;
4060     } else {
4061         self->below = FALSE;
4062         self->above = TRUE;
4063     }
4064     client_calc_layer(self);
4065     client_change_state(self); /* reflect this in the state hints */
4066 }
4067
4068 void client_set_undecorated(ObClient *self, gboolean undecorated)
4069 {
4070     if (self->undecorated != undecorated &&
4071         /* don't let it undecorate if the function is missing, but let
4072            it redecorate */
4073         (self->functions & OB_CLIENT_FUNC_UNDECORATE || !undecorated))
4074     {
4075         self->undecorated = undecorated;
4076         client_setup_decor_and_functions(self, TRUE);
4077         client_change_state(self); /* reflect this in the state hints */
4078     }
4079 }
4080
4081 guint client_monitor(ObClient *self)
4082 {
4083     return screen_find_monitor(&self->frame->area);
4084 }
4085
4086 ObClient *client_direct_parent(ObClient *self)
4087 {
4088     if (!self->parents) return NULL;
4089     if (self->transient_for_group) return NULL;
4090     return self->parents->data;
4091 }
4092
4093 ObClient *client_search_top_direct_parent(ObClient *self)
4094 {
4095     ObClient *p;
4096     while ((p = client_direct_parent(self))) self = p;
4097     return self;
4098 }
4099
4100 static GSList *client_search_all_top_parents_internal(ObClient *self,
4101                                                       gboolean bylayer,
4102                                                       ObStackingLayer layer)
4103 {
4104     GSList *ret;
4105     ObClient *p;
4106
4107     /* move up the direct transient chain as far as possible */
4108     while ((p = client_direct_parent(self)) &&
4109            (!bylayer || p->layer == layer))
4110         self = p;
4111
4112     if (!self->parents)
4113         ret = g_slist_prepend(NULL, self);
4114     else
4115         ret = g_slist_copy(self->parents);
4116
4117     return ret;
4118 }
4119
4120 GSList *client_search_all_top_parents(ObClient *self)
4121 {
4122     return client_search_all_top_parents_internal(self, FALSE, 0);
4123 }
4124
4125 GSList *client_search_all_top_parents_layer(ObClient *self)
4126 {
4127     return client_search_all_top_parents_internal(self, TRUE, self->layer);
4128 }
4129
4130 ObClient *client_search_focus_parent(ObClient *self)
4131 {
4132     GSList *it;
4133
4134     for (it = self->parents; it; it = g_slist_next(it))
4135         if (client_focused(it->data)) return it->data;
4136
4137     return NULL;
4138 }
4139
4140 ObClient *client_search_focus_parent_full(ObClient *self)
4141 {
4142     GSList *it;
4143     ObClient *ret = NULL;
4144
4145     for (it = self->parents; it; it = g_slist_next(it)) {
4146         if (client_focused(it->data))
4147             ret = it->data;
4148         else
4149             ret = client_search_focus_parent_full(it->data);
4150         if (ret) break;
4151     }
4152     return ret;
4153 }
4154
4155 ObClient *client_search_parent(ObClient *self, ObClient *search)
4156 {
4157     GSList *it;
4158
4159     for (it = self->parents; it; it = g_slist_next(it))
4160         if (it->data == search) return search;
4161
4162     return NULL;
4163 }
4164
4165 ObClient *client_search_transient(ObClient *self, ObClient *search)
4166 {
4167     GSList *sit;
4168
4169     for (sit = self->transients; sit; sit = g_slist_next(sit)) {
4170         if (sit->data == search)
4171             return search;
4172         if (client_search_transient(sit->data, search))
4173             return search;
4174     }
4175     return NULL;
4176 }
4177
4178 static void detect_edge(Rect area, ObDirection dir,
4179                         gint my_head, gint my_size,
4180                         gint my_edge_start, gint my_edge_size,
4181                         gint *dest, gboolean *near_edge)
4182 {
4183     gint edge_start, edge_size, head, tail;
4184     gboolean skip_head = FALSE, skip_tail = FALSE;
4185
4186     switch (dir) {
4187         case OB_DIRECTION_NORTH:
4188         case OB_DIRECTION_SOUTH:
4189             edge_start = area.x;
4190             edge_size = area.width;
4191             break;
4192         case OB_DIRECTION_EAST:
4193         case OB_DIRECTION_WEST:
4194             edge_start = area.y;
4195             edge_size = area.height;
4196             break;
4197         default:
4198             g_assert_not_reached();
4199     }
4200
4201     /* do we collide with this window? */
4202     if (!RANGES_INTERSECT(my_edge_start, my_edge_size,
4203                 edge_start, edge_size))
4204         return;
4205
4206     switch (dir) {
4207         case OB_DIRECTION_NORTH:
4208             head = RECT_BOTTOM(area);
4209             tail = RECT_TOP(area);
4210             break;
4211         case OB_DIRECTION_SOUTH:
4212             head = RECT_TOP(area);
4213             tail = RECT_BOTTOM(area);
4214             break;
4215         case OB_DIRECTION_WEST:
4216             head = RECT_RIGHT(area);
4217             tail = RECT_LEFT(area);
4218             break;
4219         case OB_DIRECTION_EAST:
4220             head = RECT_LEFT(area);
4221             tail = RECT_RIGHT(area);
4222             break;
4223         default:
4224             g_assert_not_reached();
4225     }
4226     switch (dir) {
4227         case OB_DIRECTION_NORTH:
4228         case OB_DIRECTION_WEST:
4229             /* check if our window is past the head of this window */
4230             if (my_head <= head + 1)
4231                 skip_head = TRUE;
4232             /* check if our window's tail is past the tail of this window */
4233             if (my_head + my_size - 1 <= tail)
4234                 skip_tail = TRUE;
4235             /* check if the head of this window is closer than the previously
4236                chosen edge (take into account that the previously chosen
4237                edge might have been a tail, not a head) */
4238             if (head + (*near_edge ? 0 : my_size) <= *dest)
4239                 skip_head = TRUE;
4240             /* check if the tail of this window is closer than the previously
4241                chosen edge (take into account that the previously chosen
4242                edge might have been a head, not a tail) */
4243             if (tail - (!*near_edge ? 0 : my_size) <= *dest)
4244                 skip_tail = TRUE;
4245             break;
4246         case OB_DIRECTION_SOUTH:
4247         case OB_DIRECTION_EAST:
4248             /* check if our window is past the head of this window */
4249             if (my_head >= head - 1)
4250                 skip_head = TRUE;
4251             /* check if our window's tail is past the tail of this window */
4252             if (my_head - my_size + 1 >= tail)
4253                 skip_tail = TRUE;
4254             /* check if the head of this window is closer than the previously
4255                chosen edge (take into account that the previously chosen
4256                edge might have been a tail, not a head) */
4257             if (head - (*near_edge ? 0 : my_size) >= *dest)
4258                 skip_head = TRUE;
4259             /* check if the tail of this window is closer than the previously
4260                chosen edge (take into account that the previously chosen
4261                edge might have been a head, not a tail) */
4262             if (tail + (!*near_edge ? 0 : my_size) >= *dest)
4263                 skip_tail = TRUE;
4264             break;
4265         default:
4266             g_assert_not_reached();
4267     }
4268
4269     ob_debug("my head %d size %d\n", my_head, my_size);
4270     ob_debug("head %d tail %d dest %d\n", head, tail, *dest);
4271     if (!skip_head) {
4272         ob_debug("using near edge %d\n", head);
4273         *dest = head;
4274         *near_edge = TRUE;
4275     }
4276     else if (!skip_tail) {
4277         ob_debug("using far edge %d\n", tail);
4278         *dest = tail;
4279         *near_edge = FALSE;
4280     }
4281 }
4282
4283 void client_find_edge_directional(ObClient *self, ObDirection dir,
4284                                   gint my_head, gint my_size,
4285                                   gint my_edge_start, gint my_edge_size,
4286                                   gint *dest, gboolean *near_edge)
4287 {
4288     GList *it;
4289     Rect *a;
4290     Rect dock_area;
4291     gint edge;
4292     guint i;
4293
4294     a = screen_area(self->desktop, SCREEN_AREA_ALL_MONITORS,
4295                     &self->frame->area);
4296
4297     switch (dir) {
4298     case OB_DIRECTION_NORTH:
4299         edge = RECT_TOP(*a) - 1;
4300         break;
4301     case OB_DIRECTION_SOUTH:
4302         edge = RECT_BOTTOM(*a) + 1;
4303         break;
4304     case OB_DIRECTION_EAST:
4305         edge = RECT_RIGHT(*a) + 1;
4306         break;
4307     case OB_DIRECTION_WEST:
4308         edge = RECT_LEFT(*a) - 1;
4309         break;
4310     default:
4311         g_assert_not_reached();
4312     }
4313     /* default to the far edge, then narrow it down */
4314     *dest = edge;
4315     *near_edge = TRUE;
4316
4317     /* search for edges of monitors */
4318     for (i = 0; i < screen_num_monitors; ++i) {
4319         Rect *area = screen_area(self->desktop, i, NULL);
4320         detect_edge(*area, dir, my_head, my_size, my_edge_start,
4321                     my_edge_size, dest, near_edge);
4322         g_free(area);
4323     }
4324
4325     /* search for edges of clients */
4326     for (it = client_list; it; it = g_list_next(it)) {
4327         ObClient *cur = it->data;
4328
4329         /* skip windows to not bump into */
4330         if (cur == self)
4331             continue;
4332         if (cur->iconic)
4333             continue;
4334         if (self->desktop != cur->desktop && cur->desktop != DESKTOP_ALL &&
4335             cur->desktop != screen_desktop)
4336             continue;
4337
4338         ob_debug("trying window %s\n", cur->title);
4339
4340         detect_edge(cur->frame->area, dir, my_head, my_size, my_edge_start,
4341                     my_edge_size, dest, near_edge);
4342     }
4343     dock_get_area(&dock_area);
4344     detect_edge(dock_area, dir, my_head, my_size, my_edge_start,
4345                 my_edge_size, dest, near_edge);
4346     g_free(a);
4347 }
4348
4349 void client_find_move_directional(ObClient *self, ObDirection dir,
4350                                   gint *x, gint *y)
4351 {
4352     gint head, size;
4353     gint e, e_start, e_size;
4354     gboolean near;
4355
4356     switch (dir) {
4357     case OB_DIRECTION_EAST:
4358         head = RECT_RIGHT(self->frame->area);
4359         size = self->frame->area.width;
4360         e_start = RECT_TOP(self->frame->area);
4361         e_size = self->frame->area.height;
4362         break;
4363     case OB_DIRECTION_WEST:
4364         head = RECT_LEFT(self->frame->area);
4365         size = self->frame->area.width;
4366         e_start = RECT_TOP(self->frame->area);
4367         e_size = self->frame->area.height;
4368         break;
4369     case OB_DIRECTION_NORTH:
4370         head = RECT_TOP(self->frame->area);
4371         size = self->frame->area.height;
4372         e_start = RECT_LEFT(self->frame->area);
4373         e_size = self->frame->area.width;
4374         break;
4375     case OB_DIRECTION_SOUTH:
4376         head = RECT_BOTTOM(self->frame->area);
4377         size = self->frame->area.height;
4378         e_start = RECT_LEFT(self->frame->area);
4379         e_size = self->frame->area.width;
4380         break;
4381     default:
4382         g_assert_not_reached();
4383     }
4384
4385     client_find_edge_directional(self, dir, head, size,
4386                                  e_start, e_size, &e, &near);
4387     *x = self->frame->area.x;
4388     *y = self->frame->area.y;
4389     switch (dir) {
4390     case OB_DIRECTION_EAST:
4391         if (near) e -= self->frame->area.width;
4392         else      e++;
4393         *x = e;
4394         break;
4395     case OB_DIRECTION_WEST:
4396         if (near) e++;
4397         else      e -= self->frame->area.width;
4398         *x = e;
4399         break;
4400     case OB_DIRECTION_NORTH:
4401         if (near) e++;
4402         else      e -= self->frame->area.height;
4403         *y = e;
4404         break;
4405     case OB_DIRECTION_SOUTH:
4406         if (near) e -= self->frame->area.height;
4407         else      e++;
4408         *y = e;
4409         break;
4410     default:
4411         g_assert_not_reached();
4412     }
4413     frame_frame_gravity(self->frame, x, y);
4414 }
4415
4416 void client_find_resize_directional(ObClient *self, ObDirection side,
4417                                     gboolean grow,
4418                                     gint *x, gint *y, gint *w, gint *h)
4419 {
4420     gint head;
4421     gint e, e_start, e_size, delta;
4422     gboolean near;
4423     ObDirection dir;
4424
4425     switch (side) {
4426     case OB_DIRECTION_EAST:
4427         head = RECT_RIGHT(self->frame->area) +
4428             (self->size_inc.width - 1) * (grow ? 1 : 0);
4429         e_start = RECT_TOP(self->frame->area);
4430         e_size = self->frame->area.height;
4431         dir = grow ? OB_DIRECTION_EAST : OB_DIRECTION_WEST;
4432         break;
4433     case OB_DIRECTION_WEST:
4434         head = RECT_LEFT(self->frame->area) -
4435             (self->size_inc.width - 1) * (grow ? 1 : 0);
4436         e_start = RECT_TOP(self->frame->area);
4437         e_size = self->frame->area.height;
4438         dir = grow ? OB_DIRECTION_WEST : OB_DIRECTION_EAST;
4439         break;
4440     case OB_DIRECTION_NORTH:
4441         head = RECT_TOP(self->frame->area) -
4442             (self->size_inc.height - 1) * (grow ? 1 : 0);
4443         e_start = RECT_LEFT(self->frame->area);
4444         e_size = self->frame->area.width;
4445         dir = grow ? OB_DIRECTION_NORTH : OB_DIRECTION_SOUTH;
4446         break;
4447     case OB_DIRECTION_SOUTH:
4448         head = RECT_BOTTOM(self->frame->area) +
4449             (self->size_inc.height - 1) * (grow ? 1 : 0);
4450         e_start = RECT_LEFT(self->frame->area);
4451         e_size = self->frame->area.width;
4452         dir = grow ? OB_DIRECTION_SOUTH : OB_DIRECTION_NORTH;
4453         break;
4454     default:
4455         g_assert_not_reached();
4456     }
4457
4458     ob_debug("head %d dir %d\n", head, dir);
4459     client_find_edge_directional(self, dir, head, 1,
4460                                  e_start, e_size, &e, &near);
4461     ob_debug("edge %d\n", e);
4462     *x = self->frame->area.x;
4463     *y = self->frame->area.y;
4464     *w = self->frame->area.width;
4465     *h = self->frame->area.height;
4466     switch (side) {
4467     case OB_DIRECTION_EAST:
4468         if (grow == near) --e;
4469         delta = e - RECT_RIGHT(self->frame->area);
4470         *w += delta;
4471         break;
4472     case OB_DIRECTION_WEST:
4473         if (grow == near) ++e;
4474         delta = RECT_LEFT(self->frame->area) - e;
4475         *x -= delta;
4476         *w += delta;
4477         break;
4478     case OB_DIRECTION_NORTH:
4479         if (grow == near) ++e;
4480         delta = RECT_TOP(self->frame->area) - e;
4481         *y -= delta;
4482         *h += delta;
4483         break;
4484     case OB_DIRECTION_SOUTH:
4485         if (grow == near) --e;
4486         delta = e - RECT_BOTTOM(self->frame->area);
4487         *h += delta;
4488         break;
4489     default:
4490         g_assert_not_reached();
4491     }
4492     frame_frame_gravity(self->frame, x, y);
4493     *w -= self->frame->size.left + self->frame->size.right;
4494     *h -= self->frame->size.top + self->frame->size.bottom;
4495 }
4496
4497 ObClient* client_under_pointer(void)
4498 {
4499     gint x, y;
4500     GList *it;
4501     ObClient *ret = NULL;
4502
4503     if (screen_pointer_pos(&x, &y)) {
4504         for (it = stacking_list; it; it = g_list_next(it)) {
4505             if (WINDOW_IS_CLIENT(it->data)) {
4506                 ObClient *c = WINDOW_AS_CLIENT(it->data);
4507                 if (c->frame->visible &&
4508                     /* check the desktop, this is done during desktop
4509                        switching and windows are shown/hidden status is not
4510                        reliable */
4511                     (c->desktop == screen_desktop ||
4512                      c->desktop == DESKTOP_ALL) &&
4513                     /* ignore all animating windows */
4514                     !frame_iconify_animating(c->frame) &&
4515                     RECT_CONTAINS(c->frame->area, x, y))
4516                 {
4517                     ret = c;
4518                     break;
4519                 }
4520             }
4521         }
4522     }
4523     return ret;
4524 }
4525
4526 gboolean client_has_group_siblings(ObClient *self)
4527 {
4528     return self->group && self->group->members->next;
4529 }
4530
4531 /*! Returns TRUE if the client is running on the same machine as Openbox */
4532 gboolean client_on_localhost(ObClient *self)
4533 {
4534     return self->client_machine == NULL;
4535 }