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