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