JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
fix default keybindings for floater movement
[spectrwm.git] / scrotwm.c
1 /* $scrotwm$ */
2 /*
3  * Copyright (c) 2009-2010-2011 Marco Peereboom <marco@peereboom.us>
4  * Copyright (c) 2009-2010-2011 Ryan McBride <mcbride@countersiege.com>
5  * Copyright (c) 2009 Darrin Chandler <dwchandler@stilyagin.com>
6  * Copyright (c) 2009 Pierre-Yves Ritschard <pyr@spootnik.org>
7  * Copyright (c) 2010 Tuukka Kataja <stuge@xor.fi>
8  * Copyright (c) 2011 Jason L. Wright <jason@thought.net>
9  *
10  * Permission to use, copy, modify, and distribute this software for any
11  * purpose with or without fee is hereby granted, provided that the above
12  * copyright notice and this permission notice appear in all copies.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22 /*
23  * Much code and ideas taken from dwm under the following license:
24  * MIT/X Consortium License
25  *
26  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
27  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
28  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
29  * 2007 Premysl Hruby <dfenze at gmail dot com>
30  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
31  * 2007 Christof Musik <christof at sendfax dot de>
32  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
33  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
34  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
35  *
36  * Permission is hereby granted, free of charge, to any person obtaining a
37  * copy of this software and associated documentation files (the "Software"),
38  * to deal in the Software without restriction, including without limitation
39  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
40  * and/or sell copies of the Software, and to permit persons to whom the
41  * Software is furnished to do so, subject to the following conditions:
42  *
43  * The above copyright notice and this permission notice shall be included in
44  * all copies or substantial portions of the Software.
45  *
46  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
47  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
48  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
49  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
50  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
51  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
52  * DEALINGS IN THE SOFTWARE.
53  */
54
55 static const char       *cvstag =
56     "$scrotwm$";
57
58 #define SWM_VERSION     "0.9.34"
59
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <err.h>
63 #include <errno.h>
64 #include <fcntl.h>
65 #include <locale.h>
66 #include <unistd.h>
67 #include <time.h>
68 #include <signal.h>
69 #include <string.h>
70 #include <util.h>
71 #include <pwd.h>
72 #include <paths.h>
73 #include <ctype.h>
74
75 #include <sys/types.h>
76 #include <sys/time.h>
77 #include <sys/stat.h>
78 #include <sys/wait.h>
79 #include <sys/queue.h>
80 #include <sys/param.h>
81 #include <sys/select.h>
82
83 #include <X11/cursorfont.h>
84 #include <X11/keysym.h>
85 #include <X11/Xatom.h>
86 #include <X11/Xlib.h>
87 #include <X11/Xproto.h>
88 #include <X11/Xutil.h>
89 #include <X11/extensions/Xrandr.h>
90 #include <X11/extensions/XTest.h>
91
92 #ifdef __OSX__
93 #include <osx.h>
94 #endif
95
96 #if RANDR_MAJOR < 1
97 #  error XRandR versions less than 1.0 are not supported
98 #endif
99
100 #if RANDR_MAJOR >= 1
101 #if RANDR_MINOR >= 2
102 #define SWM_XRR_HAS_CRTC
103 #endif
104 #endif
105
106 /*#define SWM_DEBUG*/
107 #ifdef SWM_DEBUG
108 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while (0)
109 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while (0)
110 #define SWM_D_MISC              0x0001
111 #define SWM_D_EVENT             0x0002
112 #define SWM_D_WS                0x0004
113 #define SWM_D_FOCUS             0x0008
114 #define SWM_D_MOVE              0x0010
115 #define SWM_D_STACK             0x0020
116 #define SWM_D_MOUSE             0x0040
117 #define SWM_D_PROP              0x0080
118 #define SWM_D_CLASS             0x0100
119 #define SWM_D_KEY               0x0200
120 #define SWM_D_QUIRK             0x0400
121 #define SWM_D_SPAWN             0x0800
122 #define SWM_D_EVENTQ            0x1000
123 #define SWM_D_CONF              0x2000
124
125 u_int32_t               swm_debug = 0
126                             | SWM_D_MISC
127                             | SWM_D_EVENT
128                             | SWM_D_WS
129                             | SWM_D_FOCUS
130                             | SWM_D_MOVE
131                             | SWM_D_STACK
132                             | SWM_D_MOUSE
133                             | SWM_D_PROP
134                             | SWM_D_CLASS
135                             | SWM_D_KEY
136                             | SWM_D_QUIRK
137                             | SWM_D_SPAWN
138                             | SWM_D_EVENTQ
139                             | SWM_D_CONF
140                             ;
141 #else
142 #define DPRINTF(x...)
143 #define DNPRINTF(n,x...)
144 #endif
145
146 #define LENGTH(x)               (sizeof x / sizeof x[0])
147 #define MODKEY                  Mod1Mask
148 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
149 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
150 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
151 #define SWM_PROPLEN             (16)
152 #define SWM_FUNCNAME_LEN        (32)
153 #define SWM_KEYS_LEN            (255)
154 #define SWM_QUIRK_LEN           (64)
155 #define X(r)                    (r)->g.x
156 #define Y(r)                    (r)->g.y
157 #define WIDTH(r)                (r)->g.w
158 #define HEIGHT(r)               (r)->g.h
159 #define SWM_MAX_FONT_STEPS      (3)
160 #define WINID(w)                (w ? w->id : 0)
161
162 #define SWM_FOCUS_DEFAULT       (0)
163 #define SWM_FOCUS_SYNERGY       (1)
164 #define SWM_FOCUS_FOLLOW        (2)
165
166 #ifndef SWM_LIB
167 #define SWM_LIB                 "/usr/local/lib/libswmhack.so"
168 #endif
169
170 char                    **start_argv;
171 Atom                    astate;
172 Atom                    aprot;
173 Atom                    adelete;
174 Atom                    takefocus;
175 Atom                    a_wmname;
176 Atom                    a_utf8_string;
177 Atom                    a_string;
178 Atom                    a_swm_iconic;
179 volatile sig_atomic_t   running = 1;
180 volatile sig_atomic_t   restart_wm = 0;
181 int                     outputs = 0;
182 int                     last_focus_event = FocusOut;
183 int                     (*xerrorxlib)(Display *, XErrorEvent *);
184 int                     other_wm;
185 int                     ss_enabled = 0;
186 int                     xrandr_support;
187 int                     xrandr_eventbase;
188 unsigned int            numlockmask = 0;
189 Display                 *display;
190
191 int                     cycle_empty = 0;
192 int                     cycle_visible = 0;
193 int                     term_width = 0;
194 int                     font_adjusted = 0;
195 unsigned int            mod_key = MODKEY;
196
197 /* dmenu search */
198 struct swm_region       *search_r;
199 int                     select_list_pipe[2];
200 int                     select_resp_pipe[2];
201 pid_t                   searchpid;
202 volatile sig_atomic_t   search_resp;
203
204 /* dialog windows */
205 double                  dialog_ratio = .6;
206 /* status bar */
207 #define SWM_BAR_MAX     (256)
208 char                    *bar_argv[] = { NULL, NULL };
209 int                     bar_pipe[2];
210 char                    bar_ext[SWM_BAR_MAX];
211 char                    bar_vertext[SWM_BAR_MAX];
212 int                     bar_version = 0;
213 sig_atomic_t            bar_alarm = 0;
214 int                     bar_delay = 30;
215 int                     bar_enabled = 1;
216 int                     bar_border_width = 1;
217 int                     bar_at_bottom = 0;
218 int                     bar_extra = 1;
219 int                     bar_extra_running = 0;
220 int                     bar_verbose = 1;
221 int                     bar_height = 0;
222 int                     stack_enabled = 1;
223 int                     clock_enabled = 1;
224 int                     urgent_enabled = 0;
225 char                    *clock_format = NULL;
226 int                     title_name_enabled = 0;
227 int                     title_class_enabled = 0;
228 int                     window_name_enabled = 0;
229 int                     focus_mode = SWM_FOCUS_DEFAULT;
230 int                     disable_border = 0;
231 int                     border_width = 1;
232 int                     verbose_layout = 0;
233 pid_t                   bar_pid;
234 GC                      bar_gc;
235 XGCValues               bar_gcv;
236 int                     bar_fidx = 0;
237 XFontStruct             *bar_fs;
238 char                    *bar_fonts[] = { NULL, NULL, NULL, NULL };/* XXX Make fully dynamic */
239 char                    *spawn_term[] = { NULL, NULL };         /* XXX Make fully dynamic */
240
241 #define SWM_MENU_FN     (2)
242 #define SWM_MENU_NB     (4)
243 #define SWM_MENU_NF     (6)
244 #define SWM_MENU_SB     (8)
245 #define SWM_MENU_SF     (10)
246
247 /* layout manager data */
248 struct swm_geometry {
249         int                     x;
250         int                     y;
251         int                     w;
252         int                     h;
253 };
254
255 struct swm_screen;
256 struct workspace;
257
258 /* virtual "screens" */
259 struct swm_region {
260         TAILQ_ENTRY(swm_region) entry;
261         struct swm_geometry     g;
262         struct workspace        *ws;    /* current workspace on this region */
263         struct workspace        *ws_prior; /* prior workspace on this region */
264         struct swm_screen       *s;     /* screen idx */
265         Window                  bar_window;
266 };
267 TAILQ_HEAD(swm_region_list, swm_region);
268
269 struct ws_win {
270         TAILQ_ENTRY(ws_win)     entry;
271         Window                  id;
272         Window                  transient;
273         struct ws_win           *child_trans;   /* transient child window */
274         struct swm_geometry     g;              /* current geometry */
275         struct swm_geometry     g_float;        /* geometry when floating */
276         struct swm_geometry     rg_float;       /* region geom when floating */
277         int                     g_floatvalid;   /* flag: geometry in g_float is valid */
278         int                     floatmaxed;     /* flag: floater was maxed in max_stack */
279         int                     floating;
280         int                     manual;
281         int                     iconic;
282         unsigned int            ewmh_flags;
283         int                     font_size_boundary[SWM_MAX_FONT_STEPS];
284         int                     font_steps;
285         int                     last_inc;
286         int                     can_delete;
287         int                     take_focus;
288         int                     java;
289         unsigned long           quirks;
290         struct workspace        *ws;    /* always valid */
291         struct swm_screen       *s;     /* always valid, never changes */
292         XWindowAttributes       wa;
293         XSizeHints              sh;
294         XClassHint              ch;
295         XWMHints                *hints;
296 };
297 TAILQ_HEAD(ws_win_list, ws_win);
298
299 /* pid goo */
300 struct pid_e {
301         TAILQ_ENTRY(pid_e)      entry;
302         long                    pid;
303         int                     ws;
304 };
305 TAILQ_HEAD(pid_list, pid_e);
306 struct pid_list                 pidlist = TAILQ_HEAD_INITIALIZER(pidlist);
307
308 /* layout handlers */
309 void    stack(void);
310 void    vertical_config(struct workspace *, int);
311 void    vertical_stack(struct workspace *, struct swm_geometry *);
312 void    horizontal_config(struct workspace *, int);
313 void    horizontal_stack(struct workspace *, struct swm_geometry *);
314 void    max_stack(struct workspace *, struct swm_geometry *);
315 void    plain_stacker(struct workspace *);
316 void    fancy_stacker(struct workspace *);
317
318 struct ws_win *find_window(Window);
319
320 void    grabbuttons(struct ws_win *, int);
321 void    new_region(struct swm_screen *, int, int, int, int);
322 void    unmanage_window(struct ws_win *);
323 long    getstate(Window);
324
325 struct layout {
326         void            (*l_stack)(struct workspace *, struct swm_geometry *);
327         void            (*l_config)(struct workspace *, int);
328         u_int32_t       flags;
329 #define SWM_L_FOCUSPREV         (1<<0)
330 #define SWM_L_MAPONFOCUS        (1<<1)
331         void            (*l_string)(struct workspace *);
332 } layouts[] =  {
333         /* stack,               configure */
334         { vertical_stack,       vertical_config,        0,      plain_stacker },
335         { horizontal_stack,     horizontal_config,      0,      plain_stacker },
336         { max_stack,            NULL,
337           SWM_L_MAPONFOCUS | SWM_L_FOCUSPREV,                   plain_stacker },
338         { NULL,                 NULL,                   0,      NULL  },
339 };
340
341 /* position of max_stack mode in the layouts array, index into layouts! */
342 #define SWM_V_STACK             (0)
343 #define SWM_H_STACK             (1)
344 #define SWM_MAX_STACK           (2)
345
346 #define SWM_H_SLICE             (32)
347 #define SWM_V_SLICE             (32)
348
349 /* define work spaces */
350 struct workspace {
351         int                     idx;            /* workspace index */
352         int                     always_raise;   /* raise windows on focus */
353         struct layout           *cur_layout;    /* current layout handlers */
354         struct ws_win           *focus;         /* may be NULL */
355         struct ws_win           *focus_prev;    /* may be NULL */
356         struct swm_region       *r;             /* may be NULL */
357         struct swm_region       *old_r;         /* may be NULL */
358         struct ws_win_list      winlist;        /* list of windows in ws */
359         struct ws_win_list      unmanagedlist;  /* list of dead windows in ws */
360         char                    stacker[10];    /* display stacker and layout */
361
362         /* stacker state */
363         struct {
364                                 int horizontal_msize;
365                                 int horizontal_mwin;
366                                 int horizontal_stacks;
367                                 int vertical_msize;
368                                 int vertical_mwin;
369                                 int vertical_stacks;
370         } l_state;
371 };
372
373 enum    { SWM_S_COLOR_BAR, SWM_S_COLOR_BAR_BORDER, SWM_S_COLOR_BAR_FONT,
374           SWM_S_COLOR_FOCUS, SWM_S_COLOR_UNFOCUS, SWM_S_COLOR_MAX };
375
376 /* physical screen mapping */
377 #define SWM_WS_MAX              (10)
378 struct swm_screen {
379         int                     idx;    /* screen index */
380         struct swm_region_list  rl;     /* list of regions on this screen */
381         struct swm_region_list  orl;    /* list of old regions */
382         Window                  root;
383         struct workspace        ws[SWM_WS_MAX];
384
385         /* colors */
386         struct {
387                 unsigned long   color;
388                 char            *name;
389         } c[SWM_S_COLOR_MAX];
390 };
391 struct swm_screen       *screens;
392 int                     num_screens;
393
394 /* args to functions */
395 union arg {
396         int                     id;
397 #define SWM_ARG_ID_FOCUSNEXT    (0)
398 #define SWM_ARG_ID_FOCUSPREV    (1)
399 #define SWM_ARG_ID_FOCUSMAIN    (2)
400 #define SWM_ARG_ID_FOCUSCUR     (4)
401 #define SWM_ARG_ID_SWAPNEXT     (10)
402 #define SWM_ARG_ID_SWAPPREV     (11)
403 #define SWM_ARG_ID_SWAPMAIN     (12)
404 #define SWM_ARG_ID_MOVELAST     (13)
405 #define SWM_ARG_ID_MASTERSHRINK (20)
406 #define SWM_ARG_ID_MASTERGROW   (21)
407 #define SWM_ARG_ID_MASTERADD    (22)
408 #define SWM_ARG_ID_MASTERDEL    (23)
409 #define SWM_ARG_ID_STACKRESET   (30)
410 #define SWM_ARG_ID_STACKINIT    (31)
411 #define SWM_ARG_ID_CYCLEWS_UP   (40)
412 #define SWM_ARG_ID_CYCLEWS_DOWN (41)
413 #define SWM_ARG_ID_CYCLESC_UP   (42)
414 #define SWM_ARG_ID_CYCLESC_DOWN (43)
415 #define SWM_ARG_ID_STACKINC     (50)
416 #define SWM_ARG_ID_STACKDEC     (51)
417 #define SWM_ARG_ID_SS_ALL       (60)
418 #define SWM_ARG_ID_SS_WINDOW    (61)
419 #define SWM_ARG_ID_DONTCENTER   (70)
420 #define SWM_ARG_ID_CENTER       (71)
421 #define SWM_ARG_ID_KILLWINDOW   (80)
422 #define SWM_ARG_ID_DELETEWINDOW (81)
423 #define SWM_ARG_ID_WIDTHGROW    (90)
424 #define SWM_ARG_ID_WIDTHSHRINK  (91)
425 #define SWM_ARG_ID_HEIGHTGROW   (92)
426 #define SWM_ARG_ID_HEIGHTSHRINK (93)
427 #define SWM_ARG_ID_MOVEUP       (100)
428 #define SWM_ARG_ID_MOVEDOWN     (101)
429 #define SWM_ARG_ID_MOVELEFT     (102)
430 #define SWM_ARG_ID_MOVERIGHT    (103)
431         char                    **argv;
432 };
433
434 void    focus(struct swm_region *, union arg *);
435 void    focus_magic(struct ws_win *);
436
437 /* quirks */
438 struct quirk {
439         char                    *class;
440         char                    *name;
441         unsigned long           quirk;
442 #define SWM_Q_FLOAT             (1<<0)  /* float this window */
443 #define SWM_Q_TRANSSZ           (1<<1)  /* transiend window size too small */
444 #define SWM_Q_ANYWHERE          (1<<2)  /* don't position this window */
445 #define SWM_Q_XTERM_FONTADJ     (1<<3)  /* adjust xterm fonts when resizing */
446 #define SWM_Q_FULLSCREEN        (1<<4)  /* remove border */
447 #define SWM_Q_FOCUSPREV         (1<<5)  /* focus on caller */
448 };
449 int                             quirks_size = 0, quirks_length = 0;
450 struct quirk                    *quirks = NULL;
451
452 /*
453  * Supported EWMH hints should be added to
454  * both the enum and the ewmh array
455  */
456 enum { _NET_ACTIVE_WINDOW, _NET_MOVERESIZE_WINDOW, _NET_CLOSE_WINDOW,
457     _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DOCK,
458     _NET_WM_WINDOW_TYPE_TOOLBAR, _NET_WM_WINDOW_TYPE_UTILITY,
459     _NET_WM_WINDOW_TYPE_SPLASH, _NET_WM_WINDOW_TYPE_DIALOG,
460     _NET_WM_WINDOW_TYPE_NORMAL, _NET_WM_STATE,
461     _NET_WM_STATE_MAXIMIZED_HORZ, _NET_WM_STATE_MAXIMIZED_VERT,
462     _NET_WM_STATE_SKIP_TASKBAR, _NET_WM_STATE_SKIP_PAGER,
463     _NET_WM_STATE_HIDDEN, _NET_WM_STATE_ABOVE, _SWM_WM_STATE_MANUAL,
464     _NET_WM_STATE_FULLSCREEN, _NET_WM_ALLOWED_ACTIONS, _NET_WM_ACTION_MOVE,
465     _NET_WM_ACTION_RESIZE, _NET_WM_ACTION_FULLSCREEN, _NET_WM_ACTION_CLOSE,
466     SWM_EWMH_HINT_MAX };
467
468 struct ewmh_hint {
469         char    *name;
470         Atom     atom;
471 } ewmh[SWM_EWMH_HINT_MAX] =     {
472     /* must be in same order as in the enum */
473     {"_NET_ACTIVE_WINDOW", None},
474     {"_NET_MOVERESIZE_WINDOW", None},
475     {"_NET_CLOSE_WINDOW", None},
476     {"_NET_WM_WINDOW_TYPE", None},
477     {"_NET_WM_WINDOW_TYPE_DOCK", None},
478     {"_NET_WM_WINDOW_TYPE_TOOLBAR", None},
479     {"_NET_WM_WINDOW_TYPE_UTILITY", None},
480     {"_NET_WM_WINDOW_TYPE_SPLASH", None},
481     {"_NET_WM_WINDOW_TYPE_DIALOG", None},
482     {"_NET_WM_WINDOW_TYPE_NORMAL", None},
483     {"_NET_WM_STATE", None},
484     {"_NET_WM_STATE_MAXIMIZED_HORZ", None},
485     {"_NET_WM_STATE_MAXIMIZED_VERT", None},
486     {"_NET_WM_STATE_SKIP_TASKBAR", None},
487     {"_NET_WM_STATE_SKIP_PAGER", None},
488     {"_NET_WM_STATE_HIDDEN", None},
489     {"_NET_WM_STATE_ABOVE", None},
490     {"_SWM_WM_STATE_MANUAL", None},
491     {"_NET_WM_STATE_FULLSCREEN", None},
492     {"_NET_WM_ALLOWED_ACTIONS", None},
493     {"_NET_WM_ACTION_MOVE", None},
494     {"_NET_WM_ACTION_RESIZE", None},
495     {"_NET_WM_ACTION_FULLSCREEN", None},
496     {"_NET_WM_ACTION_CLOSE", None},
497 };
498
499 void    store_float_geom(struct ws_win *win, struct swm_region *r);
500 int     floating_toggle_win(struct ws_win *win);
501 void    spawn_select(struct swm_region *, union arg *, char *, int *);
502
503 int
504 get_property(Window id, Atom atom, long count, Atom type,
505     unsigned long *n, unsigned char **data)
506 {
507         int                     format, status;
508         unsigned long           tmp, extra;
509         unsigned long           *nitems;
510         Atom                    real;
511
512         nitems = n != NULL ? n : &tmp;
513         status = XGetWindowProperty(display, id, atom, 0L, count, False, type,
514             &real, &format, nitems, &extra, data);
515
516         if (status != Success)
517                 return False;
518         if (real != type)
519                 return False;
520
521         return True;
522 }
523
524 void
525 update_iconic(struct ws_win *win, int newv)
526 {
527         int32_t v = newv;
528         Atom iprop;
529
530         win->iconic = newv;
531
532         iprop = XInternAtom(display, "_SWM_ICONIC", False);
533         if (!iprop)
534                 return;
535         if (newv)
536                 XChangeProperty(display, win->id, iprop, XA_INTEGER, 32,
537                     PropModeReplace, (unsigned char *)&v, 1);
538         else
539                 XDeleteProperty(display, win->id, iprop);
540 }
541
542 int
543 get_iconic(struct ws_win *win)
544 {
545         int32_t v = 0;
546         int retfmt, status;
547         Atom iprop, rettype;
548         unsigned long nitems, extra;
549         unsigned char *prop = NULL;
550
551         iprop = XInternAtom(display, "_SWM_ICONIC", False);
552         if (!iprop)
553                 goto out;
554         status = XGetWindowProperty(display, win->id, iprop, 0L, 1L,
555             False, XA_INTEGER, &rettype, &retfmt, &nitems, &extra, &prop);
556         if (status != Success)
557                 goto out;
558         if (rettype != XA_INTEGER || retfmt != 32)
559                 goto out;
560         if (nitems != 1)
561                 goto out;
562         v = *((int32_t *)prop);
563
564 out:
565         if (prop != NULL)
566                 XFree(prop);
567         return (v);
568 }
569
570 void
571 setup_ewmh(void)
572 {
573         int                     i,j;
574         Atom                    sup_list;
575
576         sup_list = XInternAtom(display, "_NET_SUPPORTED", False);
577
578         for (i = 0; i < LENGTH(ewmh); i++)
579                 ewmh[i].atom = XInternAtom(display, ewmh[i].name, False);
580
581         for (i = 0; i < ScreenCount(display); i++) {
582                 /* Support check window will be created by workaround(). */
583
584                 /* Report supported atoms */
585                 XDeleteProperty(display, screens[i].root, sup_list);
586                 for (j = 0; j < LENGTH(ewmh); j++)
587                         XChangeProperty(display, screens[i].root,
588                             sup_list, XA_ATOM, 32,
589                             PropModeAppend, (unsigned char *)&ewmh[j].atom,1);
590         }
591 }
592
593 void
594 teardown_ewmh(void)
595 {
596         int                     i, success;
597         unsigned char           *data = NULL;
598         unsigned long           n;
599         Atom                    sup_check, sup_list;
600         Window                  id;
601
602         sup_check = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
603         sup_list = XInternAtom(display, "_NET_SUPPORTED", False);
604
605         for (i = 0; i < ScreenCount(display); i++) {
606                 /* Get the support check window and destroy it */
607                 success = get_property(screens[i].root, sup_check, 1, XA_WINDOW,
608                     &n, &data);
609
610                 if (success) {
611                         id = data[0];
612                         XDestroyWindow(display, id);
613                         XDeleteProperty(display, screens[i].root, sup_check);
614                         XDeleteProperty(display, screens[i].root, sup_list);
615                 }
616
617                 XFree(data);
618         }
619 }
620
621 void
622 ewmh_autoquirk(struct ws_win *win)
623 {
624         int                     success, i;
625         unsigned long           *data = NULL, n;
626         Atom                    type;
627
628         success = get_property(win->id, ewmh[_NET_WM_WINDOW_TYPE].atom, (~0L),
629             XA_ATOM, &n, (void *)&data);
630
631         if (!success) {
632                 XFree(data);
633                 return;
634         }
635
636         for (i = 0; i < n; i++) {
637                 type = data[i];
638                 if (type == ewmh[_NET_WM_WINDOW_TYPE_NORMAL].atom)
639                         break;
640                 if (type == ewmh[_NET_WM_WINDOW_TYPE_DOCK].atom ||
641                     type == ewmh[_NET_WM_WINDOW_TYPE_TOOLBAR].atom ||
642                     type == ewmh[_NET_WM_WINDOW_TYPE_UTILITY].atom) {
643                         win->floating = 1;
644                         win->quirks = SWM_Q_FLOAT | SWM_Q_ANYWHERE;
645                         break;
646                 }
647                 if (type == ewmh[_NET_WM_WINDOW_TYPE_SPLASH].atom ||
648                     type == ewmh[_NET_WM_WINDOW_TYPE_DIALOG].atom) {
649                         win->floating = 1;
650                         win->quirks = SWM_Q_FLOAT;
651                         break;
652                 }
653         }
654
655         XFree(data);
656 }
657
658 #define SWM_EWMH_ACTION_COUNT_MAX       (6)
659 #define EWMH_F_FULLSCREEN               (1<<0)
660 #define EWMH_F_ABOVE                    (1<<1)
661 #define EWMH_F_HIDDEN                   (1<<2)
662 #define EWMH_F_SKIP_PAGER               (1<<3)
663 #define EWMH_F_SKIP_TASKBAR             (1<<4)
664 #define SWM_F_MANUAL                    (1<<5)
665
666 int
667 ewmh_set_win_fullscreen(struct ws_win *win, int fs)
668 {
669         struct swm_geometry     rg;
670
671         if (!win->ws->r)
672                 return 0;
673
674         if (!win->floating)
675                 return 0;
676
677         DNPRINTF(SWM_D_MISC, "ewmh_set_win_fullscreen: win 0x%lx fs: %d\n",
678             win->id, fs);
679
680         rg = win->ws->r->g;
681
682         if (fs) {
683                 store_float_geom(win, win->ws->r);
684
685                 win->g.x = rg.x;
686                 win->g.y = rg.y;
687                 win->g.w = rg.w;
688                 win->g.h = rg.h;
689         } else {
690                 if (win->g_floatvalid) {
691                         /* refloat at last floating relative position */
692                         win->g.x = win->g_float.x - win->rg_float.x + rg.x;
693                         win->g.y = win->g_float.y - win->rg_float.y + rg.y;
694                         win->g.w = win->g_float.w;
695                         win->g.h = win->g_float.h;
696                 }
697         }
698
699         return 1;
700 }
701
702 void
703 ewmh_update_actions(struct ws_win *win)
704 {
705         Atom                    actions[SWM_EWMH_ACTION_COUNT_MAX];
706         int                     n = 0;
707
708         if (win == NULL)
709                 return;
710
711         actions[n++] = ewmh[_NET_WM_ACTION_CLOSE].atom;
712
713         if (win->floating) {
714                 actions[n++] = ewmh[_NET_WM_ACTION_MOVE].atom;
715                 actions[n++] = ewmh[_NET_WM_ACTION_RESIZE].atom;
716         }
717
718         XChangeProperty(display, win->id, ewmh[_NET_WM_ALLOWED_ACTIONS].atom,
719             XA_ATOM, 32, PropModeReplace, (unsigned char *)actions, n);
720 }
721
722 #define _NET_WM_STATE_REMOVE    0    /* remove/unset property */
723 #define _NET_WM_STATE_ADD       1    /* add/set property */
724 #define _NET_WM_STATE_TOGGLE    2    /* toggle property */
725
726 void
727 ewmh_update_win_state(struct ws_win *win, long state, long action)
728 {
729         unsigned int            mask = 0;
730         unsigned int            changed = 0;
731         unsigned int            orig_flags;
732
733         if (win == NULL)
734                 return;
735
736         if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
737                 mask = EWMH_F_FULLSCREEN;
738         if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
739                 mask = EWMH_F_ABOVE;
740         if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
741                 mask = SWM_F_MANUAL;
742         if (state == ewmh[_NET_WM_STATE_SKIP_PAGER].atom)
743                 mask = EWMH_F_SKIP_PAGER;
744         if (state == ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom)
745                 mask = EWMH_F_SKIP_TASKBAR;
746
747
748         orig_flags = win->ewmh_flags;
749
750         switch (action) {
751         case _NET_WM_STATE_REMOVE:
752                 win->ewmh_flags &= ~mask;
753                 break;
754         case _NET_WM_STATE_ADD:
755                 win->ewmh_flags |= mask;
756                 break;
757         case _NET_WM_STATE_TOGGLE:
758                 win->ewmh_flags ^= mask;
759                 break;
760         }
761
762         changed = (win->ewmh_flags & mask) ^ (orig_flags & mask) ? 1 : 0;
763
764         if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
765                 if (changed)
766                         if (!floating_toggle_win(win))
767                                 win->ewmh_flags = orig_flags; /* revert */
768         if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
769                 if (changed)
770                         win->manual = (win->ewmh_flags & SWM_F_MANUAL) != 0;
771         if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
772                 if (changed)
773                         if (!ewmh_set_win_fullscreen(win,
774                             win->ewmh_flags & EWMH_F_FULLSCREEN))
775                                 win->ewmh_flags = orig_flags; /* revert */
776
777         XDeleteProperty(display, win->id, ewmh[_NET_WM_STATE].atom);
778
779         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
780                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
781                     XA_ATOM, 32, PropModeAppend,
782                     (unsigned char *)&ewmh[_NET_WM_STATE_FULLSCREEN].atom, 1);
783         if (win->ewmh_flags & EWMH_F_SKIP_PAGER)
784                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
785                     XA_ATOM, 32, PropModeAppend,
786                     (unsigned char *)&ewmh[_NET_WM_STATE_SKIP_PAGER].atom, 1);
787         if (win->ewmh_flags & EWMH_F_SKIP_TASKBAR)
788                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
789                     XA_ATOM, 32, PropModeAppend,
790                     (unsigned char *)&ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom, 1);
791         if (win->ewmh_flags & EWMH_F_ABOVE)
792                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
793                     XA_ATOM, 32, PropModeAppend,
794                     (unsigned char *)&ewmh[_NET_WM_STATE_ABOVE].atom, 1);
795         if (win->ewmh_flags & SWM_F_MANUAL)
796                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
797                     XA_ATOM, 32, PropModeAppend,
798                     (unsigned char *)&ewmh[_SWM_WM_STATE_MANUAL].atom, 1);
799 }
800
801 void
802 ewmh_get_win_state(struct ws_win *win)
803 {
804         int                     success, i;
805         unsigned long           n;
806         Atom                    *states;
807
808         if (win == NULL)
809                 return;
810
811         win->ewmh_flags = 0;
812         if (win->floating)
813                 win->ewmh_flags |= EWMH_F_ABOVE;
814         if (win->manual)
815                 win->ewmh_flags |= SWM_F_MANUAL;
816
817         success = get_property(win->id, ewmh[_NET_WM_STATE].atom,
818             (~0L), XA_ATOM, &n, (void *)&states);
819
820         if (!success)
821                 return;
822
823         for (i = 0; i < n; i++)
824                 ewmh_update_win_state(win, states[i], _NET_WM_STATE_ADD);
825
826         XFree(states);
827 }
828
829 /* events */
830 #ifdef SWM_DEBUG
831 void
832 dumpevent(XEvent *e)
833 {
834         char                    *name = NULL;
835
836         switch (e->type) {
837         case KeyPress:
838                 name = "KeyPress";
839                 break;
840         case KeyRelease:
841                 name = "KeyRelease";
842                 break;
843         case ButtonPress:
844                 name = "ButtonPress";
845                 break;
846         case ButtonRelease:
847                 name = "ButtonRelease";
848                 break;
849         case MotionNotify:
850                 name = "MotionNotify";
851                 break;
852         case EnterNotify:
853                 name = "EnterNotify";
854                 break;
855         case LeaveNotify:
856                 name = "LeaveNotify";
857                 break;
858         case FocusIn:
859                 name = "FocusIn";
860                 break;
861         case FocusOut:
862                 name = "FocusOut";
863                 break;
864         case KeymapNotify:
865                 name = "KeymapNotify";
866                 break;
867         case Expose:
868                 name = "Expose";
869                 break;
870         case GraphicsExpose:
871                 name = "GraphicsExpose";
872                 break;
873         case NoExpose:
874                 name = "NoExpose";
875                 break;
876         case VisibilityNotify:
877                 name = "VisibilityNotify";
878                 break;
879         case CreateNotify:
880                 name = "CreateNotify";
881                 break;
882         case DestroyNotify:
883                 name = "DestroyNotify";
884                 break;
885         case UnmapNotify:
886                 name = "UnmapNotify";
887                 break;
888         case MapNotify:
889                 name = "MapNotify";
890                 break;
891         case MapRequest:
892                 name = "MapRequest";
893                 break;
894         case ReparentNotify:
895                 name = "ReparentNotify";
896                 break;
897         case ConfigureNotify:
898                 name = "ConfigureNotify";
899                 break;
900         case ConfigureRequest:
901                 name = "ConfigureRequest";
902                 break;
903         case GravityNotify:
904                 name = "GravityNotify";
905                 break;
906         case ResizeRequest:
907                 name = "ResizeRequest";
908                 break;
909         case CirculateNotify:
910                 name = "CirculateNotify";
911                 break;
912         case CirculateRequest:
913                 name = "CirculateRequest";
914                 break;
915         case PropertyNotify:
916                 name = "PropertyNotify";
917                 break;
918         case SelectionClear:
919                 name = "SelectionClear";
920                 break;
921         case SelectionRequest:
922                 name = "SelectionRequest";
923                 break;
924         case SelectionNotify:
925                 name = "SelectionNotify";
926                 break;
927         case ColormapNotify:
928                 name = "ColormapNotify";
929                 break;
930         case ClientMessage:
931                 name = "ClientMessage";
932                 break;
933         case MappingNotify:
934                 name = "MappingNotify";
935                 break;
936         }
937
938         if (name)
939                 DNPRINTF(SWM_D_EVENTQ ,"window: %lu event: %s (%d), %d "
940                     "remaining\n",
941                     e->xany.window, name, e->type, QLength(display));
942         else
943                 DNPRINTF(SWM_D_EVENTQ, "window: %lu unknown event %d, %d "
944                     "remaining\n",
945                     e->xany.window, e->type, QLength(display));
946 }
947
948 void
949 dumpwins(struct swm_region *r, union arg *args)
950 {
951         struct ws_win           *win;
952         unsigned int            state;
953         XWindowAttributes       wa;
954
955         if (r->ws == NULL) {
956                 fprintf(stderr, "invalid workspace\n");
957                 return;
958         }
959
960         fprintf(stderr, "=== managed window list ws %02d ===\n", r->ws->idx);
961
962         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
963                 state = getstate(win->id);
964                 if (!XGetWindowAttributes(display, win->id, &wa))
965                         fprintf(stderr, "window: %lu failed "
966                             "XGetWindowAttributes\n", win->id);
967                 fprintf(stderr, "window: %lu map_state: %d state: %d "
968                     "transient: %lu\n",
969                     win->id, wa.map_state, state, win->transient);
970         }
971
972         fprintf(stderr, "===== unmanaged window list =====\n");
973         TAILQ_FOREACH(win, &r->ws->unmanagedlist, entry) {
974                 state = getstate(win->id);
975                 if (!XGetWindowAttributes(display, win->id, &wa))
976                         fprintf(stderr, "window: %lu failed "
977                             "XGetWindowAttributes\n", win->id);
978                 fprintf(stderr, "window: %lu map_state: %d state: %d "
979                     "transient: %lu\n",
980                     win->id, wa.map_state, state, win->transient);
981         }
982
983         fprintf(stderr, "=================================\n");
984 }
985 #else
986 #define dumpevent(e)
987 void
988 dumpwins(struct swm_region *r, union arg *args)
989 {
990 }
991 #endif /* SWM_DEBUG */
992
993 void                    expose(XEvent *);
994 void                    keypress(XEvent *);
995 void                    buttonpress(XEvent *);
996 void                    configurerequest(XEvent *);
997 void                    configurenotify(XEvent *);
998 void                    destroynotify(XEvent *);
999 void                    enternotify(XEvent *);
1000 void                    focusevent(XEvent *);
1001 void                    mapnotify(XEvent *);
1002 void                    mappingnotify(XEvent *);
1003 void                    maprequest(XEvent *);
1004 void                    propertynotify(XEvent *);
1005 void                    unmapnotify(XEvent *);
1006 void                    visibilitynotify(XEvent *);
1007 void                    clientmessage(XEvent *);
1008
1009 void                    (*handler[LASTEvent])(XEvent *) = {
1010                                 [Expose] = expose,
1011                                 [KeyPress] = keypress,
1012                                 [ButtonPress] = buttonpress,
1013                                 [ConfigureRequest] = configurerequest,
1014                                 [ConfigureNotify] = configurenotify,
1015                                 [DestroyNotify] = destroynotify,
1016                                 [EnterNotify] = enternotify,
1017                                 [FocusIn] = focusevent,
1018                                 [FocusOut] = focusevent,
1019                                 [MapNotify] = mapnotify,
1020                                 [MappingNotify] = mappingnotify,
1021                                 [MapRequest] = maprequest,
1022                                 [PropertyNotify] = propertynotify,
1023                                 [UnmapNotify] = unmapnotify,
1024                                 [VisibilityNotify] = visibilitynotify,
1025                                 [ClientMessage] = clientmessage,
1026 };
1027
1028 void
1029 sighdlr(int sig)
1030 {
1031         int                     saved_errno, status;
1032         pid_t                   pid;
1033
1034         saved_errno = errno;
1035
1036         switch (sig) {
1037         case SIGCHLD:
1038                 while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
1039                         if (pid == -1) {
1040                                 if (errno == EINTR)
1041                                         continue;
1042 #ifdef SWM_DEBUG
1043                                 if (errno != ECHILD)
1044                                         warn("sighdlr: waitpid");
1045 #endif /* SWM_DEBUG */
1046                                 break;
1047                         }
1048                         if (pid == searchpid)
1049                                 search_resp = 1;
1050
1051 #ifdef SWM_DEBUG
1052                         if (WIFEXITED(status)) {
1053                                 if (WEXITSTATUS(status) != 0)
1054                                         warnx("sighdlr: child exit status: %d",
1055                                             WEXITSTATUS(status));
1056                         } else
1057                                 warnx("sighdlr: child is terminated "
1058                                     "abnormally");
1059 #endif /* SWM_DEBUG */
1060                 }
1061                 break;
1062
1063         case SIGHUP:
1064                 restart_wm = 1;
1065                 break;
1066         case SIGINT:
1067         case SIGTERM:
1068         case SIGQUIT:
1069                 running = 0;
1070                 break;
1071         }
1072
1073         errno = saved_errno;
1074 }
1075
1076 struct pid_e *
1077 find_pid(long pid)
1078 {
1079         struct pid_e            *p = NULL;
1080
1081         DNPRINTF(SWM_D_MISC, "find_pid: %lu\n", pid);
1082
1083         if (pid == 0)
1084                 return (NULL);
1085
1086         TAILQ_FOREACH(p, &pidlist, entry) {
1087                 if (p->pid == pid)
1088                         return (p);
1089         }
1090
1091         return (NULL);
1092 }
1093
1094 unsigned long
1095 name_to_color(char *colorname)
1096 {
1097         Colormap                cmap;
1098         Status                  status;
1099         XColor                  screen_def, exact_def;
1100         unsigned long           result = 0;
1101         char                    cname[32] = "#";
1102
1103         cmap = DefaultColormap(display, screens[0].idx);
1104         status = XAllocNamedColor(display, cmap, colorname,
1105             &screen_def, &exact_def);
1106         if (!status) {
1107                 strlcat(cname, colorname + 2, sizeof cname - 1);
1108                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
1109                     &exact_def);
1110         }
1111         if (status)
1112                 result = screen_def.pixel;
1113         else
1114                 fprintf(stderr, "color '%s' not found.\n", colorname);
1115
1116         return (result);
1117 }
1118
1119 void
1120 setscreencolor(char *val, int i, int c)
1121 {
1122         if (i > 0 && i <= ScreenCount(display)) {
1123                 screens[i - 1].c[c].color = name_to_color(val);
1124                 free(screens[i - 1].c[c].name);
1125                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
1126                         errx(1, "strdup");
1127         } else if (i == -1) {
1128                 for (i = 0; i < ScreenCount(display); i++) {
1129                         screens[i].c[c].color = name_to_color(val);
1130                         free(screens[i].c[c].name);
1131                         if ((screens[i].c[c].name = strdup(val)) == NULL)
1132                                 errx(1, "strdup");
1133                 }
1134         } else
1135                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
1136                     i, ScreenCount(display));
1137 }
1138
1139 void
1140 fancy_stacker(struct workspace *ws)
1141 {
1142         strcpy(ws->stacker, "[   ]");
1143         if (ws->cur_layout->l_stack == vertical_stack)
1144                 snprintf(ws->stacker, sizeof ws->stacker, "[%d|%d]",
1145                     ws->l_state.vertical_mwin, ws->l_state.vertical_stacks);
1146         if (ws->cur_layout->l_stack == horizontal_stack)
1147                 snprintf(ws->stacker, sizeof ws->stacker, "[%d-%d]",
1148                     ws->l_state.horizontal_mwin, ws->l_state.horizontal_stacks);
1149 }
1150
1151 void
1152 plain_stacker(struct workspace *ws)
1153 {
1154         strcpy(ws->stacker, "[ ]");
1155         if (ws->cur_layout->l_stack == vertical_stack)
1156                 strcpy(ws->stacker, "[|]");
1157         if (ws->cur_layout->l_stack == horizontal_stack)
1158                 strcpy(ws->stacker, "[-]");
1159 }
1160
1161 void
1162 custom_region(char *val)
1163 {
1164         unsigned int                    sidx, x, y, w, h;
1165
1166         if (sscanf(val, "screen[%u]:%ux%u+%u+%u", &sidx, &w, &h, &x, &y) != 5)
1167                 errx(1, "invalid custom region, "
1168                     "should be 'screen[<n>]:<n>x<n>+<n>+<n>\n");
1169         if (sidx < 1 || sidx > ScreenCount(display))
1170                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
1171                     sidx, ScreenCount(display));
1172         sidx--;
1173
1174         if (w < 1 || h < 1)
1175                 errx(1, "region %ux%u+%u+%u too small\n", w, h, x, y);
1176
1177         if (x > DisplayWidth(display, sidx) ||
1178             y > DisplayHeight(display, sidx) ||
1179             w + x > DisplayWidth(display, sidx) ||
1180             h + y > DisplayHeight(display, sidx)) {
1181                 fprintf(stderr, "ignoring region %ux%u+%u+%u "
1182                     "- not within screen boundaries "
1183                     "(%ux%u)\n", w, h, x, y,
1184                     DisplayWidth(display, sidx), DisplayHeight(display, sidx));
1185                 return;
1186         }
1187
1188         new_region(&screens[sidx], x, y, w, h);
1189 }
1190
1191 void
1192 socket_setnonblock(int fd)
1193 {
1194         int                     flags;
1195
1196         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
1197                 err(1, "fcntl F_GETFL");
1198         flags |= O_NONBLOCK;
1199         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
1200                 err(1, "fcntl F_SETFL");
1201 }
1202
1203 void
1204 bar_print(struct swm_region *r, char *s)
1205 {
1206         XClearWindow(display, r->bar_window);
1207         XSetForeground(display, bar_gc, r->s->c[SWM_S_COLOR_BAR_FONT].color);
1208         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent, s,
1209             strlen(s));
1210 }
1211
1212 void
1213 bar_extra_stop(void)
1214 {
1215         if (bar_pipe[0]) {
1216                 close(bar_pipe[0]);
1217                 bzero(bar_pipe, sizeof bar_pipe);
1218         }
1219         if (bar_pid) {
1220                 kill(bar_pid, SIGTERM);
1221                 bar_pid = 0;
1222         }
1223         strlcpy(bar_ext, "", sizeof bar_ext);
1224         bar_extra = 0;
1225 }
1226
1227 void
1228 bar_class_name(char *s, ssize_t sz, struct ws_win *cur_focus)
1229 {
1230         int                     do_class, do_name;
1231         Status                  status;
1232         XClassHint              *xch = NULL;
1233
1234         if ((title_name_enabled == 1 || title_class_enabled == 1) &&
1235             cur_focus != NULL) {
1236                 if ((xch = XAllocClassHint()) == NULL)
1237                         goto out;
1238                 status = XGetClassHint(display, cur_focus->id, xch);
1239                 if (status == BadWindow || status == BadAlloc)
1240                         goto out;
1241                 do_class = (title_class_enabled && xch->res_class != NULL);
1242                 do_name = (title_name_enabled && xch->res_name != NULL);
1243                 if (do_class)
1244                         strlcat(s, xch->res_class, sz);
1245                 if (do_class && do_name)
1246                         strlcat(s, ":", sz);
1247                 if (do_name)
1248                         strlcat(s, xch->res_name, sz);
1249                 strlcat(s, "    ", sz);
1250         }
1251 out:
1252         if (xch)
1253                 XFree(xch);
1254 }
1255
1256 void
1257 bar_window_name(char *s, ssize_t sz, struct ws_win *cur_focus)
1258 {
1259         char                    *title;
1260
1261         if (window_name_enabled && cur_focus != NULL) {
1262                 XFetchName(display, cur_focus->id, &title);
1263                 if (title) {
1264                         if (cur_focus->floating)
1265                                 strlcat(s, "(f) ", sz);
1266                         strlcat(s, title, sz);
1267                         strlcat(s, " ", sz);
1268                         XFree(title);
1269                 }
1270         }
1271 }
1272
1273 int             urgent[SWM_WS_MAX];
1274 void
1275 bar_urgent(char *s, ssize_t sz)
1276 {
1277         XWMHints                *wmh = NULL;
1278         struct ws_win           *win;
1279         int                     i, j;
1280         char                    b[8];
1281
1282         if (urgent_enabled == 0)
1283                 return;
1284
1285         for (i = 0; i < SWM_WS_MAX; i++)
1286                 urgent[i] = 0;
1287
1288         for (i = 0; i < ScreenCount(display); i++)
1289                 for (j = 0; j < SWM_WS_MAX; j++)
1290                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
1291                                 wmh = XGetWMHints(display, win->id);
1292                                 if (wmh == NULL)
1293                                         continue;
1294
1295                                 if (wmh->flags & XUrgencyHint)
1296                                         urgent[j] = 1;
1297                                 XFree(wmh);
1298                         }
1299
1300         strlcat(s, "* ", sz);
1301         for (i = 0; i < SWM_WS_MAX; i++) {
1302                 if (urgent[i])
1303                         snprintf(b, sizeof b, "%d ", i + 1);
1304                 else
1305                         snprintf(b, sizeof b, "- ");
1306                 strlcat(s, b, sz);
1307         }
1308         strlcat(s, "*    ", sz);
1309 }
1310
1311 void
1312 bar_update(void)
1313 {
1314         time_t                  tmt;
1315         struct tm               tm;
1316         struct swm_region       *r;
1317         int                     i, x;
1318         size_t                  len;
1319         char                    s[SWM_BAR_MAX];
1320         char                    cn[SWM_BAR_MAX];
1321         char                    loc[SWM_BAR_MAX];
1322         char                    *b;
1323
1324         if (bar_enabled == 0)
1325                 return;
1326         if (bar_extra && bar_extra_running) {
1327                 /* ignore short reads; it'll correct itself */
1328                 while ((b = fgetln(stdin, &len)) != NULL)
1329                         if (b && b[len - 1] == '\n') {
1330                                 b[len - 1] = '\0';
1331                                 strlcpy(bar_ext, b, sizeof bar_ext);
1332                         }
1333                 if (b == NULL && errno != EAGAIN) {
1334                         fprintf(stderr, "bar_extra failed: errno: %d %s\n",
1335                             errno, strerror(errno));
1336                         bar_extra_stop();
1337                 }
1338         } else
1339                 strlcpy(bar_ext, "", sizeof bar_ext);
1340
1341         if (clock_enabled == 0)
1342                 strlcpy(s, "", sizeof s);
1343         else {
1344                 time(&tmt);
1345                 localtime_r(&tmt, &tm);
1346                 strftime(s, sizeof s, clock_format, &tm);
1347                 strlcat(s, "    ", sizeof s);
1348         }
1349
1350         for (i = 0; i < ScreenCount(display); i++) {
1351                 x = 1;
1352                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1353                         strlcpy(cn, "", sizeof cn);
1354                         if (r && r->ws) {
1355                                 bar_urgent(cn, sizeof cn);
1356                                 bar_class_name(cn, sizeof cn, r->ws->focus);
1357                                 bar_window_name(cn, sizeof cn, r->ws->focus);
1358                         }
1359
1360                         snprintf(loc, sizeof loc, "%d:%d %s   %s%s    %s    %s",
1361                             x++, r->ws->idx + 1, r->ws->stacker, s, cn, bar_ext,
1362                             bar_vertext);
1363                         bar_print(r, loc);
1364                 }
1365         }
1366         alarm(bar_delay);
1367 }
1368
1369 void
1370 bar_signal(int sig)
1371 {
1372         bar_alarm = 1;
1373 }
1374
1375 void
1376 bar_toggle(struct swm_region *r, union arg *args)
1377 {
1378         struct swm_region       *tmpr;
1379         int                     i, sc = ScreenCount(display);
1380
1381         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
1382
1383         if (bar_enabled)
1384                 for (i = 0; i < sc; i++)
1385                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1386                                 XUnmapWindow(display, tmpr->bar_window);
1387         else
1388                 for (i = 0; i < sc; i++)
1389                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1390                                 XMapRaised(display, tmpr->bar_window);
1391
1392         bar_enabled = !bar_enabled;
1393
1394         stack();
1395         /* must be after stack */
1396         bar_update();
1397 }
1398
1399 void
1400 bar_refresh(void)
1401 {
1402         XSetWindowAttributes    wa;
1403         struct swm_region       *r;
1404         int                     i;
1405
1406         /* do this here because the conf file is in memory */
1407         if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
1408                 /* launch external status app */
1409                 bar_extra_running = 1;
1410                 if (pipe(bar_pipe) == -1)
1411                         err(1, "pipe error");
1412                 socket_setnonblock(bar_pipe[0]);
1413                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
1414                 if (dup2(bar_pipe[0], 0) == -1)
1415                         errx(1, "dup2");
1416                 if (dup2(bar_pipe[1], 1) == -1)
1417                         errx(1, "dup2");
1418                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1419                         err(1, "could not disable SIGPIPE");
1420                 switch (bar_pid = fork()) {
1421                 case -1:
1422                         err(1, "cannot fork");
1423                         break;
1424                 case 0: /* child */
1425                         close(bar_pipe[0]);
1426                         execvp(bar_argv[0], bar_argv);
1427                         err(1, "%s external app failed", bar_argv[0]);
1428                         break;
1429                 default: /* parent */
1430                         close(bar_pipe[1]);
1431                         break;
1432                 }
1433         }
1434
1435         bzero(&wa, sizeof wa);
1436         for (i = 0; i < ScreenCount(display); i++)
1437                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1438                         wa.border_pixel =
1439                             screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
1440                         wa.background_pixel =
1441                             screens[i].c[SWM_S_COLOR_BAR].color;
1442                         XChangeWindowAttributes(display, r->bar_window,
1443                             CWBackPixel | CWBorderPixel, &wa);
1444                 }
1445         bar_update();
1446 }
1447
1448 void
1449 bar_setup(struct swm_region *r)
1450 {
1451         int                     i, x, y;
1452
1453         if (bar_fs) {
1454                 XFreeFont(display, bar_fs);
1455                 bar_fs = NULL;
1456         }
1457
1458         for (i = 0; bar_fonts[i] != NULL; i++) {
1459                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
1460                 if (bar_fs) {
1461                         bar_fidx = i;
1462                         break;
1463                 }
1464         }
1465         if (bar_fonts[i] == NULL)
1466                         errx(1, "couldn't load font");
1467         if (bar_fs == NULL)
1468                 errx(1, "couldn't create font structure");
1469
1470         bar_height = bar_fs->ascent + bar_fs->descent + 1 +
1471             2 * bar_border_width;
1472         x = X(r);
1473         y = bar_at_bottom ? (Y(r) + HEIGHT(r) - bar_height) : Y(r);
1474
1475         r->bar_window = XCreateSimpleWindow(display,
1476             r->s->root, x, y, WIDTH(r) - 2 * bar_border_width,
1477             bar_height - 2 * bar_border_width,
1478             bar_border_width, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
1479             r->s->c[SWM_S_COLOR_BAR].color);
1480         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
1481         XSetFont(display, bar_gc, bar_fs->fid);
1482         XSelectInput(display, r->bar_window, VisibilityChangeMask);
1483         if (bar_enabled)
1484                 XMapRaised(display, r->bar_window);
1485         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
1486
1487         if (signal(SIGALRM, bar_signal) == SIG_ERR)
1488                 err(1, "could not install bar_signal");
1489         bar_refresh();
1490 }
1491
1492 void
1493 drain_enter_notify(void)
1494 {
1495         int                     i = 0;
1496         XEvent                  cne;
1497
1498         while (XCheckMaskEvent(display, EnterWindowMask, &cne))
1499                 i++;
1500
1501         DNPRINTF(SWM_D_MISC, "drain_enter_notify: drained %d\n", i);
1502 }
1503
1504 void
1505 set_win_state(struct ws_win *win, long state)
1506 {
1507         long                    data[] = {state, None};
1508
1509         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1510
1511         if (win == NULL)
1512                 return;
1513
1514         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1515             (unsigned char *)data, 2);
1516 }
1517
1518 long
1519 getstate(Window w)
1520 {
1521         long                    result = -1;
1522         unsigned char           *p = NULL;
1523         unsigned long           n;
1524
1525         if (!get_property(w, astate, 2L, astate, &n, &p))
1526                 return (-1);
1527         if (n != 0)
1528                 result = *((long *)p);
1529         XFree(p);
1530         return (result);
1531 }
1532
1533 void
1534 version(struct swm_region *r, union arg *args)
1535 {
1536         bar_version = !bar_version;
1537         if (bar_version)
1538                 snprintf(bar_vertext, sizeof bar_vertext, "Version: %s CVS: %s",
1539                     SWM_VERSION, cvstag);
1540         else
1541                 strlcpy(bar_vertext, "", sizeof bar_vertext);
1542         bar_update();
1543 }
1544
1545 void
1546 client_msg(struct ws_win *win, Atom a)
1547 {
1548         XClientMessageEvent     cm;
1549
1550         if (win == NULL)
1551                 return;
1552
1553         bzero(&cm, sizeof cm);
1554         cm.type = ClientMessage;
1555         cm.window = win->id;
1556         cm.message_type = aprot;
1557         cm.format = 32;
1558         cm.data.l[0] = a;
1559         cm.data.l[1] = CurrentTime;
1560         XSendEvent(display, win->id, False, 0L, (XEvent *)&cm);
1561 }
1562
1563 void
1564 config_win(struct ws_win *win, XConfigureRequestEvent  *ev)
1565 {
1566         XConfigureEvent         ce;
1567
1568         if (win == NULL)
1569                 return;
1570
1571         if (ev == NULL) {
1572                 DNPRINTF(SWM_D_MISC,
1573                     "config_win: win %lu x %d y %d w %d h %d\n",
1574                     win->id, win->g.x, win->g.y, win->g.w, win->g.h);
1575
1576                 ce.type = ConfigureNotify;
1577                 ce.display = display;
1578                 ce.event = win->id;
1579                 ce.window = win->id;
1580                 ce.x = win->g.x;
1581                 ce.y = win->g.y;
1582                 ce.width = win->g.w;
1583                 ce.height = win->g.h;
1584                 ce.border_width = border_width;
1585                 ce.above = None;
1586                 ce.override_redirect = False;
1587         } else {
1588                 DNPRINTF(SWM_D_MISC,
1589                     "config_win: ev win %lu x %d y %d w %d h %d\n",
1590                     ev->window, ev->x, ev->y, ev->width, ev->height);
1591                 ce.type = ConfigureNotify;
1592                 ce.display = ev->display;
1593                 ce.event = ev->window;
1594                 ce.window = ev->window;
1595                 ce.x = ev->x;
1596                 ce.y = ev->y;
1597                 ce.width = ev->width;
1598                 ce.height = ev->height;
1599                 ce.border_width = ev->border_width;
1600                 ce.above = ev->above;
1601                 ce.override_redirect = False;
1602         }
1603
1604         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
1605 }
1606
1607 int
1608 count_win(struct workspace *ws, int count_transient)
1609 {
1610         struct ws_win           *win;
1611         int                     count = 0;
1612
1613         TAILQ_FOREACH(win, &ws->winlist, entry) {
1614                 if (count_transient == 0 && win->floating)
1615                         continue;
1616                 if (count_transient == 0 && win->transient)
1617                         continue;
1618                 if (win->iconic)
1619                         continue;
1620                 count++;
1621         }
1622         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
1623
1624         return (count);
1625 }
1626
1627 void
1628 quit(struct swm_region *r, union arg *args)
1629 {
1630         DNPRINTF(SWM_D_MISC, "quit\n");
1631         running = 0;
1632 }
1633
1634 void
1635 unmap_window(struct ws_win *win)
1636 {
1637         if (win == NULL)
1638                 return;
1639
1640         /* don't unmap again */
1641         if (getstate(win->id) == IconicState)
1642                 return;
1643
1644         set_win_state(win, IconicState);
1645
1646         XUnmapWindow(display, win->id);
1647         XSetWindowBorder(display, win->id,
1648             win->s->c[SWM_S_COLOR_UNFOCUS].color);
1649 }
1650
1651 void
1652 unmap_all(void)
1653 {
1654         struct ws_win           *win;
1655         int                     i, j;
1656
1657         for (i = 0; i < ScreenCount(display); i++)
1658                 for (j = 0; j < SWM_WS_MAX; j++)
1659                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1660                                 unmap_window(win);
1661 }
1662
1663 void
1664 fake_keypress(struct ws_win *win, int keysym, int modifiers)
1665 {
1666         XKeyEvent event;
1667
1668         if (win == NULL)
1669                 return;
1670
1671         event.display = display;        /* Ignored, but what the hell */
1672         event.window = win->id;
1673         event.root = win->s->root;
1674         event.subwindow = None;
1675         event.time = CurrentTime;
1676         event.x = win->g.x;
1677         event.y = win->g.y;
1678         event.x_root = 1;
1679         event.y_root = 1;
1680         event.same_screen = True;
1681         event.keycode = XKeysymToKeycode(display, keysym);
1682         event.state = modifiers;
1683
1684         event.type = KeyPress;
1685         XSendEvent(event.display, event.window, True,
1686             KeyPressMask, (XEvent *)&event);
1687
1688         event.type = KeyRelease;
1689         XSendEvent(event.display, event.window, True,
1690             KeyPressMask, (XEvent *)&event);
1691
1692 }
1693
1694 void
1695 restart(struct swm_region *r, union arg *args)
1696 {
1697         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
1698
1699         /* disable alarm because the following code may not be interrupted */
1700         alarm(0);
1701         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
1702                 errx(1, "can't disable alarm");
1703
1704         bar_extra_stop();
1705         bar_extra = 1;
1706         unmap_all();
1707         XCloseDisplay(display);
1708         execvp(start_argv[0], start_argv);
1709         fprintf(stderr, "execvp failed\n");
1710         perror(" failed");
1711         quit(NULL, NULL);
1712 }
1713
1714 struct swm_region *
1715 root_to_region(Window root)
1716 {
1717         struct swm_region       *r = NULL;
1718         Window                  rr, cr;
1719         int                     i, x, y, wx, wy;
1720         unsigned int            mask;
1721
1722         for (i = 0; i < ScreenCount(display); i++)
1723                 if (screens[i].root == root)
1724                         break;
1725
1726         if (XQueryPointer(display, screens[i].root,
1727             &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
1728                 /* choose a region based on pointer location */
1729                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1730                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
1731                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
1732                                 break;
1733         }
1734
1735         if (r == NULL)
1736                 r = TAILQ_FIRST(&screens[i].rl);
1737
1738         return (r);
1739 }
1740
1741 struct ws_win *
1742 find_unmanaged_window(Window id)
1743 {
1744         struct ws_win           *win;
1745         int                     i, j;
1746
1747         for (i = 0; i < ScreenCount(display); i++)
1748                 for (j = 0; j < SWM_WS_MAX; j++)
1749                         TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
1750                             entry)
1751                                 if (id == win->id)
1752                                         return (win);
1753         return (NULL);
1754 }
1755
1756 struct ws_win *
1757 find_window(Window id)
1758 {
1759         struct ws_win           *win;
1760         Window                  wrr, wpr, *wcr = NULL;
1761         int                     i, j;
1762         unsigned int            nc;
1763
1764         for (i = 0; i < ScreenCount(display); i++)
1765                 for (j = 0; j < SWM_WS_MAX; j++)
1766                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1767                                 if (id == win->id)
1768                                         return (win);
1769
1770         /* if we were looking for the parent return that window instead */
1771         if (XQueryTree(display, id, &wrr, &wpr, &wcr, &nc) == 0)
1772                 return (NULL);
1773         if (wcr)
1774                 XFree(wcr);
1775
1776         /* ignore not found and root */
1777         if (wpr == 0 || wrr == wpr)
1778                 return (NULL);
1779
1780         /* look for parent */
1781         for (i = 0; i < ScreenCount(display); i++)
1782                 for (j = 0; j < SWM_WS_MAX; j++)
1783                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1784                                 if (wpr == win->id)
1785                                         return (win);
1786
1787         return (NULL);
1788 }
1789
1790 void
1791 spawn(int ws_idx, union arg *args, int close_fd)
1792 {
1793         int                     fd;
1794         char                    *ret = NULL;
1795
1796         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
1797
1798         if (display)
1799                 close(ConnectionNumber(display));
1800
1801         setenv("LD_PRELOAD", SWM_LIB, 1);
1802
1803         if (asprintf(&ret, "%d", ws_idx) == -1) {
1804                 perror("_SWM_WS");
1805                 _exit(1);
1806         }
1807         setenv("_SWM_WS", ret, 1);
1808         free(ret);
1809         ret = NULL;
1810
1811         if (asprintf(&ret, "%d", getpid()) == -1) {
1812                 perror("_SWM_PID");
1813                 _exit(1);
1814         }
1815         setenv("_SWM_PID", ret, 1);
1816         free(ret);
1817         ret = NULL;
1818
1819         if (setsid() == -1) {
1820                 perror("setsid");
1821                 _exit(1);
1822         }
1823
1824         if (close_fd) {
1825                 /*
1826                  * close stdin and stdout to prevent interaction between apps
1827                  * and the baraction script
1828                  * leave stderr open to record errors
1829                 */
1830                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
1831                         perror("open");
1832                         _exit(1);
1833                 }
1834                 dup2(fd, STDIN_FILENO);
1835                 dup2(fd, STDOUT_FILENO);
1836                 if (fd > 2)
1837                         close(fd);
1838         }
1839
1840         execvp(args->argv[0], args->argv);
1841
1842         perror("execvp");
1843         _exit(1);
1844 }
1845
1846 void
1847 spawnterm(struct swm_region *r, union arg *args)
1848 {
1849         DNPRINTF(SWM_D_MISC, "spawnterm\n");
1850
1851         if (fork() == 0) {
1852                 if (term_width)
1853                         setenv("_SWM_XTERM_FONTADJ", "", 1);
1854                 spawn(r->ws->idx, args, 1);
1855         }
1856 }
1857
1858 void
1859 kill_refs(struct ws_win *win)
1860 {
1861         int                     i, x;
1862         struct swm_region       *r;
1863         struct workspace        *ws;
1864
1865         if (win == NULL)
1866                 return;
1867
1868         for (i = 0; i < ScreenCount(display); i++)
1869                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1870                         for (x = 0; x < SWM_WS_MAX; x++) {
1871                                 ws = &r->s->ws[x];
1872                                 if (win == ws->focus)
1873                                         ws->focus = NULL;
1874                                 if (win == ws->focus_prev)
1875                                         ws->focus_prev = NULL;
1876                         }
1877 }
1878
1879 int
1880 validate_win(struct ws_win *testwin)
1881 {
1882         struct ws_win           *win;
1883         struct workspace        *ws;
1884         struct swm_region       *r;
1885         int                     i, x, foundit = 0;
1886
1887         if (testwin == NULL)
1888                 return (0);
1889
1890         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1891                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1892                         for (x = 0; x < SWM_WS_MAX; x++) {
1893                                 ws = &r->s->ws[x];
1894                                 TAILQ_FOREACH(win, &ws->winlist, entry)
1895                                         if (win == testwin)
1896                                                 return (0);
1897                         }
1898         return (1);
1899 }
1900
1901 int
1902 validate_ws(struct workspace *testws)
1903 {
1904         struct swm_region       *r;
1905         struct workspace        *ws;
1906         int                     foundit, i, x;
1907
1908         /* validate all ws */
1909         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1910                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1911                         for (x = 0; x < SWM_WS_MAX; x++) {
1912                                 ws = &r->s->ws[x];
1913                                 if (ws == testws)
1914                                         return (0);
1915                         }
1916         return (1);
1917 }
1918
1919 void
1920 unfocus_win(struct ws_win *win)
1921 {
1922         XEvent                  cne;
1923         Window                  none = None;
1924
1925         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", WINID(win));
1926
1927         if (win == NULL)
1928                 return;
1929         if (win->ws == NULL)
1930                 return;
1931
1932         if (validate_ws(win->ws))
1933                 return; /* XXX this gets hit with thunderbird, needs fixing */
1934
1935         if (win->ws->r == NULL)
1936                 return;
1937
1938         if (validate_win(win)) {
1939                 kill_refs(win);
1940                 return;
1941         }
1942
1943         if (win->ws->focus == win) {
1944                 win->ws->focus = NULL;
1945                 win->ws->focus_prev = win;
1946         }
1947
1948         if (validate_win(win->ws->focus)) {
1949                 kill_refs(win->ws->focus);
1950                 win->ws->focus = NULL;
1951         }
1952         if (validate_win(win->ws->focus_prev)) {
1953                 kill_refs(win->ws->focus_prev);
1954                 win->ws->focus_prev = NULL;
1955         }
1956
1957         /* drain all previous unfocus events */
1958         while (XCheckTypedEvent(display, FocusOut, &cne) == True)
1959                 ;
1960
1961         grabbuttons(win, 0);
1962         XSetWindowBorder(display, win->id,
1963             win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1964
1965         XChangeProperty(display, win->s->root,
1966             ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1967             PropModeReplace, (unsigned char *)&none,1);
1968 }
1969
1970 void
1971 unfocus_all(void)
1972 {
1973         struct ws_win           *win;
1974         int                     i, j;
1975
1976         DNPRINTF(SWM_D_FOCUS, "unfocus_all\n");
1977
1978         for (i = 0; i < ScreenCount(display); i++)
1979                 for (j = 0; j < SWM_WS_MAX; j++)
1980                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1981                                 unfocus_win(win);
1982 }
1983
1984 void
1985 focus_win(struct ws_win *win)
1986 {
1987         XEvent                  cne;
1988         Window                  cur_focus;
1989         int                     rr;
1990         struct ws_win           *cfw = NULL;
1991
1992
1993         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
1994
1995         if (win == NULL)
1996                 return;
1997         if (win->ws == NULL)
1998                 return;
1999
2000         if (validate_ws(win->ws))
2001                 return; /* XXX this gets hit with thunderbird, needs fixing */
2002
2003         if (validate_win(win)) {
2004                 kill_refs(win);
2005                 return;
2006         }
2007
2008         if (validate_win(win)) {
2009                 kill_refs(win);
2010                 return;
2011         }
2012
2013         XGetInputFocus(display, &cur_focus, &rr);
2014         if ((cfw = find_window(cur_focus)) != NULL)
2015                 unfocus_win(cfw);
2016         else {
2017                 /* use larger hammer since the window was killed somehow */
2018                 TAILQ_FOREACH(cfw, &win->ws->winlist, entry)
2019                         if (cfw->ws && cfw->ws->r && cfw->ws->r->s)
2020                                 XSetWindowBorder(display, cfw->id,
2021                                     cfw->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
2022         }
2023
2024         win->ws->focus = win;
2025
2026         if (win->ws->r != NULL) {
2027                 /* drain all previous focus events */
2028                 while (XCheckTypedEvent(display, FocusIn, &cne) == True)
2029                         ;
2030
2031                 if (win->java == 0)
2032                         XSetInputFocus(display, win->id,
2033                             RevertToParent, CurrentTime);
2034                 grabbuttons(win, 1);
2035                 XSetWindowBorder(display, win->id,
2036                     win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
2037                 if (win->ws->cur_layout->flags & SWM_L_MAPONFOCUS ||
2038                     win->ws->always_raise)
2039                         XMapRaised(display, win->id);
2040
2041                 XChangeProperty(display, win->s->root,
2042                     ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
2043                     PropModeReplace, (unsigned char *)&win->id,1);
2044         }
2045
2046         if (window_name_enabled)
2047                 bar_update();
2048 }
2049
2050 void
2051 switchws(struct swm_region *r, union arg *args)
2052 {
2053         int                     wsid = args->id, unmap_old = 0;
2054         struct swm_region       *this_r, *other_r;
2055         struct ws_win           *win;
2056         struct workspace        *new_ws, *old_ws;
2057         union arg               a;
2058
2059         if (!(r && r->s))
2060                 return;
2061
2062         this_r = r;
2063         old_ws = this_r->ws;
2064         new_ws = &this_r->s->ws[wsid];
2065
2066         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
2067             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
2068             old_ws->idx, wsid);
2069
2070         if (new_ws == NULL || old_ws == NULL)
2071                 return;
2072         if (new_ws == old_ws)
2073                 return;
2074
2075         other_r = new_ws->r;
2076         if (other_r == NULL) {
2077                 /* the other workspace is hidden, hide this one */
2078                 old_ws->r = NULL;
2079                 unmap_old = 1;
2080         } else {
2081                 /* the other ws is visible in another region, exchange them */
2082                 other_r->ws_prior = new_ws;
2083                 other_r->ws = old_ws;
2084                 old_ws->r = other_r;
2085         }
2086         this_r->ws_prior = old_ws;
2087         this_r->ws = new_ws;
2088         new_ws->r = this_r;
2089
2090         /* this is needed so that we can click on a window after a restart */
2091         unfocus_all();
2092
2093         stack();
2094         a.id = SWM_ARG_ID_FOCUSCUR;
2095         focus(new_ws->r, &a);
2096
2097         bar_update();
2098
2099         /* unmap old windows */
2100         if (unmap_old)
2101                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
2102                         unmap_window(win);
2103
2104         if (focus_mode == SWM_FOCUS_DEFAULT)
2105                 drain_enter_notify();
2106 }
2107
2108 void
2109 cyclews(struct swm_region *r, union arg *args)
2110 {
2111         union                   arg a;
2112         struct swm_screen       *s = r->s;
2113
2114         DNPRINTF(SWM_D_WS, "cyclews id %d "
2115             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
2116             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2117
2118         a.id = r->ws->idx;
2119         do {
2120                 switch (args->id) {
2121                 case SWM_ARG_ID_CYCLEWS_UP:
2122                         if (a.id < SWM_WS_MAX - 1)
2123                                 a.id++;
2124                         else
2125                                 a.id = 0;
2126                         break;
2127                 case SWM_ARG_ID_CYCLEWS_DOWN:
2128                         if (a.id > 0)
2129                                 a.id--;
2130                         else
2131                                 a.id = SWM_WS_MAX - 1;
2132                         break;
2133                 default:
2134                         return;
2135                 };
2136
2137                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
2138                         continue;
2139                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
2140                         continue;
2141
2142                 switchws(r, &a);
2143         } while (a.id != r->ws->idx);
2144 }
2145
2146 void
2147 priorws(struct swm_region *r, union arg *args)
2148 {
2149         union arg               a;
2150
2151         DNPRINTF(SWM_D_WS, "priorws id %d "
2152             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
2153             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2154
2155         if (r->ws_prior == NULL)
2156                 return;
2157
2158         a.id = r->ws_prior->idx;
2159         switchws(r, &a);
2160 }
2161
2162 void
2163 cyclescr(struct swm_region *r, union arg *args)
2164 {
2165         struct swm_region       *rr = NULL;
2166         union arg               a;
2167         int                     i, x, y;
2168
2169         /* do nothing if we don't have more than one screen */
2170         if (!(ScreenCount(display) > 1 || outputs > 1))
2171                 return;
2172
2173         i = r->s->idx;
2174         switch (args->id) {
2175         case SWM_ARG_ID_CYCLESC_UP:
2176                 rr = TAILQ_NEXT(r, entry);
2177                 if (rr == NULL)
2178                         rr = TAILQ_FIRST(&screens[i].rl);
2179                 break;
2180         case SWM_ARG_ID_CYCLESC_DOWN:
2181                 rr = TAILQ_PREV(r, swm_region_list, entry);
2182                 if (rr == NULL)
2183                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2184                 break;
2185         default:
2186                 return;
2187         };
2188         if (rr == NULL)
2189                 return;
2190
2191         /* move mouse to region */
2192         x = rr->g.x + 1;
2193         y = rr->g.y + 1 + (bar_enabled ? bar_height : 0);
2194         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2195
2196         a.id = SWM_ARG_ID_FOCUSCUR;
2197         focus(rr, &a);
2198
2199         if (rr->ws->focus) {
2200                 /* move to focus window */
2201                 x = rr->ws->focus->g.x + 1;
2202                 y = rr->ws->focus->g.y + 1;
2203                 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2204         }
2205 }
2206
2207 void
2208 sort_windows(struct ws_win_list *wl)
2209 {
2210         struct ws_win           *win, *parent, *nxt;
2211
2212         if (wl == NULL)
2213                 return;
2214
2215         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
2216                 nxt = TAILQ_NEXT(win, entry);
2217                 if (win->transient) {
2218                         parent = find_window(win->transient);
2219                         if (parent == NULL) {
2220                                 fprintf(stderr, "not possible bug\n");
2221                                 continue;
2222                         }
2223                         TAILQ_REMOVE(wl, win, entry);
2224                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
2225                 }
2226         }
2227
2228 }
2229
2230 void
2231 swapwin(struct swm_region *r, union arg *args)
2232 {
2233         struct ws_win           *target, *source;
2234         struct ws_win           *cur_focus;
2235         struct ws_win_list      *wl;
2236
2237
2238         DNPRINTF(SWM_D_WS, "swapwin id %d "
2239             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
2240             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2241
2242         cur_focus = r->ws->focus;
2243         if (cur_focus == NULL)
2244                 return;
2245
2246         source = cur_focus;
2247         wl = &source->ws->winlist;
2248
2249         switch (args->id) {
2250         case SWM_ARG_ID_SWAPPREV:
2251                 if (source->transient)
2252                         source = find_window(source->transient);
2253                 target = TAILQ_PREV(source, ws_win_list, entry);
2254                 if (target && target->transient)
2255                         target = find_window(target->transient);
2256                 TAILQ_REMOVE(wl, source, entry);
2257                 if (target == NULL)
2258                         TAILQ_INSERT_TAIL(wl, source, entry);
2259                 else
2260                         TAILQ_INSERT_BEFORE(target, source, entry);
2261                 break;
2262         case SWM_ARG_ID_SWAPNEXT:
2263                 target = TAILQ_NEXT(source, entry);
2264                 /* move the parent and let the sort handle the move */
2265                 if (source->transient)
2266                         source = find_window(source->transient);
2267                 TAILQ_REMOVE(wl, source, entry);
2268                 if (target == NULL)
2269                         TAILQ_INSERT_HEAD(wl, source, entry);
2270                 else
2271                         TAILQ_INSERT_AFTER(wl, target, source, entry);
2272                 break;
2273         case SWM_ARG_ID_SWAPMAIN:
2274                 target = TAILQ_FIRST(wl);
2275                 if (target == source) {
2276                         if (source->ws->focus_prev != NULL &&
2277                             source->ws->focus_prev != target)
2278
2279                                 source = source->ws->focus_prev;
2280                         else
2281                                 return;
2282                 }
2283                 if (target == NULL || source == NULL)
2284                         return;
2285                 source->ws->focus_prev = target;
2286                 TAILQ_REMOVE(wl, target, entry);
2287                 TAILQ_INSERT_BEFORE(source, target, entry);
2288                 TAILQ_REMOVE(wl, source, entry);
2289                 TAILQ_INSERT_HEAD(wl, source, entry);
2290                 break;
2291         case SWM_ARG_ID_MOVELAST:
2292                 TAILQ_REMOVE(wl, source, entry);
2293                 TAILQ_INSERT_TAIL(wl, source, entry);
2294                 break;
2295         default:
2296                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
2297                 return;
2298         }
2299
2300         sort_windows(wl);
2301
2302         stack();
2303 }
2304
2305 void
2306 focus_prev(struct ws_win *win)
2307 {
2308         struct ws_win           *winfocus = NULL, *winlostfocus = NULL;
2309         struct ws_win           *cur_focus = NULL;
2310         struct ws_win_list      *wl = NULL;
2311         struct workspace        *ws = NULL;
2312
2313         DNPRINTF(SWM_D_FOCUS, "focus_prev: id %lu\n", WINID(win));
2314
2315         if (!(win && win->ws))
2316                 return;
2317
2318         ws = win->ws;
2319         wl = &ws->winlist;
2320         cur_focus = ws->focus;
2321         winlostfocus = cur_focus;
2322
2323         /* pickle, just focus on whatever */
2324         if (cur_focus == NULL) {
2325                 /* use prev_focus if valid */
2326                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
2327                     find_window(WINID(ws->focus_prev)))
2328                         winfocus = ws->focus_prev;
2329                 if (winfocus == NULL)
2330                         winfocus = TAILQ_FIRST(wl);
2331                 goto done;
2332         }
2333
2334         /* if transient focus on parent */
2335         if (cur_focus->transient) {
2336                 winfocus = find_window(cur_focus->transient);
2337                 goto done;
2338         }
2339
2340         /* if in max_stack try harder */
2341         if ((win->quirks & SWM_Q_FOCUSPREV) ||
2342             (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
2343                 if (cur_focus != ws->focus_prev)
2344                         winfocus = ws->focus_prev;
2345                 else if (cur_focus != ws->focus)
2346                         winfocus = ws->focus;
2347                 else
2348                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
2349                 if (winfocus)
2350                         goto done;
2351         }
2352
2353         if (cur_focus == win)
2354                 winfocus = TAILQ_PREV(win, ws_win_list, entry);
2355         if (winfocus == NULL)
2356                 winfocus = TAILQ_LAST(wl, ws_win_list);
2357         if (winfocus == NULL || winfocus == win)
2358                 winfocus = TAILQ_NEXT(cur_focus, entry);
2359 done:
2360         if (winfocus == winlostfocus || winfocus == NULL)
2361                 return;
2362
2363         focus_magic(winfocus);
2364 }
2365
2366 void
2367 focus(struct swm_region *r, union arg *args)
2368 {
2369         struct ws_win           *winfocus = NULL, *winlostfocus = NULL, *head;
2370         struct ws_win           *cur_focus = NULL;
2371         struct ws_win_list      *wl = NULL;
2372         struct workspace        *ws = NULL;
2373
2374         if (!(r && r->ws))
2375                 return;
2376
2377         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
2378
2379         /* treat FOCUS_CUR special */
2380         if (args->id == SWM_ARG_ID_FOCUSCUR) {
2381                 if (r->ws->focus && r->ws->focus->iconic == 0)
2382                         winfocus = r->ws->focus;
2383                 else if (r->ws->focus_prev && r->ws->focus_prev->iconic == 0)
2384                         winfocus = r->ws->focus_prev;
2385                 else
2386                         TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
2387                                 if (winfocus->iconic == 0)
2388                                         break;
2389
2390                 focus_magic(winfocus);
2391                 return;
2392         }
2393
2394         if ((cur_focus = r->ws->focus) == NULL)
2395                 return;
2396         ws = r->ws;
2397         wl = &ws->winlist;
2398
2399         winlostfocus = cur_focus;
2400
2401         switch (args->id) {
2402         case SWM_ARG_ID_FOCUSPREV:
2403                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
2404                 if (head == NULL)
2405                         head = TAILQ_LAST(wl, ws_win_list);
2406                 winfocus = head;
2407                 if (WINID(winfocus) == cur_focus->transient) {
2408                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
2409                         if (head == NULL)
2410                                 head = TAILQ_LAST(wl, ws_win_list);
2411                         winfocus = head;
2412                 }
2413
2414                 /* skip iconics */
2415                 if (winfocus && winfocus->iconic) {
2416                         TAILQ_FOREACH_REVERSE(winfocus, wl, ws_win_list, entry)
2417                                 if (winfocus->iconic == 0)
2418                                         break;
2419                 }
2420                 break;
2421
2422         case SWM_ARG_ID_FOCUSNEXT:
2423                 head = TAILQ_NEXT(cur_focus, entry);
2424                 if (head == NULL)
2425                         head = TAILQ_FIRST(wl);
2426                 winfocus = head;
2427
2428                 /* skip iconics */
2429                 if (winfocus && winfocus->iconic) {
2430                         TAILQ_FOREACH(winfocus, wl, entry)
2431                                 if (winfocus->iconic == 0)
2432                                         break;
2433                 }
2434                 break;
2435
2436         case SWM_ARG_ID_FOCUSMAIN:
2437                 winfocus = TAILQ_FIRST(wl);
2438                 if (winfocus == cur_focus)
2439                         winfocus = cur_focus->ws->focus_prev;
2440                 break;
2441
2442         default:
2443                 return;
2444         }
2445         if (winfocus == winlostfocus || winfocus == NULL)
2446                 return;
2447
2448         focus_magic(winfocus);
2449 }
2450
2451 void
2452 cycle_layout(struct swm_region *r, union arg *args)
2453 {
2454         struct workspace        *ws = r->ws;
2455         struct ws_win           *winfocus;
2456         union arg               a;
2457
2458         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
2459
2460         winfocus = ws->focus;
2461
2462         ws->cur_layout++;
2463         if (ws->cur_layout->l_stack == NULL)
2464                 ws->cur_layout = &layouts[0];
2465
2466         stack();
2467         if (focus_mode == SWM_FOCUS_DEFAULT)
2468                 drain_enter_notify();
2469         a.id = SWM_ARG_ID_FOCUSCUR;
2470         focus(r, &a);
2471         bar_update();
2472 }
2473
2474 void
2475 stack_config(struct swm_region *r, union arg *args)
2476 {
2477         struct workspace        *ws = r->ws;
2478
2479         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
2480             args->id, ws->idx);
2481
2482         if (ws->cur_layout->l_config != NULL)
2483                 ws->cur_layout->l_config(ws, args->id);
2484
2485         if (args->id != SWM_ARG_ID_STACKINIT)
2486                 stack();
2487         bar_update();
2488 }
2489
2490 void
2491 stack(void) {
2492         struct swm_geometry     g;
2493         struct swm_region       *r;
2494         int                     i, j;
2495
2496         DNPRINTF(SWM_D_STACK, "stack\n");
2497
2498         for (i = 0; i < ScreenCount(display); i++) {
2499                 j = 0;
2500                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2501                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
2502                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
2503
2504                         /* start with screen geometry, adjust for bar */
2505                         g = r->g;
2506                         g.w -= 2 * border_width;
2507                         g.h -= 2 * border_width;
2508                         if (bar_enabled) {
2509                                 if (!bar_at_bottom)
2510                                         g.y += bar_height;
2511                                 g.h -= bar_height;
2512                         }
2513                         r->ws->cur_layout->l_stack(r->ws, &g);
2514                         r->ws->cur_layout->l_string(r->ws);
2515                         /* save r so we can track region changes */
2516                         r->ws->old_r = r;
2517                 }
2518         }
2519         if (font_adjusted)
2520                 font_adjusted--;
2521
2522         if (focus_mode == SWM_FOCUS_DEFAULT)
2523                 drain_enter_notify();
2524 }
2525
2526 void
2527 store_float_geom(struct ws_win *win, struct swm_region *r)
2528 {
2529         /* retain window geom and region geom */
2530         win->g_float.x = win->g.x;
2531         win->g_float.y = win->g.y;
2532         win->g_float.w = win->g.w;
2533         win->g_float.h = win->g.h;
2534         win->rg_float.x = r->g.x;
2535         win->rg_float.y = r->g.y;
2536         win->rg_float.w = r->g.w;
2537         win->rg_float.h = r->g.h;
2538         win->g_floatvalid = 1;
2539 }
2540
2541 void
2542 stack_floater(struct ws_win *win, struct swm_region *r)
2543 {
2544         unsigned int            mask;
2545         XWindowChanges          wc;
2546
2547         if (win == NULL)
2548                 return;
2549
2550         bzero(&wc, sizeof wc);
2551         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
2552
2553         /*
2554          * to allow windows to change their size (e.g. mplayer fs) only retrieve
2555          * geom on ws switches or return from max mode
2556          */
2557
2558         if (win->floatmaxed || (r != r->ws->old_r && win->g_floatvalid
2559             && !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
2560                 /*
2561                  * use stored g and rg to set relative position and size
2562                  * as in old region or before max stack mode
2563                  */
2564                 win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
2565                 win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
2566                 win->g.w = win->g_float.w;
2567                 win->g.h = win->g_float.h;
2568                 win->g_floatvalid = 0;
2569         }
2570
2571         win->floatmaxed = 0;
2572
2573         if ((win->quirks & SWM_Q_FULLSCREEN) && (win->g.w >= WIDTH(r)) &&
2574             (win->g.h >= HEIGHT(r)))
2575                 wc.border_width = 0;
2576         else
2577                 wc.border_width = border_width;
2578         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
2579                 win->g.w = (double)WIDTH(r) * dialog_ratio;
2580                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
2581         }
2582
2583         if (!win->manual) {
2584                 /*
2585                  * floaters and transients are auto-centred unless moved
2586                  * or resized
2587                  */
2588                 win->g.x = r->g.x + (WIDTH(r) - win->g.w) /
2589                     2 - wc.border_width;
2590                 win->g.y = r->g.y + (HEIGHT(r) - win->g.h) /
2591                     2 - wc.border_width;
2592         }
2593
2594         /* win can be outside r if new r smaller than old r */
2595         /* Ensure top left corner inside r (move probs otherwise) */
2596         if (win->g.x < r->g.x - wc.border_width)
2597                 win->g.x = r->g.x - wc.border_width;
2598         if (win->g.x > r->g.x + r->g.w - 1)
2599                 win->g.x = (win->g.w > r->g.w) ? r->g.x :
2600                     (r->g.x + r->g.w - win->g.w - 2 * wc.border_width);
2601         if (win->g.y < r->g.y - wc.border_width)
2602                 win->g.y = r->g.y - wc.border_width;
2603         if (win->g.y > r->g.y + r->g.h - 1)
2604                 win->g.y = (win->g.h > r->g.h) ? r->g.y :
2605                     (r->g.y + r->g.h - win->g.h - 2 * wc.border_width);
2606
2607         wc.x = win->g.x;
2608         wc.y = win->g.y;
2609         wc.width = win->g.w;
2610         wc.height = win->g.h;
2611
2612         /*
2613          * Retain floater and transient geometry for correct positioning
2614          * when ws changes region
2615          */
2616         if (!(win->ewmh_flags & EWMH_F_FULLSCREEN))
2617                 store_float_geom(win, r);
2618
2619         DNPRINTF(SWM_D_MISC, "stack_floater: win %lu x %d y %d w %d h %d\n",
2620             win->id, wc.x, wc.y, wc.width, wc.height);
2621
2622         XConfigureWindow(display, win->id, mask, &wc);
2623 }
2624
2625 /*
2626  * Send keystrokes to terminal to decrease/increase the font size as the
2627  * window size changes.
2628  */
2629 void
2630 adjust_font(struct ws_win *win)
2631 {
2632         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
2633             win->floating || win->transient)
2634                 return;
2635
2636         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
2637             win->g.w / win->sh.width_inc < term_width &&
2638             win->font_steps < SWM_MAX_FONT_STEPS) {
2639                 win->font_size_boundary[win->font_steps] =
2640                     (win->sh.width_inc * term_width) + win->sh.base_width;
2641                 win->font_steps++;
2642                 font_adjusted++;
2643                 win->last_inc = win->sh.width_inc;
2644                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
2645         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
2646             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
2647                 win->font_steps--;
2648                 font_adjusted++;
2649                 win->last_inc = win->sh.width_inc;
2650                 fake_keypress(win, XK_KP_Add, ShiftMask);
2651         }
2652 }
2653
2654 #define SWAPXY(g)       do {                            \
2655         int tmp;                                        \
2656         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
2657         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
2658 } while (0)
2659 void
2660 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
2661 {
2662         XWindowChanges          wc;
2663         XWindowAttributes       wa;
2664         struct swm_geometry     win_g, r_g = *g;
2665         struct ws_win           *win, *fs_win = 0;
2666         int                     i, j, s, stacks;
2667         int                     w_inc = 1, h_inc, w_base = 1, h_base;
2668         int                     hrh, extra = 0, h_slice, last_h = 0;
2669         int                     split, colno, winno, mwin, msize, mscale;
2670         int                     remain, missing, v_slice, reconfigure;
2671         unsigned int            mask;
2672
2673         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
2674             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
2675
2676         winno = count_win(ws, 0);
2677         if (winno == 0 && count_win(ws, 1) == 0)
2678                 return;
2679
2680         TAILQ_FOREACH(win, &ws->winlist, entry)
2681                 if (win->transient == 0 && win->floating == 0
2682                     && win->iconic == 0)
2683                         break;
2684
2685         if (win == NULL)
2686                 goto notiles;
2687
2688         if (rot) {
2689                 w_inc = win->sh.width_inc;
2690                 w_base = win->sh.base_width;
2691                 mwin = ws->l_state.horizontal_mwin;
2692                 mscale = ws->l_state.horizontal_msize;
2693                 stacks = ws->l_state.horizontal_stacks;
2694                 SWAPXY(&r_g);
2695         } else {
2696                 w_inc = win->sh.height_inc;
2697                 w_base = win->sh.base_height;
2698                 mwin = ws->l_state.vertical_mwin;
2699                 mscale = ws->l_state.vertical_msize;
2700                 stacks = ws->l_state.vertical_stacks;
2701         }
2702         win_g = r_g;
2703
2704         if (stacks > winno - mwin)
2705                 stacks = winno - mwin;
2706         if (stacks < 1)
2707                 stacks = 1;
2708
2709         h_slice = r_g.h / SWM_H_SLICE;
2710         if (mwin && winno > mwin) {
2711                 v_slice = r_g.w / SWM_V_SLICE;
2712
2713                 split = mwin;
2714                 colno = split;
2715                 win_g.w = v_slice * mscale;
2716
2717                 if (w_inc > 1 && w_inc < v_slice) {
2718                         /* adjust for window's requested size increment */
2719                         remain = (win_g.w - w_base) % w_inc;
2720                         missing = w_inc - remain;
2721                         win_g.w -= remain;
2722                         extra += remain;
2723                 }
2724
2725                 msize = win_g.w;
2726                 if (flip)
2727                         win_g.x += r_g.w - msize;
2728         } else {
2729                 msize = -2;
2730                 colno = split = winno / stacks;
2731                 win_g.w = ((r_g.w - (stacks * 2 * border_width) +
2732                     2 * border_width) / stacks);
2733         }
2734         hrh = r_g.h / colno;
2735         extra = r_g.h - (colno * hrh);
2736         win_g.h = hrh - 2 * border_width;
2737
2738         /*  stack all the tiled windows */
2739         i = j = 0, s = stacks;
2740         TAILQ_FOREACH(win, &ws->winlist, entry) {
2741                 if (win->transient != 0 || win->floating != 0)
2742                         continue;
2743                 if (win->iconic != 0)
2744                         continue;
2745
2746                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2747                         fs_win = win;
2748                         continue;
2749                 }
2750
2751                 if (split && i == split) {
2752                         colno = (winno - mwin) / stacks;
2753                         if (s <= (winno - mwin) % stacks)
2754                                 colno++;
2755                         split = split + colno;
2756                         hrh = (r_g.h / colno);
2757                         extra = r_g.h - (colno * hrh);
2758                         if (flip)
2759                                 win_g.x = r_g.x;
2760                         else
2761                                 win_g.x += win_g.w + 2 * border_width;
2762                         win_g.w = (r_g.w - msize -
2763                             (stacks * 2 * border_width)) / stacks;
2764                         if (s == 1)
2765                                 win_g.w += (r_g.w - msize -
2766                                     (stacks * 2 * border_width)) % stacks;
2767                         s--;
2768                         j = 0;
2769                 }
2770                 win_g.h = hrh - 2 * border_width;
2771                 if (rot) {
2772                         h_inc = win->sh.width_inc;
2773                         h_base = win->sh.base_width;
2774                 } else {
2775                         h_inc = win->sh.height_inc;
2776                         h_base = win->sh.base_height;
2777                 }
2778                 if (j == colno - 1) {
2779                         win_g.h = hrh + extra;
2780                 } else if (h_inc > 1 && h_inc < h_slice) {
2781                         /* adjust for window's requested size increment */
2782                         remain = (win_g.h - h_base) % h_inc;
2783                         missing = h_inc - remain;
2784
2785                         if (missing <= extra || j == 0) {
2786                                 extra -= missing;
2787                                 win_g.h += missing;
2788                         } else {
2789                                 win_g.h -= remain;
2790                                 extra += remain;
2791                         }
2792                 }
2793
2794                 if (j == 0)
2795                         win_g.y = r_g.y;
2796                 else
2797                         win_g.y += last_h + 2 * border_width;
2798
2799                 bzero(&wc, sizeof wc);
2800                 if (disable_border && bar_enabled == 0 && winno == 1){
2801                         wc.border_width = 0;
2802                         win_g.w += 2 * border_width;
2803                         win_g.h += 2 * border_width;
2804                 } else
2805                         wc.border_width = border_width;
2806                 reconfigure = 0;
2807                 if (rot) {
2808                         if (win->g.x != win_g.y || win->g.y != win_g.x ||
2809                             win->g.w != win_g.h || win->g.h != win_g.w) {
2810                                 reconfigure = 1;
2811                                 win->g.x = wc.x = win_g.y;
2812                                 win->g.y = wc.y = win_g.x;
2813                                 win->g.w = wc.width = win_g.h;
2814                                 win->g.h = wc.height = win_g.w;
2815                         }
2816                 } else {
2817                         if (win->g.x != win_g.x || win->g.y != win_g.y ||
2818                             win->g.w != win_g.w || win->g.h != win_g.h) {
2819                                 reconfigure = 1;
2820                                 win->g.x = wc.x = win_g.x;
2821                                 win->g.y = wc.y = win_g.y;
2822                                 win->g.w = wc.width = win_g.w;
2823                                 win->g.h = wc.height = win_g.h;
2824                         }
2825                 }
2826                 if (reconfigure) {
2827                         adjust_font(win);
2828                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2829                         XConfigureWindow(display, win->id, mask, &wc);
2830                 }
2831
2832                 if (XGetWindowAttributes(display, win->id, &wa))
2833                         if (wa.map_state == IsUnmapped)
2834                                 XMapRaised(display, win->id);
2835
2836                 last_h = win_g.h;
2837                 i++;
2838                 j++;
2839         }
2840
2841 notiles:
2842         /* now, stack all the floaters and transients */
2843         TAILQ_FOREACH(win, &ws->winlist, entry) {
2844                 if (win->transient == 0 && win->floating == 0)
2845                         continue;
2846                 if (win->iconic == 1)
2847                         continue;
2848                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2849                         fs_win = win;
2850                         continue;
2851                 }
2852
2853                 stack_floater(win, ws->r);
2854                 XMapRaised(display, win->id);
2855         }
2856
2857         if (fs_win) {
2858                 stack_floater(fs_win, ws->r);
2859                 XMapRaised(display, fs_win->id);
2860         }
2861 }
2862
2863 void
2864 vertical_config(struct workspace *ws, int id)
2865 {
2866         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
2867
2868         switch (id) {
2869         case SWM_ARG_ID_STACKRESET:
2870         case SWM_ARG_ID_STACKINIT:
2871                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
2872                 ws->l_state.vertical_mwin = 1;
2873                 ws->l_state.vertical_stacks = 1;
2874                 break;
2875         case SWM_ARG_ID_MASTERSHRINK:
2876                 if (ws->l_state.vertical_msize > 1)
2877                         ws->l_state.vertical_msize--;
2878                 break;
2879         case SWM_ARG_ID_MASTERGROW:
2880                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
2881                         ws->l_state.vertical_msize++;
2882                 break;
2883         case SWM_ARG_ID_MASTERADD:
2884                 ws->l_state.vertical_mwin++;
2885                 break;
2886         case SWM_ARG_ID_MASTERDEL:
2887                 if (ws->l_state.vertical_mwin > 0)
2888                         ws->l_state.vertical_mwin--;
2889                 break;
2890         case SWM_ARG_ID_STACKINC:
2891                 ws->l_state.vertical_stacks++;
2892                 break;
2893         case SWM_ARG_ID_STACKDEC:
2894                 if (ws->l_state.vertical_stacks > 1)
2895                         ws->l_state.vertical_stacks--;
2896                 break;
2897         default:
2898                 return;
2899         }
2900 }
2901
2902 void
2903 vertical_stack(struct workspace *ws, struct swm_geometry *g)
2904 {
2905         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
2906
2907         stack_master(ws, g, 0, 0);
2908 }
2909
2910 void
2911 horizontal_config(struct workspace *ws, int id)
2912 {
2913         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
2914
2915         switch (id) {
2916         case SWM_ARG_ID_STACKRESET:
2917         case SWM_ARG_ID_STACKINIT:
2918                 ws->l_state.horizontal_mwin = 1;
2919                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
2920                 ws->l_state.horizontal_stacks = 1;
2921                 break;
2922         case SWM_ARG_ID_MASTERSHRINK:
2923                 if (ws->l_state.horizontal_msize > 1)
2924                         ws->l_state.horizontal_msize--;
2925                 break;
2926         case SWM_ARG_ID_MASTERGROW:
2927                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
2928                         ws->l_state.horizontal_msize++;
2929                 break;
2930         case SWM_ARG_ID_MASTERADD:
2931                 ws->l_state.horizontal_mwin++;
2932                 break;
2933         case SWM_ARG_ID_MASTERDEL:
2934                 if (ws->l_state.horizontal_mwin > 0)
2935                         ws->l_state.horizontal_mwin--;
2936                 break;
2937         case SWM_ARG_ID_STACKINC:
2938                 ws->l_state.horizontal_stacks++;
2939                 break;
2940         case SWM_ARG_ID_STACKDEC:
2941                 if (ws->l_state.horizontal_stacks > 1)
2942                         ws->l_state.horizontal_stacks--;
2943                 break;
2944         default:
2945                 return;
2946         }
2947 }
2948
2949 void
2950 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
2951 {
2952         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
2953
2954         stack_master(ws, g, 1, 0);
2955 }
2956
2957 /* fullscreen view */
2958 void
2959 max_stack(struct workspace *ws, struct swm_geometry *g)
2960 {
2961         XWindowChanges          wc;
2962         struct swm_geometry     gg = *g;
2963         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
2964         unsigned int            mask;
2965         int                     winno;
2966
2967         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
2968
2969         if (ws == NULL)
2970                 return;
2971
2972         winno = count_win(ws, 0);
2973         if (winno == 0 && count_win(ws, 1) == 0)
2974                 return;
2975
2976         TAILQ_FOREACH(win, &ws->winlist, entry) {
2977                 if (win->transient) {
2978                         wintrans = win;
2979                         parent = find_window(win->transient);
2980                         continue;
2981                 }
2982
2983                 if (win->floating && win->floatmaxed == 0 ) {
2984                         /*
2985                          * retain geometry for retrieval on exit from
2986                          * max_stack mode
2987                          */
2988                         store_float_geom(win, ws->r);
2989                         win->floatmaxed = 1;
2990                 }
2991
2992                 /* only reconfigure if necessary */
2993                 if (win->g.x != gg.x || win->g.y != gg.y || win->g.w != gg.w ||
2994                     win->g.h != gg.h) {
2995                         bzero(&wc, sizeof wc);
2996                         win->g.x = wc.x = gg.x;
2997                         win->g.y = wc.y = gg.y;
2998                         if (bar_enabled){
2999                                 wc.border_width = border_width;
3000                                 win->g.w = wc.width = gg.w;
3001                                 win->g.h = wc.height = gg.h;
3002                         } else {
3003                                 wc.border_width = 0;
3004                                 win->g.w = wc.width = gg.w + 2 * border_width;
3005                                 win->g.h = wc.height = gg.h + 2 * border_width;
3006                         }
3007                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
3008                         XConfigureWindow(display, win->id, mask, &wc);
3009                 }
3010                 /* unmap only if we don't have multi screen */
3011                 if (win != ws->focus)
3012                         if (!(ScreenCount(display) > 1 || outputs > 1))
3013                                 unmap_window(win);
3014         }
3015
3016         /* put the last transient on top */
3017         if (wintrans) {
3018                 if (parent)
3019                         XMapRaised(display, parent->id);
3020                 stack_floater(wintrans, ws->r);
3021                 focus_magic(wintrans);
3022         }
3023 }
3024
3025 void
3026 send_to_ws(struct swm_region *r, union arg *args)
3027 {
3028         int                     wsid = args->id;
3029         struct ws_win           *win = NULL, *parent;
3030         struct workspace        *ws, *nws;
3031         Atom                    ws_idx_atom = 0;
3032         unsigned char           ws_idx_str[SWM_PROPLEN];
3033         union arg               a;
3034
3035         if (r && r->ws)
3036                 win = r->ws->focus;
3037         else
3038                 return;
3039         if (win == NULL)
3040                 return;
3041         if (win->ws->idx == wsid)
3042                 return;
3043
3044         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
3045
3046         ws = win->ws;
3047         nws = &win->s->ws[wsid];
3048
3049         a.id = SWM_ARG_ID_FOCUSPREV;
3050         focus(r, &a);
3051         if (win->transient) {
3052                 parent = find_window(win->transient);
3053                 if (parent) {
3054                         unmap_window(parent);
3055                         TAILQ_REMOVE(&ws->winlist, parent, entry);
3056                         TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
3057                         parent->ws = nws;
3058                 }
3059         }
3060         unmap_window(win);
3061         TAILQ_REMOVE(&ws->winlist, win, entry);
3062         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
3063         win->ws = nws;
3064
3065         /* Try to update the window's workspace property */
3066         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
3067         if (ws_idx_atom &&
3068             snprintf((char *)ws_idx_str, SWM_PROPLEN, "%d", nws->idx) <
3069                 SWM_PROPLEN) {
3070                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
3071                     ws_idx_str);
3072                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
3073                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
3074         }
3075
3076         stack();
3077 }
3078
3079 void
3080 pressbutton(struct swm_region *r, union arg *args)
3081 {
3082         XTestFakeButtonEvent(display, args->id, True, CurrentTime);
3083         XTestFakeButtonEvent(display, args->id, False, CurrentTime);
3084 }
3085
3086 void
3087 raise_toggle(struct swm_region *r, union arg *args)
3088 {
3089         if (r && r->ws == NULL)
3090                 return;
3091
3092         r->ws->always_raise = !r->ws->always_raise;
3093
3094         /* bring floaters back to top */
3095         if (r->ws->always_raise == 0)
3096                 stack();
3097 }
3098
3099 void
3100 iconify(struct swm_region *r, union arg *args)
3101 {
3102         union arg a;
3103
3104         if (r->ws->focus == NULL)
3105                 return;
3106         unmap_window(r->ws->focus);
3107         update_iconic(r->ws->focus, 1);
3108         stack();
3109         if (focus_mode == SWM_FOCUS_DEFAULT)
3110                 drain_enter_notify();
3111         r->ws->focus = NULL;
3112         a.id = SWM_ARG_ID_FOCUSCUR;
3113         focus(r, &a);
3114 }
3115
3116 unsigned char *
3117 get_win_name(Display *dpy, Window win, Atom wname, Atom stype,
3118     unsigned long *slen)
3119 {
3120         int                     status, retfmt;
3121         unsigned long           nitems, nbytes, nextra;
3122         unsigned char           *prop = NULL;
3123         Atom                    rettype;
3124
3125         status = XGetWindowProperty(dpy, win, wname, 0L, 0L, False, stype,
3126             &rettype, &retfmt,  &nitems, &nbytes, &prop);
3127         if (status != Success)
3128                 return (NULL);
3129         XFree(prop);
3130
3131         status = XGetWindowProperty(dpy, win, wname, 0L, nbytes, False,
3132             stype, &rettype, &retfmt, &nitems, &nextra, &prop);
3133         if (status != Success) {
3134                 XFree(prop);
3135                 return (NULL);
3136         }
3137         if (rettype != stype) {
3138                 XFree(prop);
3139                 return (NULL);
3140         }
3141         *slen = nitems;
3142         return (prop);
3143 }
3144
3145 void
3146 uniconify(struct swm_region *r, union arg *args)
3147 {
3148         struct ws_win           *win;
3149         FILE                    *lfile;
3150         unsigned char           *name;
3151         int                     count = 0;
3152         unsigned long           len;
3153
3154         DNPRINTF(SWM_D_MISC, "uniconify\n");
3155
3156         if (r && r->ws == NULL)
3157                 return;
3158
3159         /* make sure we have anything to uniconify */
3160         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3161                 if (win->ws == NULL)
3162                         continue; /* should never happen */
3163                 if (win->iconic == 0)
3164                         continue;
3165                 count++;
3166         }
3167         if (count == 0)
3168                 return;
3169
3170         search_r = r;
3171
3172         spawn_select(r, args, "uniconify", &searchpid);
3173
3174         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3175                 return;
3176
3177         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3178                 if (win->ws == NULL)
3179                         continue; /* should never happen */
3180                 if (win->iconic == 0)
3181                         continue;
3182
3183                 name = get_win_name(display, win->id, a_wmname, a_string,
3184                     &len);
3185                 if (name == NULL)
3186                         continue;
3187                 fprintf(lfile, "%s.%lu\n", name, win->id);
3188                 XFree(name);
3189         }
3190
3191         fclose(lfile);
3192 }
3193
3194 #define MAX_RESP_LEN    1024
3195
3196 void
3197 search_do_resp(void)
3198 {
3199         ssize_t                 rbytes;
3200         struct ws_win           *win;
3201         unsigned char           *name;
3202         char                    *resp, *s;
3203         unsigned long           len;
3204
3205         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
3206
3207         search_resp = 0;
3208         searchpid = 0;
3209
3210         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
3211                 fprintf(stderr, "search: calloc\n");
3212                 return;
3213         }
3214
3215         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
3216         if (rbytes <= 0) {
3217                 fprintf(stderr, "search: read error: %s\n", strerror(errno));
3218                 goto done;
3219         }
3220         resp[rbytes] = '\0';
3221         len = strlen(resp);
3222
3223         DNPRINTF(SWM_D_MISC, "search_do_resp: resp %s\n", resp);
3224         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
3225                 if (win->iconic == 0)
3226                         continue;
3227                 name = get_win_name(display, win->id, a_wmname, a_string, &len);
3228                 if (name == NULL)
3229                         continue;
3230                 if (asprintf(&s, "%s.%lu", name, win->id) == -1) {
3231                         XFree(name);
3232                         continue;
3233                 }
3234                 XFree(name);
3235                 if (strncmp(s, resp, len) == 0) {
3236                         /* XXX this should be a callback to generalize */
3237                         update_iconic(win, 0);
3238                         free(s);
3239                         break;
3240                 }
3241                 free(s);
3242         }
3243 done:
3244         free(resp);
3245 }
3246
3247 void
3248 wkill(struct swm_region *r, union arg *args)
3249 {
3250         DNPRINTF(SWM_D_MISC, "wkill %d\n", args->id);
3251
3252         if (r->ws->focus == NULL)
3253                 return;
3254
3255         if (args->id == SWM_ARG_ID_KILLWINDOW)
3256                 XKillClient(display, r->ws->focus->id);
3257         else
3258                 if (r->ws->focus->can_delete)
3259                         client_msg(r->ws->focus, adelete);
3260 }
3261
3262
3263 int
3264 floating_toggle_win(struct ws_win *win)
3265 {
3266         struct swm_region       *r;
3267
3268         if (win == NULL)
3269                 return 0;
3270
3271         if (!win->ws->r)
3272                 return 0;
3273
3274         r = win->ws->r;
3275
3276         /* reject floating toggles in max stack mode */
3277         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
3278                 return 0;
3279
3280         if (win->floating) {
3281                 if (!win->floatmaxed) {
3282                         /* retain position for refloat */
3283                         store_float_geom(win, r);
3284                 }
3285                 win->floating = 0;
3286         } else {
3287                 if (win->g_floatvalid) {
3288                         /* refloat at last floating relative position */
3289                         win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
3290                         win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
3291                         win->g.w = win->g_float.w;
3292                         win->g.h = win->g_float.h;
3293                 }
3294                 win->floating = 1;
3295         }
3296
3297         ewmh_update_actions(win);
3298
3299         return 1;
3300 }
3301
3302 void
3303 floating_toggle(struct swm_region *r, union arg *args)
3304 {
3305         struct ws_win           *win = r->ws->focus;
3306         union arg               a;
3307
3308         if (win == NULL)
3309                 return;
3310
3311         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3312             _NET_WM_STATE_TOGGLE);
3313
3314         stack();
3315         if (focus_mode == SWM_FOCUS_DEFAULT)
3316                 drain_enter_notify();
3317
3318         if (win == win->ws->focus) {
3319                 a.id = SWM_ARG_ID_FOCUSCUR;
3320                 focus(win->ws->r, &a);
3321         }
3322 }
3323
3324 void
3325 resize_window(struct ws_win *win, int center)
3326 {
3327         unsigned int            mask;
3328         XWindowChanges          wc;
3329         struct swm_region       *r;
3330
3331         r = root_to_region(win->wa.root);
3332         bzero(&wc, sizeof wc);
3333         mask = CWBorderWidth | CWWidth | CWHeight;
3334         wc.border_width = border_width;
3335         wc.width = win->g.w;
3336         wc.height = win->g.h;
3337         if (center == SWM_ARG_ID_CENTER) {
3338                 wc.x = (WIDTH(r) - win->g.w) / 2 - border_width;
3339                 wc.y = (HEIGHT(r) - win->g.h) / 2 - border_width;
3340                 mask |= CWX | CWY;
3341         }
3342
3343         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
3344             win->id, wc.x, wc.y, wc.width, wc.height);
3345
3346         XConfigureWindow(display, win->id, mask, &wc);
3347 }
3348
3349 #define SWM_RESIZE_STEPS        (50)
3350
3351 void
3352 resize(struct ws_win *win, union arg *args)
3353 {
3354         XEvent                  ev;
3355         Time                    time = 0;
3356         struct swm_region       *r = win->ws->r;
3357         int                     relx, rely;
3358         int                     resize_step = 0;
3359
3360
3361         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %lu\n",
3362             win->id, win->floating, win->transient);
3363
3364         if (!(win->transient != 0 || win->floating != 0))
3365                 return;
3366
3367         /* reject resizes in max mode for floaters (transient ok) */
3368         if (win->floatmaxed)
3369                 return;
3370
3371         win->manual = 1;
3372         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3373             _NET_WM_STATE_ADD);
3374
3375         stack();
3376
3377         switch (args->id) {
3378         case SWM_ARG_ID_WIDTHSHRINK:
3379                 win->g.w -= SWM_RESIZE_STEPS;
3380                 resize_step = 1;
3381                 break;
3382         case SWM_ARG_ID_WIDTHGROW:
3383                 win->g.w += SWM_RESIZE_STEPS;
3384                 resize_step = 1;
3385                 break;
3386         case SWM_ARG_ID_HEIGHTSHRINK:
3387                 win->g.h -= SWM_RESIZE_STEPS;
3388                 resize_step = 1;
3389                 break;
3390         case SWM_ARG_ID_HEIGHTGROW:
3391                 win->g.h += SWM_RESIZE_STEPS;
3392                 resize_step = 1;
3393                 break;
3394         default:
3395                 break;
3396         }
3397         if (resize_step) {
3398                 resize_window(win, 0);
3399                 store_float_geom(win,r);
3400                 return;
3401         }
3402
3403         if (focus_mode == SWM_FOCUS_DEFAULT)
3404                 drain_enter_notify();
3405
3406         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3407             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3408                 return;
3409
3410         /* place pointer at bottom left corner or nearest point inside r */
3411         if ( win->g.x + win->g.w < r->g.x + r->g.w - 1)
3412                 relx = win->g.w - 1;
3413         else
3414                 relx = r->g.x + r->g.w - win->g.x - 1;
3415
3416         if ( win->g.y + win->g.h < r->g.y + r->g.h - 1)
3417                 rely = win->g.h - 1;
3418         else
3419                 rely = r->g.y + r->g.h - win->g.y - 1;
3420
3421         XWarpPointer(display, None, win->id, 0, 0, 0, 0, relx, rely);
3422         do {
3423                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3424                     SubstructureRedirectMask, &ev);
3425                 switch (ev.type) {
3426                 case ConfigureRequest:
3427                 case Expose:
3428                 case MapRequest:
3429                         handler[ev.type](&ev);
3430                         break;
3431                 case MotionNotify:
3432                         /* do not allow resize outside of region */
3433                         if (    ev.xmotion.x_root < r->g.x ||
3434                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3435                                 ev.xmotion.y_root < r->g.y ||
3436                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3437                                 continue;
3438
3439                         if (ev.xmotion.x <= 1)
3440                                 ev.xmotion.x = 1;
3441                         if (ev.xmotion.y <= 1)
3442                                 ev.xmotion.y = 1;
3443                         win->g.w = ev.xmotion.x + 1;
3444                         win->g.h = ev.xmotion.y + 1;
3445
3446                         /* not free, don't sync more than 120 times / second */
3447                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3448                                 time = ev.xmotion.time;
3449                                 XSync(display, False);
3450                                 resize_window(win, args->id);
3451                         }
3452                         break;
3453                 }
3454         } while (ev.type != ButtonRelease);
3455         if (time) {
3456                 XSync(display, False);
3457                 resize_window(win, args->id);
3458         }
3459         store_float_geom(win,r);
3460
3461         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
3462             win->g.h - 1);
3463         XUngrabPointer(display, CurrentTime);
3464
3465         /* drain events */
3466         drain_enter_notify();
3467 }
3468
3469 void
3470 resize_step(struct swm_region *r, union arg *args)
3471 {
3472         struct ws_win           *win = NULL;
3473
3474         if (r && r->ws)
3475                 win = r->ws->focus;
3476         else
3477                 return;
3478
3479         resize(win, args);
3480 }
3481
3482
3483 void
3484 move_window(struct ws_win *win)
3485 {
3486         unsigned int            mask;
3487         XWindowChanges          wc;
3488         struct swm_region       *r;
3489
3490         r = root_to_region(win->wa.root);
3491         bzero(&wc, sizeof wc);
3492         mask = CWX | CWY;
3493         wc.x = win->g.x;
3494         wc.y = win->g.y;
3495         wc.border_width = border_width;
3496
3497         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
3498             win->id, wc.x, wc.y, wc.width, wc.height);
3499
3500         XConfigureWindow(display, win->id, mask, &wc);
3501 }
3502
3503 #define SWM_MOVE_STEPS  (50)
3504
3505 void
3506 move(struct ws_win *win, union arg *args)
3507 {
3508         XEvent                  ev;
3509         Time                    time = 0;
3510         int                     move_step = 0;
3511         struct swm_region       *r = win->ws->r;
3512
3513         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %lu\n",
3514             win->id, win->floating, win->transient);
3515
3516         /* in max_stack mode should only move transients */
3517         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
3518                 return;
3519
3520         win->manual = 1;
3521         if (win->floating == 0 && !win->transient) {
3522                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3523                     _NET_WM_STATE_ADD);
3524         }
3525         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3526             _NET_WM_STATE_ADD);
3527
3528         stack();
3529
3530         move_step = 0;
3531         switch (args->id) {
3532         case SWM_ARG_ID_MOVELEFT:
3533                 win->g.x -= (SWM_MOVE_STEPS - border_width);
3534                 move_step = 1;
3535                 break;
3536         case SWM_ARG_ID_MOVERIGHT:
3537                 win->g.x += (SWM_MOVE_STEPS - border_width);
3538                 move_step = 1;
3539                 break;
3540         case SWM_ARG_ID_MOVEUP:
3541                 win->g.y -= (SWM_MOVE_STEPS - border_width);
3542                 move_step = 1;
3543                 break;
3544         case SWM_ARG_ID_MOVEDOWN:
3545                 win->g.y += (SWM_MOVE_STEPS - border_width);
3546                 move_step = 1;
3547                 break;
3548         default:
3549                 break;
3550         }
3551         if (move_step) {
3552                 move_window(win);
3553                 store_float_geom(win,r);
3554                 return;
3555         }
3556
3557
3558         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3559             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3560                 return;
3561         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3562         do {
3563                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3564                     SubstructureRedirectMask, &ev);
3565                 switch (ev.type) {
3566                 case ConfigureRequest:
3567                 case Expose:
3568                 case MapRequest:
3569                         handler[ev.type](&ev);
3570                         break;
3571                 case MotionNotify:
3572                         /* don't allow to move window origin out of region */
3573                         if (    ev.xmotion.x_root < r->g.x ||
3574                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3575                                 ev.xmotion.y_root < r->g.y ||
3576                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3577                                 continue;
3578
3579                         win->g.x = ev.xmotion.x_root - border_width;
3580                         win->g.y = ev.xmotion.y_root - border_width;
3581
3582                         /* not free, don't sync more than 120 times / second */
3583                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3584                                 time = ev.xmotion.time;
3585                                 XSync(display, False);
3586                                 move_window(win);
3587                         }
3588                         break;
3589                 }
3590         } while (ev.type != ButtonRelease);
3591         if (time) {
3592                 XSync(display, False);
3593                 move_window(win);
3594         }
3595         store_float_geom(win,r);
3596         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3597         XUngrabPointer(display, CurrentTime);
3598
3599         /* drain events */
3600         drain_enter_notify();
3601 }
3602
3603 void
3604 move_step(struct swm_region *r, union arg *args)
3605 {
3606         struct ws_win           *win = NULL;
3607
3608         if (r && r->ws)
3609                 win = r->ws->focus;
3610         else
3611                 return;
3612
3613         if (!(win->transient != 0 || win->floating != 0))
3614                 return;
3615
3616         move(win, args);
3617 }
3618
3619
3620 /* user/key callable function IDs */
3621 enum keyfuncid {
3622         kf_cycle_layout,
3623         kf_stack_reset,
3624         kf_master_shrink,
3625         kf_master_grow,
3626         kf_master_add,
3627         kf_master_del,
3628         kf_stack_inc,
3629         kf_stack_dec,
3630         kf_swap_main,
3631         kf_focus_next,
3632         kf_focus_prev,
3633         kf_swap_next,
3634         kf_swap_prev,
3635         kf_spawn_term,
3636         kf_spawn_menu,
3637         kf_quit,
3638         kf_restart,
3639         kf_focus_main,
3640         kf_ws_1,
3641         kf_ws_2,
3642         kf_ws_3,
3643         kf_ws_4,
3644         kf_ws_5,
3645         kf_ws_6,
3646         kf_ws_7,
3647         kf_ws_8,
3648         kf_ws_9,
3649         kf_ws_10,
3650         kf_ws_next,
3651         kf_ws_prev,
3652         kf_ws_prior,
3653         kf_screen_next,
3654         kf_screen_prev,
3655         kf_mvws_1,
3656         kf_mvws_2,
3657         kf_mvws_3,
3658         kf_mvws_4,
3659         kf_mvws_5,
3660         kf_mvws_6,
3661         kf_mvws_7,
3662         kf_mvws_8,
3663         kf_mvws_9,
3664         kf_mvws_10,
3665         kf_bar_toggle,
3666         kf_wind_kill,
3667         kf_wind_del,
3668         kf_screenshot_all,
3669         kf_screenshot_wind,
3670         kf_float_toggle,
3671         kf_version,
3672         kf_spawn_lock,
3673         kf_spawn_initscr,
3674         kf_spawn_custom,
3675         kf_iconify,
3676         kf_uniconify,
3677         kf_raise_toggle,
3678         kf_button2,
3679         kf_width_shrink,
3680         kf_width_grow,
3681         kf_height_shrink,
3682         kf_height_grow,
3683         kf_move_left,
3684         kf_move_right,
3685         kf_move_up,
3686         kf_move_down,
3687         kf_dumpwins, /* MUST BE LAST */
3688         kf_invalid
3689 };
3690
3691 /* key definitions */
3692 void
3693 dummykeyfunc(struct swm_region *r, union arg *args)
3694 {
3695 };
3696
3697 void
3698 legacyfunc(struct swm_region *r, union arg *args)
3699 {
3700 };
3701
3702 struct keyfunc {
3703         char                    name[SWM_FUNCNAME_LEN];
3704         void                    (*func)(struct swm_region *r, union arg *);
3705         union arg               args;
3706 } keyfuncs[kf_invalid + 1] = {
3707         /* name                 function        argument */
3708         { "cycle_layout",       cycle_layout,   {0} },
3709         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
3710         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
3711         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
3712         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
3713         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
3714         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
3715         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
3716         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
3717         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
3718         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
3719         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
3720         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
3721         { "spawn_term",         spawnterm,      {.argv = spawn_term} },
3722         { "spawn_menu",         legacyfunc,     {0} },
3723         { "quit",               quit,           {0} },
3724         { "restart",            restart,        {0} },
3725         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
3726         { "ws_1",               switchws,       {.id = 0} },
3727         { "ws_2",               switchws,       {.id = 1} },
3728         { "ws_3",               switchws,       {.id = 2} },
3729         { "ws_4",               switchws,       {.id = 3} },
3730         { "ws_5",               switchws,       {.id = 4} },
3731         { "ws_6",               switchws,       {.id = 5} },
3732         { "ws_7",               switchws,       {.id = 6} },
3733         { "ws_8",               switchws,       {.id = 7} },
3734         { "ws_9",               switchws,       {.id = 8} },
3735         { "ws_10",              switchws,       {.id = 9} },
3736         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
3737         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
3738         { "ws_prior",           priorws,        {0} },
3739         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
3740         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
3741         { "mvws_1",             send_to_ws,     {.id = 0} },
3742         { "mvws_2",             send_to_ws,     {.id = 1} },
3743         { "mvws_3",             send_to_ws,     {.id = 2} },
3744         { "mvws_4",             send_to_ws,     {.id = 3} },
3745         { "mvws_5",             send_to_ws,     {.id = 4} },
3746         { "mvws_6",             send_to_ws,     {.id = 5} },
3747         { "mvws_7",             send_to_ws,     {.id = 6} },
3748         { "mvws_8",             send_to_ws,     {.id = 7} },
3749         { "mvws_9",             send_to_ws,     {.id = 8} },
3750         { "mvws_10",            send_to_ws,     {.id = 9} },
3751         { "bar_toggle",         bar_toggle,     {0} },
3752         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
3753         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
3754         { "screenshot_all",     legacyfunc,     {0} },
3755         { "screenshot_wind",    legacyfunc,     {0} },
3756         { "float_toggle",       floating_toggle,{0} },
3757         { "version",            version,        {0} },
3758         { "spawn_lock",         legacyfunc,     {0} },
3759         { "spawn_initscr",      legacyfunc,     {0} },
3760         { "spawn_custom",       dummykeyfunc,   {0} },
3761         { "iconify",            iconify,        {0} },
3762         { "uniconify",          uniconify,      {0} },
3763         { "raise_toggle",       raise_toggle,   {0} },
3764         { "button2",            pressbutton,    {2} },
3765         { "width_shrink",       resize_step,    {.id = SWM_ARG_ID_WIDTHSHRINK} },
3766         { "width_grow",         resize_step,    {.id = SWM_ARG_ID_WIDTHGROW} },
3767         { "height_shrink",      resize_step,    {.id = SWM_ARG_ID_HEIGHTSHRINK} },
3768         { "height_grow",        resize_step,    {.id = SWM_ARG_ID_HEIGHTGROW} },
3769         { "move_left",          move_step,      {.id = SWM_ARG_ID_MOVELEFT} },
3770         { "move_right",         move_step,      {.id = SWM_ARG_ID_MOVERIGHT} },
3771         { "move_up",            move_step,      {.id = SWM_ARG_ID_MOVEUP} },
3772         { "move_down",          move_step,      {.id = SWM_ARG_ID_MOVEDOWN} },
3773         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
3774         { "invalid key func",   NULL,           {0} },
3775 };
3776 struct key {
3777         unsigned int            mod;
3778         KeySym                  keysym;
3779         enum keyfuncid          funcid;
3780         char                    *spawn_name;
3781 };
3782 int                             keys_size = 0, keys_length = 0;
3783 struct key                      *keys = NULL;
3784
3785 /* mouse */
3786 enum { client_click, root_click };
3787 struct button {
3788         unsigned int            action;
3789         unsigned int            mask;
3790         unsigned int            button;
3791         void                    (*func)(struct ws_win *, union arg *);
3792         union arg               args;
3793 } buttons[] = {
3794           /* action     key             mouse button    func    args */
3795         { client_click, MODKEY,         Button3,        resize, {.id = SWM_ARG_ID_DONTCENTER} },
3796         { client_click, MODKEY | ShiftMask, Button3,    resize, {.id = SWM_ARG_ID_CENTER} },
3797         { client_click, MODKEY,         Button1,        move,   {0} },
3798 };
3799
3800 void
3801 update_modkey(unsigned int mod)
3802 {
3803         int                     i;
3804
3805         mod_key = mod;
3806         for (i = 0; i < keys_length; i++)
3807                 if (keys[i].mod & ShiftMask)
3808                         keys[i].mod = mod | ShiftMask;
3809                 else
3810                         keys[i].mod = mod;
3811
3812         for (i = 0; i < LENGTH(buttons); i++)
3813                 if (buttons[i].mask & ShiftMask)
3814                         buttons[i].mask = mod | ShiftMask;
3815                 else
3816                         buttons[i].mask = mod;
3817 }
3818
3819 /* spawn */
3820 struct spawn_prog {
3821         char                    *name;
3822         int                     argc;
3823         char                    **argv;
3824 };
3825
3826 int                             spawns_size = 0, spawns_length = 0;
3827 struct spawn_prog               *spawns = NULL;
3828
3829 int
3830 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
3831     char ***ret_args)
3832 {
3833         struct spawn_prog       *prog = NULL;
3834         int                     i;
3835         char                    *ap, **real_args;
3836
3837         DNPRINTF(SWM_D_SPAWN, "spawn_expand %s\n", spawn_name);
3838
3839         /* find program */
3840         for (i = 0; i < spawns_length; i++) {
3841                 if (!strcasecmp(spawn_name, spawns[i].name))
3842                         prog = &spawns[i];
3843         }
3844         if (prog == NULL) {
3845                 fprintf(stderr, "spawn_custom: program %s not found\n",
3846                     spawn_name);
3847                 return (-1);
3848         }
3849
3850         /* make room for expanded args */
3851         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
3852                 err(1, "spawn_custom: calloc real_args");
3853
3854         /* expand spawn_args into real_args */
3855         for (i = 0; i < prog->argc; i++) {
3856                 ap = prog->argv[i];
3857                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg = %s\n", ap);
3858                 if (!strcasecmp(ap, "$bar_border")) {
3859                         if ((real_args[i] =
3860                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
3861                             == NULL)
3862                                 err(1,  "spawn_custom border color");
3863                 } else if (!strcasecmp(ap, "$bar_color")) {
3864                         if ((real_args[i] =
3865                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
3866                             == NULL)
3867                                 err(1, "spawn_custom bar color");
3868                 } else if (!strcasecmp(ap, "$bar_font")) {
3869                         if ((real_args[i] = strdup(bar_fonts[bar_fidx]))
3870                             == NULL)
3871                                 err(1, "spawn_custom bar fonts");
3872                 } else if (!strcasecmp(ap, "$bar_font_color")) {
3873                         if ((real_args[i] =
3874                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
3875                             == NULL)
3876                                 err(1, "spawn_custom color font");
3877                 } else if (!strcasecmp(ap, "$color_focus")) {
3878                         if ((real_args[i] =
3879                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
3880                             == NULL)
3881                                 err(1, "spawn_custom color focus");
3882                 } else if (!strcasecmp(ap, "$color_unfocus")) {
3883                         if ((real_args[i] =
3884                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
3885                             == NULL)
3886                                 err(1, "spawn_custom color unfocus");
3887                 } else {
3888                         /* no match --> copy as is */
3889                         if ((real_args[i] = strdup(ap)) == NULL)
3890                                 err(1, "spawn_custom strdup(ap)");
3891                 }
3892                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg = %s\n",
3893                     real_args[i]);
3894         }
3895
3896 #ifdef SWM_DEBUG
3897         if ((swm_debug & SWM_D_SPAWN) != 0) {
3898                 fprintf(stderr, "spawn_custom: result = ");
3899                 for (i = 0; i < prog->argc; i++)
3900                         fprintf(stderr, "\"%s\" ", real_args[i]);
3901                 fprintf(stderr, "\n");
3902         }
3903 #endif
3904         *ret_args = real_args;
3905         return (prog->argc);
3906 }
3907
3908 void
3909 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
3910 {
3911         union arg               a;
3912         char                    **real_args;
3913         int                     spawn_argc, i;
3914
3915         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3916                 return;
3917         a.argv = real_args;
3918         if (fork() == 0)
3919                 spawn(r->ws->idx, &a, 1);
3920
3921         for (i = 0; i < spawn_argc; i++)
3922                 free(real_args[i]);
3923         free(real_args);
3924 }
3925
3926 void
3927 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
3928 {
3929         union arg               a;
3930         char                    **real_args;
3931         int                     i, spawn_argc;
3932
3933         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3934                 return;
3935         a.argv = real_args;
3936
3937         if (pipe(select_list_pipe) == -1)
3938                 err(1, "pipe error");
3939         if (pipe(select_resp_pipe) == -1)
3940                 err(1, "pipe error");
3941
3942         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3943                 err(1, "could not disable SIGPIPE");
3944         switch (*pid = fork()) {
3945         case -1:
3946                 err(1, "cannot fork");
3947                 break;
3948         case 0: /* child */
3949                 if (dup2(select_list_pipe[0], 0) == -1)
3950                         errx(1, "dup2");
3951                 if (dup2(select_resp_pipe[1], 1) == -1)
3952                         errx(1, "dup2");
3953                 close(select_list_pipe[1]);
3954                 close(select_resp_pipe[0]);
3955                 spawn(r->ws->idx, &a, 0);
3956                 break;
3957         default: /* parent */
3958                 close(select_list_pipe[0]);
3959                 close(select_resp_pipe[1]);
3960                 break;
3961         }
3962
3963         for (i = 0; i < spawn_argc; i++)
3964                 free(real_args[i]);
3965         free(real_args);
3966 }
3967
3968 void
3969 setspawn(struct spawn_prog *prog)
3970 {
3971         int                     i, j;
3972
3973         if (prog == NULL || prog->name == NULL)
3974                 return;
3975
3976         /* find existing */
3977         for (i = 0; i < spawns_length; i++) {
3978                 if (!strcmp(spawns[i].name, prog->name)) {
3979                         /* found */
3980                         if (prog->argv == NULL) {
3981                                 /* delete */
3982                                 DNPRINTF(SWM_D_SPAWN,
3983                                     "setspawn: delete #%d %s\n",
3984                                     i, spawns[i].name);
3985                                 free(spawns[i].name);
3986                                 for (j = 0; j < spawns[i].argc; j++)
3987                                         free(spawns[i].argv[j]);
3988                                 free(spawns[i].argv);
3989                                 j = spawns_length - 1;
3990                                 if (i < j)
3991                                         spawns[i] = spawns[j];
3992                                 spawns_length--;
3993                                 free(prog->name);
3994                         } else {
3995                                 /* replace */
3996                                 DNPRINTF(SWM_D_SPAWN,
3997                                     "setspawn: replace #%d %s\n",
3998                                     i, spawns[i].name);
3999                                 free(spawns[i].name);
4000                                 for (j = 0; j < spawns[i].argc; j++)
4001                                         free(spawns[i].argv[j]);
4002                                 free(spawns[i].argv);
4003                                 spawns[i] = *prog;
4004                         }
4005                         /* found case handled */
4006                         free(prog);
4007                         return;
4008                 }
4009         }
4010
4011         if (prog->argv == NULL) {
4012                 fprintf(stderr,
4013                     "error: setspawn: cannot find program %s", prog->name);
4014                 free(prog);
4015                 return;
4016         }
4017
4018         /* not found: add */
4019         if (spawns_size == 0 || spawns == NULL) {
4020                 spawns_size = 4;
4021                 DNPRINTF(SWM_D_SPAWN, "setspawn: init list %d\n", spawns_size);
4022                 spawns = malloc((size_t)spawns_size *
4023                     sizeof(struct spawn_prog));
4024                 if (spawns == NULL) {
4025                         fprintf(stderr, "setspawn: malloc failed\n");
4026                         perror(" failed");
4027                         quit(NULL, NULL);
4028                 }
4029         } else if (spawns_length == spawns_size) {
4030                 spawns_size *= 2;
4031                 DNPRINTF(SWM_D_SPAWN, "setspawn: grow list %d\n", spawns_size);
4032                 spawns = realloc(spawns, (size_t)spawns_size *
4033                     sizeof(struct spawn_prog));
4034                 if (spawns == NULL) {
4035                         fprintf(stderr, "setspawn: realloc failed\n");
4036                         perror(" failed");
4037                         quit(NULL, NULL);
4038                 }
4039         }
4040
4041         if (spawns_length < spawns_size) {
4042                 DNPRINTF(SWM_D_SPAWN, "setspawn: add #%d %s\n",
4043                     spawns_length, prog->name);
4044                 i = spawns_length++;
4045                 spawns[i] = *prog;
4046         } else {
4047                 fprintf(stderr, "spawns array problem?\n");
4048                 if (spawns == NULL) {
4049                         fprintf(stderr, "spawns array is NULL!\n");
4050                         quit(NULL, NULL);
4051                 }
4052         }
4053         free(prog);
4054 }
4055
4056 int
4057 setconfspawn(char *selector, char *value, int flags)
4058 {
4059         struct spawn_prog       *prog;
4060         char                    *vp, *cp, *word;
4061
4062         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
4063         if ((prog = calloc(1, sizeof *prog)) == NULL)
4064                 err(1, "setconfspawn: calloc prog");
4065         prog->name = strdup(selector);
4066         if (prog->name == NULL)
4067                 err(1, "setconfspawn prog->name");
4068         if ((cp = vp = strdup(value)) == NULL)
4069                 err(1, "setconfspawn: strdup(value) ");
4070         while ((word = strsep(&cp, " \t")) != NULL) {
4071                 DNPRINTF(SWM_D_SPAWN, "setconfspawn: arg [%s]\n", word);
4072                 if (cp)
4073                         cp += (long)strspn(cp, " \t");
4074                 if (strlen(word) > 0) {
4075                         prog->argc++;
4076                         if ((prog->argv = realloc(prog->argv,
4077                             prog->argc * sizeof(char *))) == NULL)
4078                                 err(1, "setconfspawn: realloc");
4079                         if ((prog->argv[prog->argc - 1] = strdup(word)) == NULL)
4080                                 err(1, "setconfspawn: strdup");
4081                 }
4082         }
4083         free(vp);
4084
4085         setspawn(prog);
4086
4087         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
4088         return (0);
4089 }
4090
4091 void
4092 setup_spawn(void)
4093 {
4094         setconfspawn("term",            "xterm",                0);
4095         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
4096         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
4097         setconfspawn("lock",            "xlock",                0);
4098         setconfspawn("initscr",         "initscreen.sh",        0);
4099         setconfspawn("menu",            "dmenu_run"
4100                                         " -fn $bar_font"
4101                                         " -nb $bar_color"
4102                                         " -nf $bar_font_color"
4103                                         " -sb $bar_border"
4104                                         " -sf $bar_color",      0);
4105         setconfspawn("uniconify",       "dmenu"
4106                                         " -i"
4107                                         " -fn $bar_font"
4108                                         " -nb $bar_color"
4109                                         " -nf $bar_font_color"
4110                                         " -sb $bar_border"
4111                                         " -sf $bar_color",      0);
4112 }
4113
4114 /* key bindings */
4115 #define SWM_MODNAME_SIZE        32
4116 #define SWM_KEY_WS              "\n+ \t"
4117 int
4118 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
4119 {
4120         char                    *cp, *name;
4121         KeySym                  uks;
4122         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
4123         if (mod == NULL || ks == NULL) {
4124                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
4125                 return (1);
4126         }
4127         if (keystr == NULL || strlen(keystr) == 0) {
4128                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
4129                 return (1);
4130         }
4131         cp = keystr;
4132         *ks = NoSymbol;
4133         *mod = 0;
4134         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
4135                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
4136                 if (cp)
4137                         cp += (long)strspn(cp, SWM_KEY_WS);
4138                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
4139                         *mod |= currmod;
4140                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
4141                         *mod |= Mod1Mask;
4142                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
4143                         *mod += Mod2Mask;
4144                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
4145                         *mod |= Mod3Mask;
4146                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
4147                         *mod |= Mod4Mask;
4148                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
4149                         *mod |= ShiftMask;
4150                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
4151                         *mod |= ControlMask;
4152                 else {
4153                         *ks = XStringToKeysym(name);
4154                         XConvertCase(*ks, ks, &uks);
4155                         if (ks == NoSymbol) {
4156                                 DNPRINTF(SWM_D_KEY,
4157                                     "parsekeys: invalid key %s\n",
4158                                     name);
4159                                 return (1);
4160                         }
4161                 }
4162         }
4163         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
4164         return (0);
4165 }
4166
4167 char *
4168 strdupsafe(char *str)
4169 {
4170         if (str == NULL)
4171                 return (NULL);
4172         else
4173                 return (strdup(str));
4174 }
4175
4176 void
4177 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
4178     char *spawn_name)
4179 {
4180         int                     i, j;
4181         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
4182             keyfuncs[kfid].name, spawn_name);
4183         /* find existing */
4184         for (i = 0; i < keys_length; i++) {
4185                 if (keys[i].mod == mod && keys[i].keysym == ks) {
4186                         if (kfid == kf_invalid) {
4187                                 /* found: delete */
4188                                 DNPRINTF(SWM_D_KEY,
4189                                     "setkeybinding: delete #%d %s\n",
4190                                     i, keyfuncs[keys[i].funcid].name);
4191                                 free(keys[i].spawn_name);
4192                                 j = keys_length - 1;
4193                                 if (i < j)
4194                                         keys[i] = keys[j];
4195                                 keys_length--;
4196                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4197                                 return;
4198                         } else {
4199                                 /* found: replace */
4200                                 DNPRINTF(SWM_D_KEY,
4201                                     "setkeybinding: replace #%d %s %s\n",
4202                                     i, keyfuncs[keys[i].funcid].name,
4203                                     spawn_name);
4204                                 free(keys[i].spawn_name);
4205                                 keys[i].mod = mod;
4206                                 keys[i].keysym = ks;
4207                                 keys[i].funcid = kfid;
4208                                 keys[i].spawn_name = strdupsafe(spawn_name);
4209                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4210                                 return;
4211                         }
4212                 }
4213         }
4214         if (kfid == kf_invalid) {
4215                 fprintf(stderr,
4216                     "error: setkeybinding: cannot find mod/key combination");
4217                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4218                 return;
4219         }
4220         /* not found: add */
4221         if (keys_size == 0 || keys == NULL) {
4222                 keys_size = 4;
4223                 DNPRINTF(SWM_D_KEY, "setkeybinding: init list %d\n", keys_size);
4224                 keys = malloc((size_t)keys_size * sizeof(struct key));
4225                 if (keys == NULL) {
4226                         fprintf(stderr, "malloc failed\n");
4227                         perror(" failed");
4228                         quit(NULL, NULL);
4229                 }
4230         } else if (keys_length == keys_size) {
4231                 keys_size *= 2;
4232                 DNPRINTF(SWM_D_KEY, "setkeybinding: grow list %d\n", keys_size);
4233                 keys = realloc(keys, (size_t)keys_size * sizeof(struct key));
4234                 if (keys == NULL) {
4235                         fprintf(stderr, "realloc failed\n");
4236                         perror(" failed");
4237                         quit(NULL, NULL);
4238                 }
4239         }
4240         if (keys_length < keys_size) {
4241                 j = keys_length++;
4242                 DNPRINTF(SWM_D_KEY, "setkeybinding: add #%d %s %s\n",
4243                     j, keyfuncs[kfid].name, spawn_name);
4244                 keys[j].mod = mod;
4245                 keys[j].keysym = ks;
4246                 keys[j].funcid = kfid;
4247                 keys[j].spawn_name = strdupsafe(spawn_name);
4248         } else {
4249                 fprintf(stderr, "keys array problem?\n");
4250                 if (keys == NULL) {
4251                         fprintf(stderr, "keys array problem\n");
4252                         quit(NULL, NULL);
4253                 }
4254         }
4255         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4256 }
4257
4258 int
4259 setconfbinding(char *selector, char *value, int flags)
4260 {
4261         enum keyfuncid          kfid;
4262         unsigned int            mod;
4263         KeySym                  ks;
4264         int                     i;
4265         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
4266         if (selector == NULL) {
4267                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
4268                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4269                         kfid = kf_invalid;
4270                         setkeybinding(mod, ks, kfid, NULL);
4271                         return (0);
4272                 } else
4273                         return (1);
4274         }
4275         /* search by key function name */
4276         for (kfid = 0; kfid < kf_invalid; (kfid)++) {
4277                 if (strncasecmp(selector, keyfuncs[kfid].name,
4278                     SWM_FUNCNAME_LEN) == 0) {
4279                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4280                             selector);
4281                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4282                                 setkeybinding(mod, ks, kfid, NULL);
4283                                 return (0);
4284                         } else
4285                                 return (1);
4286                 }
4287         }
4288         /* search by custom spawn name */
4289         for (i = 0; i < spawns_length; i++) {
4290                 if (strcasecmp(selector, spawns[i].name) == 0) {
4291                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4292                             selector);
4293                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4294                                 setkeybinding(mod, ks, kf_spawn_custom,
4295                                     spawns[i].name);
4296                                 return (0);
4297                         } else
4298                                 return (1);
4299                 }
4300         }
4301         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
4302         return (1);
4303 }
4304
4305 void
4306 setup_keys(void)
4307 {
4308         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout,NULL);
4309         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset, NULL);
4310         setkeybinding(MODKEY,           XK_h,           kf_master_shrink,NULL);
4311         setkeybinding(MODKEY,           XK_l,           kf_master_grow, NULL);
4312         setkeybinding(MODKEY,           XK_comma,       kf_master_add,  NULL);
4313         setkeybinding(MODKEY,           XK_period,      kf_master_del,  NULL);
4314         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc,   NULL);
4315         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec,   NULL);
4316         setkeybinding(MODKEY,           XK_Return,      kf_swap_main,   NULL);
4317         setkeybinding(MODKEY,           XK_j,           kf_focus_next,  NULL);
4318         setkeybinding(MODKEY,           XK_k,           kf_focus_prev,  NULL);
4319         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next,   NULL);
4320         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev,   NULL);
4321         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_term,  NULL);
4322         setkeybinding(MODKEY,           XK_p,           kf_spawn_custom,"menu");
4323         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit,        NULL);
4324         setkeybinding(MODKEY,           XK_q,           kf_restart,     NULL);
4325         setkeybinding(MODKEY,           XK_m,           kf_focus_main,  NULL);
4326         setkeybinding(MODKEY,           XK_1,           kf_ws_1,        NULL);
4327         setkeybinding(MODKEY,           XK_2,           kf_ws_2,        NULL);
4328         setkeybinding(MODKEY,           XK_3,           kf_ws_3,        NULL);
4329         setkeybinding(MODKEY,           XK_4,           kf_ws_4,        NULL);
4330         setkeybinding(MODKEY,           XK_5,           kf_ws_5,        NULL);
4331         setkeybinding(MODKEY,           XK_6,           kf_ws_6,        NULL);
4332         setkeybinding(MODKEY,           XK_7,           kf_ws_7,        NULL);
4333         setkeybinding(MODKEY,           XK_8,           kf_ws_8,        NULL);
4334         setkeybinding(MODKEY,           XK_9,           kf_ws_9,        NULL);
4335         setkeybinding(MODKEY,           XK_0,           kf_ws_10,       NULL);
4336         setkeybinding(MODKEY,           XK_Right,       kf_ws_next,     NULL);
4337         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev,     NULL);
4338         setkeybinding(MODKEY,           XK_a,           kf_ws_prior,    NULL);
4339         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next, NULL);
4340         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev, NULL);
4341         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1,      NULL);
4342         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2,      NULL);
4343         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3,      NULL);
4344         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4,      NULL);
4345         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5,      NULL);
4346         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6,      NULL);
4347         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7,      NULL);
4348         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8,      NULL);
4349         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9,      NULL);
4350         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10,     NULL);
4351         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle,  NULL);
4352         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next,  NULL);
4353         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev,  NULL);
4354         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill,   NULL);
4355         setkeybinding(MODKEY,           XK_x,           kf_wind_del,    NULL);
4356         setkeybinding(MODKEY,           XK_s,           kf_spawn_custom,"screenshot_all");
4357         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_spawn_custom,"screenshot_wind");
4358         setkeybinding(MODKEY,           XK_t,           kf_float_toggle,NULL);
4359         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version,     NULL);
4360         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_custom,"lock");
4361         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_custom,"initscr");
4362         setkeybinding(MODKEY,           XK_w,           kf_iconify,     NULL);
4363         setkeybinding(MODKEY|ShiftMask, XK_w,           kf_uniconify,   NULL);
4364         setkeybinding(MODKEY|ShiftMask, XK_r,           kf_raise_toggle,NULL);
4365         setkeybinding(MODKEY,           XK_v,           kf_button2,     NULL);
4366         setkeybinding(MODKEY,           XK_equal,       kf_width_grow,  NULL);
4367         setkeybinding(MODKEY,           XK_minus,       kf_width_shrink,NULL);
4368         setkeybinding(MODKEY|ShiftMask, XK_equal,       kf_height_grow, NULL);
4369         setkeybinding(MODKEY|ShiftMask, XK_minus,       kf_height_shrink,NULL);
4370         setkeybinding(MODKEY,           XK_bracketleft, kf_move_left,   NULL);
4371         setkeybinding(MODKEY,           XK_bracketright,kf_move_right,  NULL);
4372         setkeybinding(MODKEY|ShiftMask, XK_bracketleft, kf_move_up,     NULL);
4373         setkeybinding(MODKEY|ShiftMask, XK_bracketright,kf_move_down,   NULL);
4374 #ifdef SWM_DEBUG
4375         setkeybinding(MODKEY|ShiftMask, XK_d,           kf_dumpwins,    NULL);
4376 #endif
4377 }
4378
4379 void
4380 updatenumlockmask(void)
4381 {
4382         unsigned int            i, j;
4383         XModifierKeymap         *modmap;
4384
4385         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
4386         numlockmask = 0;
4387         modmap = XGetModifierMapping(display);
4388         for (i = 0; i < 8; i++)
4389                 for (j = 0; j < modmap->max_keypermod; j++)
4390                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
4391                             == XKeysymToKeycode(display, XK_Num_Lock))
4392                                 numlockmask = (1 << i);
4393
4394         XFreeModifiermap(modmap);
4395 }
4396
4397 void
4398 grabkeys(void)
4399 {
4400         unsigned int            i, j, k;
4401         KeyCode                 code;
4402         unsigned int            modifiers[] =
4403             { 0, LockMask, numlockmask, numlockmask | LockMask };
4404
4405         DNPRINTF(SWM_D_MISC, "grabkeys\n");
4406         updatenumlockmask();
4407
4408         for (k = 0; k < ScreenCount(display); k++) {
4409                 if (TAILQ_EMPTY(&screens[k].rl))
4410                         continue;
4411                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
4412                 for (i = 0; i < keys_length; i++) {
4413                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
4414                                 for (j = 0; j < LENGTH(modifiers); j++)
4415                                         XGrabKey(display, code,
4416                                             keys[i].mod | modifiers[j],
4417                                             screens[k].root, True,
4418                                             GrabModeAsync, GrabModeAsync);
4419                 }
4420         }
4421 }
4422
4423 void
4424 grabbuttons(struct ws_win *win, int focused)
4425 {
4426         unsigned int            i, j;
4427         unsigned int            modifiers[] =
4428             { 0, LockMask, numlockmask, numlockmask|LockMask };
4429
4430         updatenumlockmask();
4431         XUngrabButton(display, AnyButton, AnyModifier, win->id);
4432         if (focused) {
4433                 for (i = 0; i < LENGTH(buttons); i++)
4434                         if (buttons[i].action == client_click)
4435                                 for (j = 0; j < LENGTH(modifiers); j++)
4436                                         XGrabButton(display, buttons[i].button,
4437                                             buttons[i].mask | modifiers[j],
4438                                             win->id, False, BUTTONMASK,
4439                                             GrabModeAsync, GrabModeSync, None,
4440                                             None);
4441         } else
4442                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
4443                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
4444 }
4445
4446 const char *quirkname[] = {
4447         "NONE",         /* config string for "no value" */
4448         "FLOAT",
4449         "TRANSSZ",
4450         "ANYWHERE",
4451         "XTERM_FONTADJ",
4452         "FULLSCREEN",
4453         "FOCUSPREV",
4454 };
4455
4456 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
4457 #define SWM_Q_WS                "\n|+ \t"
4458 int
4459 parsequirks(char *qstr, unsigned long *quirk)
4460 {
4461         char                    *cp, *name;
4462         int                     i;
4463
4464         if (quirk == NULL)
4465                 return (1);
4466
4467         cp = qstr;
4468         *quirk = 0;
4469         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
4470                 if (cp)
4471                         cp += (long)strspn(cp, SWM_Q_WS);
4472                 for (i = 0; i < LENGTH(quirkname); i++) {
4473                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
4474                                 DNPRINTF(SWM_D_QUIRK,
4475                                     "parsequirks: %s\n", name);
4476                                 if (i == 0) {
4477                                         *quirk = 0;
4478                                         return (0);
4479                                 }
4480                                 *quirk |= 1 << (i-1);
4481                                 break;
4482                         }
4483                 }
4484                 if (i >= LENGTH(quirkname)) {
4485                         DNPRINTF(SWM_D_QUIRK,
4486                             "parsequirks: invalid quirk [%s]\n", name);
4487                         return (1);
4488                 }
4489         }
4490         return (0);
4491 }
4492
4493 void
4494 setquirk(const char *class, const char *name, const int quirk)
4495 {
4496         int                     i, j;
4497
4498         /* find existing */
4499         for (i = 0; i < quirks_length; i++) {
4500                 if (!strcmp(quirks[i].class, class) &&
4501                     !strcmp(quirks[i].name, name)) {
4502                         if (!quirk) {
4503                                 /* found: delete */
4504                                 DNPRINTF(SWM_D_QUIRK,
4505                                     "setquirk: delete #%d %s:%s\n",
4506                                     i, quirks[i].class, quirks[i].name);
4507                                 free(quirks[i].class);
4508                                 free(quirks[i].name);
4509                                 j = quirks_length - 1;
4510                                 if (i < j)
4511                                         quirks[i] = quirks[j];
4512                                 quirks_length--;
4513                                 return;
4514                         } else {
4515                                 /* found: replace */
4516                                 DNPRINTF(SWM_D_QUIRK,
4517                                     "setquirk: replace #%d %s:%s\n",
4518                                     i, quirks[i].class, quirks[i].name);
4519                                 free(quirks[i].class);
4520                                 free(quirks[i].name);
4521                                 quirks[i].class = strdup(class);
4522                                 quirks[i].name = strdup(name);
4523                                 quirks[i].quirk = quirk;
4524                                 return;
4525                         }
4526                 }
4527         }
4528         if (!quirk) {
4529                 fprintf(stderr,
4530                     "error: setquirk: cannot find class/name combination");
4531                 return;
4532         }
4533         /* not found: add */
4534         if (quirks_size == 0 || quirks == NULL) {
4535                 quirks_size = 4;
4536                 DNPRINTF(SWM_D_QUIRK, "setquirk: init list %d\n", quirks_size);
4537                 quirks = malloc((size_t)quirks_size * sizeof(struct quirk));
4538                 if (quirks == NULL) {
4539                         fprintf(stderr, "setquirk: malloc failed\n");
4540                         perror(" failed");
4541                         quit(NULL, NULL);
4542                 }
4543         } else if (quirks_length == quirks_size) {
4544                 quirks_size *= 2;
4545                 DNPRINTF(SWM_D_QUIRK, "setquirk: grow list %d\n", quirks_size);
4546                 quirks = realloc(quirks,
4547                     (size_t)quirks_size * sizeof(struct quirk));
4548                 if (quirks == NULL) {
4549                         fprintf(stderr, "setquirk: realloc failed\n");
4550                         perror(" failed");
4551                         quit(NULL, NULL);
4552                 }
4553         }
4554         if (quirks_length < quirks_size) {
4555                 DNPRINTF(SWM_D_QUIRK, "setquirk: add %d\n", quirks_length);
4556                 j = quirks_length++;
4557                 quirks[j].class = strdup(class);
4558                 quirks[j].name = strdup(name);
4559                 quirks[j].quirk = quirk;
4560         } else {
4561                 fprintf(stderr, "quirks array problem?\n");
4562                 if (quirks == NULL) {
4563                         fprintf(stderr, "quirks array problem!\n");
4564                         quit(NULL, NULL);
4565                 }
4566         }
4567 }
4568
4569 int
4570 setconfquirk(char *selector, char *value, int flags)
4571 {
4572         char                    *cp, *class, *name;
4573         int                     retval;
4574         unsigned long           quirks;
4575         if (selector == NULL)
4576                 return (0);
4577         if ((cp = strchr(selector, ':')) == NULL)
4578                 return (0);
4579         *cp = '\0';
4580         class = selector;
4581         name = cp + 1;
4582         if ((retval = parsequirks(value, &quirks)) == 0)
4583                 setquirk(class, name, quirks);
4584         return (retval);
4585 }
4586
4587 void
4588 setup_quirks(void)
4589 {
4590         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
4591         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
4592         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
4593         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
4594         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4595         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
4596         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4597         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4598         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4599         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4600         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
4601         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
4602         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
4603 }
4604
4605 /* conf file stuff */
4606 #define SWM_CONF_FILE   "scrotwm.conf"
4607
4608 enum    { SWM_S_BAR_DELAY, SWM_S_BAR_ENABLED, SWM_S_BAR_BORDER_WIDTH,
4609           SWM_S_STACK_ENABLED, SWM_S_CLOCK_ENABLED, SWM_S_CLOCK_FORMAT,
4610           SWM_S_CYCLE_EMPTY, SWM_S_CYCLE_VISIBLE, SWM_S_SS_ENABLED,
4611           SWM_S_TERM_WIDTH, SWM_S_TITLE_CLASS_ENABLED,
4612           SWM_S_TITLE_NAME_ENABLED, SWM_S_WINDOW_NAME_ENABLED, SWM_S_URGENT_ENABLED,
4613           SWM_S_FOCUS_MODE, SWM_S_DISABLE_BORDER, SWM_S_BORDER_WIDTH,
4614           SWM_S_BAR_FONT, SWM_S_BAR_ACTION, SWM_S_SPAWN_TERM,
4615           SWM_S_SS_APP, SWM_S_DIALOG_RATIO, SWM_S_BAR_AT_BOTTOM,
4616           SWM_S_VERBOSE_LAYOUT
4617         };
4618
4619 int
4620 setconfvalue(char *selector, char *value, int flags)
4621 {
4622         int i;
4623         switch (flags) {
4624         case SWM_S_BAR_DELAY:
4625                 bar_delay = atoi(value);
4626                 break;
4627         case SWM_S_BAR_ENABLED:
4628                 bar_enabled = atoi(value);
4629                 break;
4630         case SWM_S_BAR_BORDER_WIDTH:
4631                 bar_border_width = atoi(value);
4632                 break;
4633         case SWM_S_BAR_AT_BOTTOM:
4634                 bar_at_bottom = atoi(value);
4635                 break;
4636         case SWM_S_STACK_ENABLED:
4637                 stack_enabled = atoi(value);
4638                 break;
4639         case SWM_S_CLOCK_ENABLED:
4640                 clock_enabled = atoi(value);
4641                 break;
4642         case SWM_S_CLOCK_FORMAT:
4643 #ifndef SWM_DENY_CLOCK_FORMAT
4644                 free(clock_format);
4645                 if ((clock_format = strdup(value)) == NULL)
4646                         err(1, "setconfvalue: clock_format");
4647 #endif
4648                 break;
4649         case SWM_S_CYCLE_EMPTY:
4650                 cycle_empty = atoi(value);
4651                 break;
4652         case SWM_S_CYCLE_VISIBLE:
4653                 cycle_visible = atoi(value);
4654                 break;
4655         case SWM_S_SS_ENABLED:
4656                 ss_enabled = atoi(value);
4657                 break;
4658         case SWM_S_TERM_WIDTH:
4659                 term_width = atoi(value);
4660                 break;
4661         case SWM_S_TITLE_CLASS_ENABLED:
4662                 title_class_enabled = atoi(value);
4663                 break;
4664         case SWM_S_WINDOW_NAME_ENABLED:
4665                 window_name_enabled = atoi(value);
4666                 break;
4667         case SWM_S_TITLE_NAME_ENABLED:
4668                 title_name_enabled = atoi(value);
4669                 break;
4670         case SWM_S_URGENT_ENABLED:
4671                 urgent_enabled = atoi(value);
4672                 break;
4673         case SWM_S_FOCUS_MODE:
4674                 if (!strcmp(value, "default"))
4675                         focus_mode = SWM_FOCUS_DEFAULT;
4676                 else if (!strcmp(value, "follow_cursor"))
4677                         focus_mode = SWM_FOCUS_FOLLOW;
4678                 else if (!strcmp(value, "synergy"))
4679                         focus_mode = SWM_FOCUS_SYNERGY;
4680                 else
4681                         err(1, "focus_mode");
4682                 break;
4683         case SWM_S_DISABLE_BORDER:
4684                 disable_border = atoi(value);
4685                 break;
4686         case SWM_S_BORDER_WIDTH:
4687                 border_width = atoi(value);
4688                 break;
4689         case SWM_S_BAR_FONT:
4690                 free(bar_fonts[0]);
4691                 if ((bar_fonts[0] = strdup(value)) == NULL)
4692                         err(1, "setconfvalue: bar_font");
4693                 break;
4694         case SWM_S_BAR_ACTION:
4695                 free(bar_argv[0]);
4696                 if ((bar_argv[0] = strdup(value)) == NULL)
4697                         err(1, "setconfvalue: bar_action");
4698                 break;
4699         case SWM_S_SPAWN_TERM:
4700                 free(spawn_term[0]);
4701                 if ((spawn_term[0] = strdup(value)) == NULL)
4702                         err(1, "setconfvalue: spawn_term");
4703                 break;
4704         case SWM_S_SS_APP:
4705                 break;
4706         case SWM_S_DIALOG_RATIO:
4707                 dialog_ratio = atof(value);
4708                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
4709                         dialog_ratio = .6;
4710                 break;
4711         case SWM_S_VERBOSE_LAYOUT:
4712                 verbose_layout = atoi(value);
4713                 for (i = 0; layouts[i].l_stack != NULL; i++) {
4714                         if (verbose_layout)
4715                                 layouts[i].l_string = fancy_stacker;
4716                         else
4717                                 layouts[i].l_string = plain_stacker;
4718                 }
4719                 break;
4720         default:
4721                 return (1);
4722         }
4723         return (0);
4724 }
4725
4726 int
4727 setconfmodkey(char *selector, char *value, int flags)
4728 {
4729         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
4730                 update_modkey(Mod1Mask);
4731         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
4732                 update_modkey(Mod2Mask);
4733         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
4734                 update_modkey(Mod3Mask);
4735         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
4736                 update_modkey(Mod4Mask);
4737         else
4738                 return (1);
4739         return (0);
4740 }
4741
4742 int
4743 setconfcolor(char *selector, char *value, int flags)
4744 {
4745         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
4746         return (0);
4747 }
4748
4749 int
4750 setconfregion(char *selector, char *value, int flags)
4751 {
4752         custom_region(value);
4753         return (0);
4754 }
4755
4756 int
4757 setautorun(char *selector, char *value, int flags)
4758 {
4759         int                     ws_id;
4760         char                    s[1024];
4761         char                    *ap, *sp = s;
4762         union arg               a;
4763         int                     argc = 0;
4764         long                    pid;
4765         struct pid_e            *p;
4766
4767         if (getenv("SWM_STARTED"))
4768                 return (0);
4769
4770         bzero(s, sizeof s);
4771         if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
4772                 errx(1, "invalid autorun entry, should be 'ws[<idx>]:command'\n");
4773         ws_id--;
4774         if (ws_id < 0 || ws_id >= SWM_WS_MAX)
4775                 errx(1, "autorun: invalid workspace %d\n", ws_id + 1);
4776
4777         /*
4778          * This is a little intricate
4779          *
4780          * If the pid already exists we simply reuse it because it means it was
4781          * used before AND not claimed by manage_window.  We get away with
4782          * altering it in the parent after INSERT because this can not be a race
4783          */
4784         a.argv = NULL;
4785         while ((ap = strsep(&sp, " \t")) != NULL) {
4786                 if (*ap == '\0')
4787                         continue;
4788                 DNPRINTF(SWM_D_SPAWN, "setautorun: arg [%s]\n", ap);
4789                 argc++;
4790                 if ((a.argv = realloc(a.argv, argc * sizeof(char *))) == NULL)
4791                         err(1, "setautorun: realloc");
4792                 a.argv[argc - 1] = ap;
4793         }
4794
4795         if ((a.argv = realloc(a.argv, (argc + 1) * sizeof(char *))) == NULL)
4796                 err(1, "setautorun: realloc");
4797         a.argv[argc] = NULL;
4798
4799         if ((pid = fork()) == 0) {
4800                 spawn(ws_id, &a, 1);
4801                 /* NOTREACHED */
4802                 _exit(1);
4803         }
4804         free(a.argv);
4805
4806         /* parent */
4807         p = find_pid(pid);
4808         if (p == NULL) {
4809                 p = calloc(1, sizeof *p);
4810                 if (p == NULL)
4811                         return (1);
4812                 TAILQ_INSERT_TAIL(&pidlist, p, entry);
4813         }
4814
4815         p->pid = pid;
4816         p->ws = ws_id;
4817
4818         return (0);
4819 }
4820
4821 int
4822 setlayout(char *selector, char *value, int flags)
4823 {
4824         int                     ws_id, st, i, x, mg, ma, si, raise;
4825         char                    s[1024];
4826         struct workspace        *ws;
4827
4828         if (getenv("SWM_STARTED"))
4829                 return (0);
4830
4831         bzero(s, sizeof s);
4832         if (sscanf(value, "ws[%d]:%d:%d:%d:%d:%1023c",
4833             &ws_id, &mg, &ma, &si, &raise, s) != 6)
4834                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
4835                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
4836                     "<type>'\n");
4837         ws_id--;
4838         if (ws_id < 0 || ws_id >= SWM_WS_MAX)
4839                 errx(1, "layout: invalid workspace %d\n", ws_id + 1);
4840
4841         if (!strcasecmp(s, "vertical"))
4842                 st = SWM_V_STACK;
4843         else if (!strcasecmp(s, "horizontal"))
4844                 st = SWM_H_STACK;
4845         else if (!strcasecmp(s, "fullscreen"))
4846                 st = SWM_MAX_STACK;
4847         else
4848                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
4849                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
4850                     "<type>'\n");
4851
4852         for (i = 0; i < ScreenCount(display); i++) {
4853                 ws = (struct workspace *)&screens[i].ws;
4854                 ws[ws_id].cur_layout = &layouts[st];
4855
4856                 ws[ws_id].always_raise = raise;
4857                 if (st == SWM_MAX_STACK)
4858                         continue;
4859
4860                 /* master grow */
4861                 for (x = 0; x < abs(mg); x++) {
4862                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
4863                             mg >= 0 ?  SWM_ARG_ID_MASTERGROW :
4864                             SWM_ARG_ID_MASTERSHRINK);
4865                         stack();
4866                 }
4867                 /* master add */
4868                 for (x = 0; x < abs(ma); x++) {
4869                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
4870                             ma >= 0 ?  SWM_ARG_ID_MASTERADD :
4871                             SWM_ARG_ID_MASTERDEL);
4872                         stack();
4873                 }
4874                 /* stack inc */
4875                 for (x = 0; x < abs(si); x++) {
4876                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
4877                             si >= 0 ?  SWM_ARG_ID_STACKINC :
4878                             SWM_ARG_ID_STACKDEC);
4879                         stack();
4880                 }
4881         }
4882
4883         return (0);
4884 }
4885
4886 /* config options */
4887 struct config_option {
4888         char                    *optname;
4889         int                     (*func)(char*, char*, int);
4890         int                     funcflags;
4891 };
4892 struct config_option configopt[] = {
4893         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
4894         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
4895         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
4896         { "bar_border_width",           setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
4897         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
4898         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
4899         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
4900         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
4901         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
4902         { "bind",                       setconfbinding, 0 },
4903         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
4904         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
4905         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
4906         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
4907         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
4908         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
4909         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
4910         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
4911         { "verbose_layout",             setconfvalue,   SWM_S_VERBOSE_LAYOUT },
4912         { "modkey",                     setconfmodkey,  0 },
4913         { "program",                    setconfspawn,   0 },
4914         { "quirk",                      setconfquirk,   0 },
4915         { "region",                     setconfregion,  0 },
4916         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
4917         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
4918         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
4919         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
4920         { "urgent_enabled",             setconfvalue,   SWM_S_URGENT_ENABLED },
4921         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
4922         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
4923         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
4924         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
4925         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
4926         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
4927         { "autorun",                    setautorun,     0 },
4928         { "layout",                     setlayout,      0 },
4929 };
4930
4931
4932 int
4933 conf_load(char *filename)
4934 {
4935         FILE                    *config;
4936         char                    *line, *cp, *optsub, *optval;
4937         size_t                  linelen, lineno = 0;
4938         int                     wordlen, i, optind;
4939         struct config_option    *opt;
4940
4941         DNPRINTF(SWM_D_CONF, "conf_load begin\n");
4942
4943         if (filename == NULL) {
4944                 fprintf(stderr, "conf_load: no filename\n");
4945                 return (1);
4946         }
4947         if ((config = fopen(filename, "r")) == NULL) {
4948                 warn("conf_load: fopen");
4949                 return (1);
4950         }
4951
4952         while (!feof(config)) {
4953                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
4954                     == NULL) {
4955                         if (ferror(config))
4956                                 err(1, "%s", filename);
4957                         else
4958                                 continue;
4959                 }
4960                 cp = line;
4961                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4962                 if (cp[0] == '\0') {
4963                         /* empty line */
4964                         free(line);
4965                         continue;
4966                 }
4967                 /* get config option */
4968                 wordlen = strcspn(cp, "=[ \t\n");
4969                 if (wordlen == 0) {
4970                         warnx("%s: line %zd: no option found",
4971                             filename, lineno);
4972                         return (1);
4973                 }
4974                 optind = -1;
4975                 for (i = 0; i < LENGTH(configopt); i++) {
4976                         opt = &configopt[i];
4977                         if (!strncasecmp(cp, opt->optname, wordlen) &&
4978                             strlen(opt->optname) == wordlen) {
4979                                 optind = i;
4980                                 break;
4981                         }
4982                 }
4983                 if (optind == -1) {
4984                         warnx("%s: line %zd: unknown option %.*s",
4985                             filename, lineno, wordlen, cp);
4986                         return (1);
4987                 }
4988                 cp += wordlen;
4989                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4990                 /* get [selector] if any */
4991                 optsub = NULL;
4992                 if (*cp == '[') {
4993                         cp++;
4994                         wordlen = strcspn(cp, "]");
4995                         if (*cp != ']') {
4996                                 if (wordlen == 0) {
4997                                         warnx("%s: line %zd: syntax error",
4998                                             filename, lineno);
4999                                         return (1);
5000                                 }
5001                                 asprintf(&optsub, "%.*s", wordlen, cp);
5002                         }
5003                         cp += wordlen;
5004                         cp += strspn(cp, "] \t\n"); /* eat trailing */
5005                 }
5006                 cp += strspn(cp, "= \t\n"); /* eat trailing */
5007                 /* get RHS value */
5008                 optval = strdup(cp);
5009                 /* call function to deal with it all */
5010                 if (configopt[optind].func(optsub, optval,
5011                     configopt[optind].funcflags) != 0) {
5012                         fprintf(stderr, "%s line %zd: %s\n",
5013                             filename, lineno, line);
5014                         errx(1, "%s: line %zd: invalid data for %s",
5015                             filename, lineno, configopt[optind].optname);
5016                 }
5017                 free(optval);
5018                 free(optsub);
5019                 free(line);
5020         }
5021
5022         fclose(config);
5023         DNPRINTF(SWM_D_CONF, "conf_load end\n");
5024
5025         return (0);
5026 }
5027
5028 void
5029 set_child_transient(struct ws_win *win, Window *trans)
5030 {
5031         struct ws_win           *parent, *w;
5032         XWMHints                *wmh = NULL;
5033         struct swm_region       *r;
5034         struct workspace        *ws;
5035
5036         parent = find_window(win->transient);
5037         if (parent)
5038                 parent->child_trans = win;
5039         else {
5040                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
5041                     " for %lu trans %lu\n", win->id, win->transient);
5042
5043                 if (win->hints == NULL) {
5044                         fprintf(stderr, "no hints for %lu\n", win->id);
5045                         return;
5046                 }
5047
5048                 r = root_to_region(win->wa.root);
5049                 ws = r->ws;
5050                 /* parent doen't exist in our window list */
5051                 TAILQ_FOREACH(w, &ws->winlist, entry) {
5052                         if (wmh)
5053                                 XFree(wmh);
5054
5055                         if ((wmh = XGetWMHints(display, w->id)) == NULL) {
5056                                 fprintf(stderr, "can't get hints for %lu\n",
5057                                     w->id);
5058                                 continue;
5059                         }
5060
5061                         if (win->hints->window_group != wmh->window_group)
5062                                 continue;
5063
5064                         w->child_trans = win;
5065                         win->transient = w->id;
5066                         *trans = w->id;
5067                         DNPRINTF(SWM_D_MISC, "set_child_transient: asjusting "
5068                             "transient to %lu\n", win->transient);
5069                         break;
5070                 }
5071         }
5072
5073         if (wmh)
5074                 XFree(wmh);
5075 }
5076
5077 long
5078 window_get_pid(Window win)
5079 {
5080         Atom                    actual_type_return;
5081         int                     actual_format_return = 0;
5082         unsigned long           nitems_return = 0;
5083         unsigned long           bytes_after_return = 0;
5084         long                    *pid = NULL;
5085         long                    ret = 0;
5086         const char              *errstr;
5087         unsigned char           *prop = NULL;
5088
5089         if (XGetWindowProperty(display, win,
5090             XInternAtom(display, "_NET_WM_PID", False), 0, 1, False,
5091             XA_CARDINAL, &actual_type_return, &actual_format_return,
5092             &nitems_return, &bytes_after_return,
5093             (unsigned char**)(void*)&pid) != Success)
5094                 goto tryharder;
5095         if (actual_type_return != XA_CARDINAL)
5096                 goto tryharder;
5097         if (pid == NULL)
5098                 goto tryharder;
5099
5100         ret = *pid;
5101         XFree(pid);
5102
5103         return (ret);
5104
5105 tryharder:
5106         if (XGetWindowProperty(display, win,
5107             XInternAtom(display, "_SWM_PID", False), 0, SWM_PROPLEN, False,
5108             XA_STRING, &actual_type_return, &actual_format_return,
5109             &nitems_return, &bytes_after_return, &prop) != Success)
5110                 return (0);
5111         if (actual_type_return != XA_STRING)
5112                 return (0);
5113         if (prop == NULL)
5114                 return (0);
5115
5116         ret = strtonum((const char *)prop, 0, UINT_MAX, &errstr);
5117         /* ignore error because strtonum returns 0 anyway */
5118         XFree(prop);
5119
5120         return (ret);
5121 }
5122
5123 struct ws_win *
5124 manage_window(Window id)
5125 {
5126         Window                  trans = 0;
5127         struct workspace        *ws;
5128         struct ws_win           *win, *ww;
5129         int                     format, i, ws_idx, n, border_me = 0;
5130         unsigned long           nitems, bytes;
5131         Atom                    ws_idx_atom = 0, type;
5132         Atom                    *prot = NULL, *pp;
5133         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
5134         struct swm_region       *r;
5135         long                    mask;
5136         const char              *errstr;
5137         XWindowChanges          wc;
5138         struct pid_e            *p;
5139
5140         if ((win = find_window(id)) != NULL)
5141                 return (win);   /* already being managed */
5142
5143         /* see if we are on the unmanaged list */
5144         if ((win = find_unmanaged_window(id)) != NULL) {
5145                 DNPRINTF(SWM_D_MISC, "manage previously unmanaged window "
5146                     "%lu\n", win->id);
5147                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
5148                 if (win->transient) {
5149                         set_child_transient(win, &trans);
5150                 } if (trans && (ww = find_window(trans)))
5151                         TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
5152                 else
5153                         TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
5154                 ewmh_update_actions(win);
5155                 return (win);
5156         }
5157
5158         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
5159                 errx(1, "calloc: failed to allocate memory for new window");
5160
5161         win->id = id;
5162
5163         /* see if we need to override the workspace */
5164         p = find_pid(window_get_pid(id));
5165
5166         /* Get all the window data in one shot */
5167         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
5168         if (ws_idx_atom) {
5169                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
5170                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
5171         }
5172         XGetWindowAttributes(display, id, &win->wa);
5173         XGetWMNormalHints(display, id, &win->sh, &mask);
5174         win->hints = XGetWMHints(display, id);
5175         XGetTransientForHint(display, id, &trans);
5176         if (trans) {
5177                 win->transient = trans;
5178                 set_child_transient(win, &trans);
5179                 DNPRINTF(SWM_D_MISC, "manage_window: win %lu transient %lu\n",
5180                     win->id, win->transient);
5181         }
5182
5183         /* get supported protocols */
5184         if (XGetWMProtocols(display, id, &prot, &n)) {
5185                 for (i = 0, pp = prot; i < n; i++, pp++) {
5186                         if (*pp == takefocus)
5187                                 win->take_focus = 1;
5188                         if (*pp == adelete)
5189                                 win->can_delete = 1;
5190                 }
5191                 if (prot)
5192                         XFree(prot);
5193         }
5194
5195         win->iconic = get_iconic(win);
5196
5197         /*
5198          * Figure out where to put the window. If it was previously assigned to
5199          * a workspace (either by spawn() or manually moving), and isn't
5200          * transient, * put it in the same workspace
5201          */
5202         r = root_to_region(win->wa.root);
5203         if (p) {
5204                 ws = &r->s->ws[p->ws];
5205                 TAILQ_REMOVE(&pidlist, p, entry);
5206                 free(p);
5207                 p = NULL;
5208         } else if (prop && win->transient == 0) {
5209                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
5210                 ws_idx = strtonum((const char *)prop, 0, 9, &errstr);
5211                 if (errstr) {
5212                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
5213                             errstr, prop);
5214                 }
5215                 ws = &r->s->ws[ws_idx];
5216         } else {
5217                 ws = r->ws;
5218                 /* this should launch transients in the same ws as parent */
5219                 if (id && trans)
5220                         if ((ww = find_window(trans)) != NULL)
5221                                 if (ws->r) {
5222                                         ws = ww->ws;
5223                                         if (ww->ws->r)
5224                                                 r = ww->ws->r;
5225                                         else
5226                                                 fprintf(stderr,
5227                                                     "fix this bug mcbride\n");
5228                                         border_me = 1;
5229                                 }
5230         }
5231
5232         /* set up the window layout */
5233         win->id = id;
5234         win->ws = ws;
5235         win->s = r->s;  /* this never changes */
5236         if (trans && (ww = find_window(trans)))
5237                 TAILQ_INSERT_AFTER(&ws->winlist, ww, win, entry);
5238         else
5239                 TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
5240
5241         win->g.w = win->wa.width;
5242         win->g.h = win->wa.height;
5243         win->g.x = win->wa.x;
5244         win->g.y = win->wa.y;
5245         win->g_floatvalid = 0;
5246         win->floatmaxed = 0;
5247         win->ewmh_flags = 0;
5248
5249         /* Set window properties so we can remember this after reincarnation */
5250         if (ws_idx_atom && prop == NULL &&
5251             snprintf((char *)ws_idx_str, SWM_PROPLEN, "%d", ws->idx) <
5252                 SWM_PROPLEN) {
5253                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
5254                     ws_idx_str);
5255                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
5256                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
5257         }
5258         if (prop)
5259                 XFree(prop);
5260
5261         ewmh_autoquirk(win);
5262
5263         if (XGetClassHint(display, win->id, &win->ch)) {
5264                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
5265                     win->ch.res_class, win->ch.res_name);
5266
5267                 /* java is retarded so treat it special */
5268                 if (strstr(win->ch.res_name, "sun-awt")) {
5269                         win->java = 1;
5270                         border_me = 1;
5271                 }
5272
5273                 for (i = 0; i < quirks_length; i++){
5274                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
5275                             !strcmp(win->ch.res_name, quirks[i].name)) {
5276                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
5277                                     win->ch.res_class, win->ch.res_name);
5278                                 if (quirks[i].quirk & SWM_Q_FLOAT) {
5279                                         win->floating = 1;
5280                                         border_me = 1;
5281                                 }
5282                                 win->quirks = quirks[i].quirk;
5283                         }
5284                 }
5285         }
5286
5287         /* alter window position if quirky */
5288         if (win->quirks & SWM_Q_ANYWHERE) {
5289                 win->manual = 1; /* don't center the quirky windows */
5290                 bzero(&wc, sizeof wc);
5291                 mask = 0;
5292                 if (bar_enabled && win->g.y < bar_height) {
5293                         win->g.y = wc.y = bar_height;
5294                         mask |= CWY;
5295                 }
5296                 if (win->g.w + win->g.x > WIDTH(r)) {
5297                         win->g.x = wc.x = WIDTH(r) - win->g.w - 2;
5298                         mask |= CWX;
5299                 }
5300                 border_me = 1;
5301         }
5302
5303         /* Reset font sizes (the bruteforce way; no default keybinding). */
5304         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
5305                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
5306                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
5307                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
5308                         fake_keypress(win, XK_KP_Add, ShiftMask);
5309         }
5310
5311         ewmh_get_win_state(win);
5312         ewmh_update_actions(win);
5313         ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
5314
5315         /* border me */
5316         if (border_me) {
5317                 bzero(&wc, sizeof wc);
5318                 wc.border_width = border_width;
5319                 mask = CWBorderWidth;
5320                 XConfigureWindow(display, win->id, mask, &wc);
5321         }
5322
5323         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
5324             PropertyChangeMask | StructureNotifyMask);
5325
5326         /* floaters need to be mapped if they are in the current workspace */
5327         if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
5328                 XMapRaised(display, win->id);
5329
5330         return (win);
5331 }
5332
5333 void
5334 free_window(struct ws_win *win)
5335 {
5336         DNPRINTF(SWM_D_MISC, "free_window:  %lu\n", win->id);
5337
5338         if (win == NULL)
5339                 return;
5340
5341         /* needed for restart wm */
5342         set_win_state(win, WithdrawnState);
5343
5344         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
5345
5346         if (win->ch.res_class)
5347                 XFree(win->ch.res_class);
5348         if (win->ch.res_name)
5349                 XFree(win->ch.res_name);
5350
5351         kill_refs(win);
5352
5353         /* paint memory */
5354         memset(win, 0xff, sizeof *win); /* XXX kill later */
5355
5356         free(win);
5357 }
5358
5359 void
5360 unmanage_window(struct ws_win *win)
5361 {
5362         struct ws_win           *parent;
5363
5364         if (win == NULL)
5365                 return;
5366
5367         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
5368
5369         if (win->transient) {
5370                 parent = find_window(win->transient);
5371                 if (parent)
5372                         parent->child_trans = NULL;
5373         }
5374
5375         /* focus on root just in case */
5376         XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
5377
5378         focus_prev(win);
5379
5380         TAILQ_REMOVE(&win->ws->winlist, win, entry);
5381         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
5382
5383         kill_refs(win);
5384 }
5385
5386 void
5387 focus_magic(struct ws_win *win)
5388 {
5389         DNPRINTF(SWM_D_FOCUS, "focus_magic: %lu\n", WINID(win));
5390
5391         if (win == NULL)
5392                 return;
5393
5394         if (win->child_trans) {
5395                 /* win = parent & has a transient so focus on that */
5396                 if (win->java) {
5397                         focus_win(win->child_trans);
5398                         if (win->child_trans->take_focus)
5399                                 client_msg(win, takefocus);
5400                 } else {
5401                         /* make sure transient hasn't dissapeared */
5402                         if (validate_win(win->child_trans) == 0) {
5403                                 focus_win(win->child_trans);
5404                                 if (win->child_trans->take_focus)
5405                                         client_msg(win->child_trans, takefocus);
5406                         } else {
5407                                 win->child_trans = NULL;
5408                                 focus_win(win);
5409                                 if (win->take_focus)
5410                                         client_msg(win, takefocus);
5411                         }
5412                 }
5413         } else {
5414                 /* regular focus */
5415                 focus_win(win);
5416                 if (win->take_focus)
5417                         client_msg(win, takefocus);
5418         }
5419 }
5420
5421 void
5422 expose(XEvent *e)
5423 {
5424         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
5425 }
5426
5427 void
5428 keypress(XEvent *e)
5429 {
5430         unsigned int            i;
5431         KeySym                  keysym;
5432         XKeyEvent               *ev = &e->xkey;
5433
5434         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
5435
5436         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
5437         for (i = 0; i < keys_length; i++)
5438                 if (keysym == keys[i].keysym
5439                     && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
5440                     && keyfuncs[keys[i].funcid].func) {
5441                         if (keys[i].funcid == kf_spawn_custom)
5442                                 spawn_custom(
5443                                     root_to_region(ev->root),
5444                                     &(keyfuncs[keys[i].funcid].args),
5445                                     keys[i].spawn_name
5446                                     );
5447                         else
5448                                 keyfuncs[keys[i].funcid].func(
5449                                     root_to_region(ev->root),
5450                                     &(keyfuncs[keys[i].funcid].args)
5451                                     );
5452                 }
5453 }
5454
5455 void
5456 buttonpress(XEvent *e)
5457 {
5458         struct ws_win           *win;
5459         int                     i, action;
5460         XButtonPressedEvent     *ev = &e->xbutton;
5461
5462         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
5463
5464         action = root_click;
5465         if ((win = find_window(ev->window)) == NULL)
5466                 return;
5467
5468         focus_magic(win);
5469         action = client_click;
5470
5471         for (i = 0; i < LENGTH(buttons); i++)
5472                 if (action == buttons[i].action && buttons[i].func &&
5473                     buttons[i].button == ev->button &&
5474                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
5475                         buttons[i].func(win, &buttons[i].args);
5476 }
5477
5478 void
5479 configurerequest(XEvent *e)
5480 {
5481         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
5482         struct ws_win           *win;
5483         int                     new = 0;
5484         XWindowChanges          wc;
5485
5486         if ((win = find_window(ev->window)) == NULL)
5487                 if ((win = find_unmanaged_window(ev->window)) == NULL)
5488                         new = 1;
5489
5490         if (new) {
5491                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
5492                     ev->window);
5493                 bzero(&wc, sizeof wc);
5494                 wc.x = ev->x;
5495                 wc.y = ev->y;
5496                 wc.width = ev->width;
5497                 wc.height = ev->height;
5498                 wc.border_width = ev->border_width;
5499                 wc.sibling = ev->above;
5500                 wc.stack_mode = ev->detail;
5501                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
5502         } else {
5503                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
5504                     ev->window);
5505                 config_win(win, ev);
5506         }
5507 }
5508
5509 void
5510 configurenotify(XEvent *e)
5511 {
5512         struct ws_win           *win;
5513         long                    mask;
5514
5515         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
5516             e->xconfigure.window);
5517
5518         win = find_window(e->xconfigure.window);
5519         if (win) {
5520                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5521                 adjust_font(win);
5522                 if (font_adjusted)
5523                         stack();
5524                 if (focus_mode == SWM_FOCUS_DEFAULT)
5525                         drain_enter_notify();
5526         }
5527 }
5528
5529 void
5530 destroynotify(XEvent *e)
5531 {
5532         struct ws_win           *win;
5533         XDestroyWindowEvent     *ev = &e->xdestroywindow;
5534
5535         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
5536
5537         if ((win = find_window(ev->window)) == NULL) {
5538                 if ((win = find_unmanaged_window(ev->window)) == NULL)
5539                         return;
5540                 free_window(win);
5541                 return;
5542         }
5543
5544         /* make sure we focus on something */
5545         win->floating = 0;
5546
5547         unmanage_window(win);
5548         stack();
5549         if (focus_mode == SWM_FOCUS_DEFAULT)
5550                 drain_enter_notify();
5551         free_window(win);
5552 }
5553
5554 void
5555 enternotify(XEvent *e)
5556 {
5557         XCrossingEvent          *ev = &e->xcrossing;
5558         XEvent                  cne;
5559         struct ws_win           *win;
5560 #if 0
5561         struct ws_win           *w;
5562         Window                  focus_return;
5563         int                     revert_to_return;
5564 #endif
5565         DNPRINTF(SWM_D_FOCUS, "enternotify: window: %lu mode %d detail %d root "
5566             "%lu subwindow %lu same_screen %d focus %d state %d\n",
5567             ev->window, ev->mode, ev->detail, ev->root, ev->subwindow,
5568             ev->same_screen, ev->focus, ev->state);
5569
5570         switch (focus_mode) {
5571         case SWM_FOCUS_DEFAULT:
5572                 break;
5573         case SWM_FOCUS_FOLLOW:
5574                 break;
5575         case SWM_FOCUS_SYNERGY:
5576 #if 0
5577         /*
5578          * all these checks need to be in this order because the
5579          * XCheckTypedWindowEvent relies on weeding out the previous events
5580          *
5581          * making this code an option would enable a follow mouse for focus
5582          * feature
5583          */
5584
5585         /*
5586          * state is set when we are switching workspaces and focus is set when
5587          * the window or a subwindow already has focus (occurs during restart).
5588          *
5589          * Only honor the focus flag if last_focus_event is not FocusOut,
5590          * this allows scrotwm to continue to control focus when another
5591          * program is also playing with it.
5592          */
5593         if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
5594                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
5595                 return;
5596         }
5597
5598         /*
5599          * happens when a window is created or destroyed and the border
5600          * crosses the mouse pointer and when switching ws
5601          *
5602          * we need the subwindow test to see if we came from root in order
5603          * to give focus to floaters
5604          */
5605         if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
5606             ev->subwindow == 0) {
5607                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
5608                 return;
5609         }
5610
5611         /* this window already has focus */
5612         if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
5613                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
5614                 return;
5615         }
5616
5617         /* this window is being deleted or moved to another ws */
5618         if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
5619             &cne) == True) {
5620                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
5621                 XPutBackEvent(display, &cne);
5622                 return;
5623         }
5624
5625         if ((win = find_window(ev->window)) == NULL) {
5626                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5627                 return;
5628         }
5629
5630         /*
5631          * In fullstack kill all enters unless they come from a different ws
5632          * (i.e. another region) or focus has been grabbed externally.
5633          */
5634         if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
5635             last_focus_event != FocusOut) {
5636                 XGetInputFocus(display, &focus_return, &revert_to_return);
5637                 if ((w = find_window(focus_return)) == NULL ||
5638                     w->ws == win->ws) {
5639                         DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
5640                         return;
5641                 }
5642         }
5643 #endif
5644                 break;
5645         }
5646
5647         if ((win = find_window(ev->window)) == NULL) {
5648                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5649                 return;
5650         }
5651
5652         /*
5653          * if we have more enternotifies let them handle it in due time
5654          */
5655         if (XCheckTypedEvent(display, EnterNotify, &cne) == True) {
5656                 DNPRINTF(SWM_D_EVENT,
5657                     "ignoring enternotify: got more enternotify\n");
5658                 XPutBackEvent(display, &cne);
5659                 return;
5660         }
5661
5662         focus_magic(win);
5663 }
5664
5665 /* lets us use one switch statement for arbitrary mode/detail combinations */
5666 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
5667
5668 void
5669 focusevent(XEvent *e)
5670 {
5671 #if 0
5672         struct ws_win           *win;
5673         u_int32_t               mode_detail;
5674         XFocusChangeEvent       *ev = &e->xfocus;
5675
5676         DNPRINTF(SWM_D_EVENT, "focusevent: %s window: %lu mode %d detail %d\n",
5677             ev->type == FocusIn ? "entering" : "leaving",
5678             ev->window, ev->mode, ev->detail);
5679
5680         if (last_focus_event == ev->type) {
5681                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent: bad ordering\n");
5682                 return;
5683         }
5684
5685         last_focus_event = ev->type;
5686         mode_detail = MERGE_MEMBERS(ev->mode, ev->detail);
5687
5688         switch (mode_detail) {
5689         /* synergy client focus operations */
5690         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinear):
5691         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinearVirtual):
5692
5693         /* synergy server focus operations */
5694         case MERGE_MEMBERS(NotifyWhileGrabbed, NotifyNonlinear):
5695
5696         /* Entering applications like rdesktop that mangle the pointer */
5697         case MERGE_MEMBERS(NotifyNormal, NotifyPointer):
5698
5699                 if ((win = find_window(e->xfocus.window)) != NULL && win->ws->r)
5700                         XSetWindowBorder(display, win->id,
5701                             win->ws->r->s->c[ev->type == FocusIn ?
5702                             SWM_S_COLOR_FOCUS : SWM_S_COLOR_UNFOCUS].color);
5703                 break;
5704         default:
5705                 fprintf(stderr, "ignoring focusevent\n");
5706                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent\n");
5707                 break;
5708         }
5709 #endif
5710 }
5711
5712 void
5713 mapnotify(XEvent *e)
5714 {
5715         struct ws_win           *win;
5716         XMapEvent               *ev = &e->xmap;
5717
5718         DNPRINTF(SWM_D_EVENT, "mapnotify: window: %lu\n", ev->window);
5719
5720         win = manage_window(ev->window);
5721         if (win)
5722                 set_win_state(win, NormalState);
5723 }
5724
5725 void
5726 mappingnotify(XEvent *e)
5727 {
5728         XMappingEvent           *ev = &e->xmapping;
5729
5730         XRefreshKeyboardMapping(ev);
5731         if (ev->request == MappingKeyboard)
5732                 grabkeys();
5733 }
5734
5735 void
5736 maprequest(XEvent *e)
5737 {
5738         struct ws_win           *win;
5739         struct swm_region       *r;
5740         XWindowAttributes       wa;
5741         XMapRequestEvent        *ev = &e->xmaprequest;
5742
5743         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
5744             e->xmaprequest.window);
5745
5746         if (!XGetWindowAttributes(display, ev->window, &wa))
5747                 return;
5748         if (wa.override_redirect)
5749                 return;
5750
5751         win = manage_window(e->xmaprequest.window);
5752         if (win == NULL)
5753                 return; /* can't happen */
5754
5755         stack();
5756
5757         /* make new win focused */
5758         r = root_to_region(win->wa.root);
5759         if (win->ws == r->ws)
5760                 focus_magic(win);
5761 }
5762
5763 void
5764 propertynotify(XEvent *e)
5765 {
5766         struct ws_win           *win;
5767         XPropertyEvent          *ev = &e->xproperty;
5768
5769         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
5770             ev->window);
5771
5772         win = find_window(ev->window);
5773         if (win == NULL)
5774                 return;
5775
5776         if (ev->state == PropertyDelete && ev->atom == a_swm_iconic) {
5777                 update_iconic(win, 0);
5778                 XMapRaised(display, win->id);
5779                 stack();
5780                 focus_win(win);
5781                 return;
5782         }
5783
5784         switch (ev->atom) {
5785         case XA_WM_NORMAL_HINTS:
5786 #if 0
5787                 long            mask;
5788                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5789                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
5790                 if (win->sh.flags & PMinSize) {
5791                         win->g.w = win->sh.min_width;
5792                         win->g.h = win->sh.min_height;
5793                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
5794                 }
5795                 XMoveResizeWindow(display, win->id,
5796                     win->g.x, win->g.y, win->g.w, win->g.h);
5797 #endif
5798                 if (window_name_enabled)
5799                         bar_update();
5800                 break;
5801         default:
5802                 break;
5803         }
5804 }
5805
5806 void
5807 unmapnotify(XEvent *e)
5808 {
5809         struct ws_win           *win;
5810
5811         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
5812
5813         /* determine if we need to help unmanage this window */
5814         win = find_window(e->xunmap.window);
5815         if (win == NULL)
5816                 return;
5817
5818         if (getstate(e->xunmap.window) == NormalState) {
5819                 unmanage_window(win);
5820                 stack();
5821
5822                 /* giant hack for apps that don't destroy transient windows */
5823                 /* eat a bunch of events to prevent remanaging the window */
5824                 XEvent                  cne;
5825                 while (XCheckWindowEvent(display, e->xunmap.window,
5826                     EnterWindowMask, &cne))
5827                         ;
5828                 while (XCheckWindowEvent(display, e->xunmap.window,
5829                     StructureNotifyMask, &cne))
5830                         ;
5831                 while (XCheckWindowEvent(display, e->xunmap.window,
5832                     SubstructureNotifyMask, &cne))
5833                         ;
5834                 /* resend unmap because we ated it */
5835                 XUnmapWindow(display, e->xunmap.window);
5836         }
5837
5838         if (focus_mode == SWM_FOCUS_DEFAULT)
5839                 drain_enter_notify();
5840 }
5841
5842 void
5843 visibilitynotify(XEvent *e)
5844 {
5845         int                     i;
5846         struct swm_region       *r;
5847
5848         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
5849             e->xvisibility.window);
5850         if (e->xvisibility.state == VisibilityUnobscured)
5851                 for (i = 0; i < ScreenCount(display); i++)
5852                         TAILQ_FOREACH(r, &screens[i].rl, entry)
5853                                 if (e->xvisibility.window == r->bar_window)
5854                                         bar_update();
5855 }
5856
5857 void
5858 clientmessage(XEvent *e)
5859 {
5860         XClientMessageEvent *ev;
5861         struct ws_win *win;
5862
5863         ev = &e->xclient;
5864
5865         win = find_window(ev->window);
5866         if (win == NULL)
5867                 return;
5868
5869         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%lx type: %ld \n",
5870             ev->window, ev->message_type);
5871
5872         if (ev->message_type == ewmh[_NET_ACTIVE_WINDOW].atom) {
5873                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW \n");
5874                 focus_win(win);
5875         }
5876         if (ev->message_type == ewmh[_NET_CLOSE_WINDOW].atom) {
5877                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW \n");
5878                 if (win->can_delete)
5879                         client_msg(win, adelete);
5880                 else
5881                         XKillClient(display, win->id);
5882         }
5883         if (ev->message_type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
5884                 DNPRINTF(SWM_D_EVENT,
5885                     "clientmessage: _NET_MOVERESIZE_WINDOW \n");
5886                 if (win->floating) {
5887                         if (ev->data.l[0] & (1<<8)) /* x */
5888                                 win->g.x = ev->data.l[1];
5889                         if (ev->data.l[0] & (1<<9)) /* y */
5890                                 win->g.y = ev->data.l[2];
5891                         if (ev->data.l[0] & (1<<10)) /* width */
5892                                 win->g.w = ev->data.l[3];
5893                         if (ev->data.l[0] & (1<<11)) /* height */
5894                                 win->g.h = ev->data.l[4];
5895                 }
5896                 else {
5897                         /* TODO: Change stack sizes */
5898                 }
5899                 config_win(win, NULL);
5900         }
5901         if (ev->message_type == ewmh[_NET_WM_STATE].atom) {
5902                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE \n");
5903                 ewmh_update_win_state(win, ev->data.l[1], ev->data.l[0]);
5904                 if (ev->data.l[2])
5905                         ewmh_update_win_state(win, ev->data.l[2],
5906                             ev->data.l[0]);
5907
5908                 stack();
5909         }
5910 }
5911
5912 int
5913 xerror_start(Display *d, XErrorEvent *ee)
5914 {
5915         other_wm = 1;
5916         return (-1);
5917 }
5918
5919 int
5920 xerror(Display *d, XErrorEvent *ee)
5921 {
5922         /* fprintf(stderr, "error: %p %p\n", display, ee); */
5923         return (-1);
5924 }
5925
5926 int
5927 active_wm(void)
5928 {
5929         other_wm = 0;
5930         xerrorxlib = XSetErrorHandler(xerror_start);
5931
5932         /* this causes an error if some other window manager is running */
5933         XSelectInput(display, DefaultRootWindow(display),
5934             SubstructureRedirectMask);
5935         XSync(display, False);
5936         if (other_wm)
5937                 return (1);
5938
5939         XSetErrorHandler(xerror);
5940         XSync(display, False);
5941         return (0);
5942 }
5943
5944 void
5945 new_region(struct swm_screen *s, int x, int y, int w, int h)
5946 {
5947         struct swm_region       *r, *n;
5948         struct workspace        *ws = NULL;
5949         int                     i;
5950
5951         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
5952              s->idx, w, h, x, y);
5953
5954         /* remove any conflicting regions */
5955         n = TAILQ_FIRST(&s->rl);
5956         while (n) {
5957                 r = n;
5958                 n = TAILQ_NEXT(r, entry);
5959                 if (X(r) < (x + w) &&
5960                     (X(r) + WIDTH(r)) > x &&
5961                     Y(r) < (y + h) &&
5962                     (Y(r) + HEIGHT(r)) > y) {
5963                         if (r->ws->r != NULL)
5964                                 r->ws->old_r = r->ws->r;
5965                         r->ws->r = NULL;
5966                         XDestroyWindow(display, r->bar_window);
5967                         TAILQ_REMOVE(&s->rl, r, entry);
5968                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
5969                 }
5970         }
5971
5972         /* search old regions for one to reuse */
5973
5974         /* size + location match */
5975         TAILQ_FOREACH(r, &s->orl, entry)
5976                 if (X(r) == x && Y(r) == y &&
5977                     HEIGHT(r) == h && WIDTH(r) == w)
5978                         break;
5979
5980         /* size match */
5981         TAILQ_FOREACH(r, &s->orl, entry)
5982                 if (HEIGHT(r) == h && WIDTH(r) == w)
5983                         break;
5984
5985         if (r != NULL) {
5986                 TAILQ_REMOVE(&s->orl, r, entry);
5987                 /* try to use old region's workspace */
5988                 if (r->ws->r == NULL)
5989                         ws = r->ws;
5990         } else
5991                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
5992                         errx(1, "calloc: failed to allocate memory for screen");
5993
5994         /* if we don't have a workspace already, find one */
5995         if (ws == NULL) {
5996                 for (i = 0; i < SWM_WS_MAX; i++)
5997                         if (s->ws[i].r == NULL) {
5998                                 ws = &s->ws[i];
5999                                 break;
6000                         }
6001         }
6002
6003         if (ws == NULL)
6004                 errx(1, "no free workspaces\n");
6005
6006         X(r) = x;
6007         Y(r) = y;
6008         WIDTH(r) = w;
6009         HEIGHT(r) = h;
6010         r->s = s;
6011         r->ws = ws;
6012         r->ws_prior = NULL;
6013         ws->r = r;
6014         outputs++;
6015         TAILQ_INSERT_TAIL(&s->rl, r, entry);
6016 }
6017
6018 void
6019 scan_xrandr(int i)
6020 {
6021 #ifdef SWM_XRR_HAS_CRTC
6022         XRRCrtcInfo             *ci;
6023         XRRScreenResources      *sr;
6024         int                     c;
6025         int                     ncrtc = 0;
6026 #endif /* SWM_XRR_HAS_CRTC */
6027         struct swm_region       *r;
6028
6029
6030         if (i >= ScreenCount(display))
6031                 errx(1, "invalid screen");
6032
6033         /* remove any old regions */
6034         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
6035                 r->ws->old_r = r->ws->r = NULL;
6036                 XDestroyWindow(display, r->bar_window);
6037                 TAILQ_REMOVE(&screens[i].rl, r, entry);
6038                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
6039         }
6040         outputs = 0;
6041
6042         /* map virtual screens onto physical screens */
6043 #ifdef SWM_XRR_HAS_CRTC
6044         if (xrandr_support) {
6045                 sr = XRRGetScreenResources(display, screens[i].root);
6046                 if (sr == NULL)
6047                         new_region(&screens[i], 0, 0,
6048                             DisplayWidth(display, i),
6049                             DisplayHeight(display, i));
6050                 else
6051                         ncrtc = sr->ncrtc;
6052
6053                 for (c = 0, ci = NULL; c < ncrtc; c++) {
6054                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
6055                         if (ci->noutput == 0)
6056                                 continue;
6057
6058                         if (ci != NULL && ci->mode == None)
6059                                 new_region(&screens[i], 0, 0,
6060                                     DisplayWidth(display, i),
6061                                     DisplayHeight(display, i));
6062                         else
6063                                 new_region(&screens[i],
6064                                     ci->x, ci->y, ci->width, ci->height);
6065                 }
6066                 if (ci)
6067                         XRRFreeCrtcInfo(ci);
6068                 XRRFreeScreenResources(sr);
6069         } else
6070 #endif /* SWM_XRR_HAS_CRTC */
6071         {
6072                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
6073                     DisplayHeight(display, i));
6074         }
6075 }
6076
6077 void
6078 screenchange(XEvent *e) {
6079         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
6080         struct swm_region               *r;
6081         int                             i;
6082
6083         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
6084
6085         if (!XRRUpdateConfiguration(e))
6086                 return;
6087
6088         /* silly event doesn't include the screen index */
6089         for (i = 0; i < ScreenCount(display); i++)
6090                 if (screens[i].root == xe->root)
6091                         break;
6092         if (i >= ScreenCount(display))
6093                 errx(1, "screenchange: screen not found\n");
6094
6095         /* brute force for now, just re-enumerate the regions */
6096         scan_xrandr(i);
6097
6098         /* add bars to all regions */
6099         for (i = 0; i < ScreenCount(display); i++)
6100                 TAILQ_FOREACH(r, &screens[i].rl, entry)
6101                         bar_setup(r);
6102         stack();
6103         if (focus_mode == SWM_FOCUS_DEFAULT)
6104                 drain_enter_notify();
6105 }
6106
6107 void
6108 grab_windows(void)
6109 {
6110         Window                  d1, d2, *wins = NULL;
6111         XWindowAttributes       wa;
6112         unsigned int            no;
6113         int                     i, j;
6114         long                    state, manage;
6115
6116         for (i = 0; i < ScreenCount(display); i++) {
6117                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
6118                         continue;
6119
6120                 /* attach windows to a region */
6121                 /* normal windows */
6122                 for (j = 0; j < no; j++) {
6123                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
6124                             wa.override_redirect ||
6125                             XGetTransientForHint(display, wins[j], &d1))
6126                                 continue;
6127
6128                         state = getstate(wins[j]);
6129                         manage = state == IconicState;
6130                         if (wa.map_state == IsViewable || manage)
6131                                 manage_window(wins[j]);
6132                 }
6133                 /* transient windows */
6134                 for (j = 0; j < no; j++) {
6135                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
6136                             wa.override_redirect)
6137                                 continue;
6138
6139                         state = getstate(wins[j]);
6140                         manage = state == IconicState;
6141                         if (XGetTransientForHint(display, wins[j], &d1) &&
6142                             manage)
6143                                 manage_window(wins[j]);
6144                 }
6145                 if (wins) {
6146                         XFree(wins);
6147                         wins = NULL;
6148                 }
6149         }
6150 }
6151
6152 void
6153 setup_screens(void)
6154 {
6155         int                     i, j, k;
6156         int                     errorbase, major, minor;
6157         struct workspace        *ws;
6158
6159         if ((screens = calloc(ScreenCount(display),
6160              sizeof(struct swm_screen))) == NULL)
6161                 errx(1, "calloc: screens");
6162
6163         /* initial Xrandr setup */
6164         xrandr_support = XRRQueryExtension(display,
6165             &xrandr_eventbase, &errorbase);
6166         if (xrandr_support)
6167                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
6168                         xrandr_support = 0;
6169
6170         /* map physical screens */
6171         for (i = 0; i < ScreenCount(display); i++) {
6172                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
6173                 screens[i].idx = i;
6174                 TAILQ_INIT(&screens[i].rl);
6175                 TAILQ_INIT(&screens[i].orl);
6176                 screens[i].root = RootWindow(display, i);
6177
6178                 /* set default colors */
6179                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
6180                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
6181                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
6182                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
6183                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
6184
6185                 /* set default cursor */
6186                 XDefineCursor(display, screens[i].root,
6187                     XCreateFontCursor(display, XC_left_ptr));
6188
6189                 /* init all workspaces */
6190                 /* XXX these should be dynamically allocated too */
6191                 for (j = 0; j < SWM_WS_MAX; j++) {
6192                         ws = &screens[i].ws[j];
6193                         ws->idx = j;
6194                         ws->focus = NULL;
6195                         ws->r = NULL;
6196                         ws->old_r = NULL;
6197                         TAILQ_INIT(&ws->winlist);
6198                         TAILQ_INIT(&ws->unmanagedlist);
6199
6200                         for (k = 0; layouts[k].l_stack != NULL; k++)
6201                                 if (layouts[k].l_config != NULL)
6202                                         layouts[k].l_config(ws,
6203                                             SWM_ARG_ID_STACKINIT);
6204                         ws->cur_layout = &layouts[0];
6205                         ws->cur_layout->l_string(ws);
6206                 }
6207
6208                 scan_xrandr(i);
6209
6210                 if (xrandr_support)
6211                         XRRSelectInput(display, screens[i].root,
6212                             RRScreenChangeNotifyMask);
6213         }
6214 }
6215
6216 void
6217 setup_globals(void)
6218 {
6219         if ((bar_fonts[0] = strdup("-*-terminus-medium-*-*-*-*-*-*-*-*-*-*-*"))
6220             == NULL)
6221                 err(1, "setup_globals: strdup");
6222         if ((bar_fonts[1] = strdup("-*-times-medium-r-*-*-*-*-*-*-*-*-*-*"))
6223             == NULL)
6224                 err(1, "setup_globals: strdup");
6225         if ((bar_fonts[2] = strdup("-misc-fixed-medium-r-*-*-*-*-*-*-*-*-*-*"))
6226             == NULL)
6227                 err(1, "setup_globals: strdup");
6228         if ((spawn_term[0] = strdup("xterm")) == NULL)
6229                 err(1, "setup_globals: strdup");
6230         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
6231                 errx(1, "strdup");
6232 }
6233
6234 void
6235 workaround(void)
6236 {
6237         int                     i;
6238         Atom                    netwmcheck, netwmname, utf8_string;
6239         Window                  root, win;
6240
6241         /* work around sun jdk bugs, code from wmname */
6242         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
6243         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
6244         utf8_string = XInternAtom(display, "UTF8_STRING", False);
6245         for (i = 0; i < ScreenCount(display); i++) {
6246                 root = screens[i].root;
6247                 win = XCreateSimpleWindow(display,root, 0, 0, 1, 1, 0,
6248                     screens[i].c[SWM_S_COLOR_UNFOCUS].color,
6249                     screens[i].c[SWM_S_COLOR_UNFOCUS].color);
6250
6251                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
6252                     PropModeReplace, (unsigned char *)&win,1);
6253                 XChangeProperty(display, win, netwmcheck, XA_WINDOW, 32,
6254                     PropModeReplace, (unsigned char *)&win,1);
6255                 XChangeProperty(display, win, netwmname, utf8_string, 8,
6256                     PropModeReplace, (unsigned char*)"LG3D", strlen("LG3D"));
6257         }
6258 }
6259
6260 int
6261 main(int argc, char *argv[])
6262 {
6263         struct passwd           *pwd;
6264         struct swm_region       *r, *rr;
6265         struct ws_win           *winfocus = NULL;
6266         struct timeval          tv;
6267         union arg               a;
6268         char                    conf[PATH_MAX], *cfile = NULL;
6269         struct stat             sb;
6270         XEvent                  e;
6271         int                     xfd, i;
6272         fd_set                  rd;
6273         struct sigaction        sact;
6274
6275         start_argv = argv;
6276         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
6277             SWM_VERSION, cvstag);
6278         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
6279                 warnx("no locale support");
6280
6281         if (!(display = XOpenDisplay(0)))
6282                 errx(1, "can not open display");
6283
6284         if (active_wm())
6285                 errx(1, "other wm running");
6286
6287         /* handle some signals */
6288         bzero(&sact, sizeof(sact));
6289         sigemptyset(&sact.sa_mask);
6290         sact.sa_flags = 0;
6291         sact.sa_handler = sighdlr;
6292         sigaction(SIGINT, &sact, NULL);
6293         sigaction(SIGQUIT, &sact, NULL);
6294         sigaction(SIGTERM, &sact, NULL);
6295         sigaction(SIGHUP, &sact, NULL);
6296
6297         sact.sa_handler = sighdlr;
6298         sact.sa_flags = SA_NOCLDSTOP;
6299         sigaction(SIGCHLD, &sact, NULL);
6300
6301         astate = XInternAtom(display, "WM_STATE", False);
6302         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
6303         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
6304         takefocus = XInternAtom(display, "WM_TAKE_FOCUS", False);
6305         a_wmname = XInternAtom(display, "WM_NAME", False);
6306         a_utf8_string = XInternAtom(display, "UTF8_STRING", False);
6307         a_string = XInternAtom(display, "STRING", False);
6308         a_swm_iconic = XInternAtom(display, "_SWM_ICONIC", False);
6309
6310         /* look for local and global conf file */
6311         pwd = getpwuid(getuid());
6312         if (pwd == NULL)
6313                 errx(1, "invalid user %d", getuid());
6314
6315         setup_screens();
6316         setup_globals();
6317         setup_keys();
6318         setup_quirks();
6319         setup_spawn();
6320
6321         /* load config */
6322         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
6323         if (stat(conf, &sb) != -1) {
6324                 if (S_ISREG(sb.st_mode))
6325                         cfile = conf;
6326         } else {
6327                 /* try global conf file */
6328                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
6329                 if (!stat(conf, &sb))
6330                         if (S_ISREG(sb.st_mode))
6331                                 cfile = conf;
6332         }
6333         if (cfile)
6334                 conf_load(cfile);
6335
6336         setup_ewmh();
6337         /* set some values to work around bad programs */
6338         workaround();
6339         /* grab existing windows (before we build the bars) */
6340         grab_windows();
6341
6342         if (getenv("SWM_STARTED") == NULL)
6343                 setenv("SWM_STARTED", "YES", 1);
6344
6345         /* setup all bars */
6346         for (i = 0; i < ScreenCount(display); i++)
6347                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
6348                         if (winfocus == NULL)
6349                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
6350                         bar_setup(r);
6351                 }
6352
6353         unfocus_all();
6354
6355         grabkeys();
6356         stack();
6357         if (focus_mode == SWM_FOCUS_DEFAULT)
6358                 drain_enter_notify();
6359
6360         xfd = ConnectionNumber(display);
6361         while (running) {
6362                 while (XPending(display)) {
6363                         XNextEvent(display, &e);
6364                         if (running == 0)
6365                                 goto done;
6366                         if (e.type < LASTEvent) {
6367                                 dumpevent(&e);
6368                                 if (handler[e.type])
6369                                         handler[e.type](&e);
6370                                 else
6371                                         DNPRINTF(SWM_D_EVENT,
6372                                             "win: %lu unknown event: %d\n",
6373                                             e.xany.window, e.type);
6374                         } else {
6375                                 switch (e.type - xrandr_eventbase) {
6376                                 case RRScreenChangeNotify:
6377                                         screenchange(&e);
6378                                         break;
6379                                 default:
6380                                         DNPRINTF(SWM_D_EVENT,
6381                                             "win: %lu unknown xrandr event: "
6382                                             "%d\n", e.xany.window, e.type);
6383                                         break;
6384                                 }
6385                         }
6386                 }
6387
6388                 /* if we are being restarted go focus on first window */
6389                 if (winfocus) {
6390                         rr = winfocus->ws->r;
6391                         if (rr == NULL) {
6392                                 /* not a visible window */
6393                                 winfocus = NULL;
6394                                 continue;
6395                         }
6396                         /* move pointer to first screen if multi screen */
6397                         if (ScreenCount(display) > 1 || outputs > 1)
6398                                 XWarpPointer(display, None, rr->s[0].root,
6399                                     0, 0, 0, 0, rr->g.x,
6400                                     rr->g.y + (bar_enabled ? bar_height : 0));
6401
6402                         a.id = SWM_ARG_ID_FOCUSCUR;
6403                         focus(rr, &a);
6404                         winfocus = NULL;
6405                         continue;
6406                 }
6407
6408                 FD_ZERO(&rd);
6409                 FD_SET(xfd, &rd);
6410                 tv.tv_sec = 1;
6411                 tv.tv_usec = 0;
6412                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
6413                         if (errno != EINTR)
6414                                 DNPRINTF(SWM_D_MISC, "select failed");
6415                 if (restart_wm == 1)
6416                         restart(NULL, NULL);
6417                 if (search_resp == 1)
6418                         search_do_resp();
6419                 if (running == 0)
6420                         goto done;
6421                 if (bar_alarm) {
6422                         bar_alarm = 0;
6423                         bar_update();
6424                 }
6425         }
6426 done:
6427         teardown_ewmh();
6428         bar_extra_stop();
6429         XFreeGC(display, bar_gc);
6430         XCloseDisplay(display);
6431
6432         return (0);
6433 }