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