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