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