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