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