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