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