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