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