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