JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
307e004f4b7ccfda7f1a262043c538dc2e23000b
[spectrwm.git] / scrotwm.c
1 /* $scrotwm$ */
2 /*
3  * Copyright (c) 2009-2010-2011 Marco Peereboom <marco@peereboom.us>
4  * Copyright (c) 2009-2010-2011 Ryan McBride <mcbride@countersiege.com>
5  * Copyright (c) 2009 Darrin Chandler <dwchandler@stilyagin.com>
6  * Copyright (c) 2009 Pierre-Yves Ritschard <pyr@spootnik.org>
7  * Copyright (c) 2011 Jason L. Wright <jason@thought.net>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21 /*
22  * Much code and ideas taken from dwm under the following license:
23  * MIT/X Consortium License
24  *
25  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
26  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
27  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
28  * 2007 Premysl Hruby <dfenze at gmail dot com>
29  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
30  * 2007 Christof Musik <christof at sendfax dot de>
31  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
32  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
33  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
34  *
35  * Permission is hereby granted, free of charge, to any person obtaining a
36  * copy of this software and associated documentation files (the "Software"),
37  * to deal in the Software without restriction, including without limitation
38  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
39  * and/or sell copies of the Software, and to permit persons to whom the
40  * Software is furnished to do so, subject to the following conditions:
41  *
42  * The above copyright notice and this permission notice shall be included in
43  * all copies or substantial portions of the Software.
44  *
45  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
48  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
50  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
51  * DEALINGS IN THE SOFTWARE.
52  */
53
54 static const char       *cvstag = "$scrotwm$";
55
56 #define SWM_VERSION     "0.9.30"
57
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <locale.h>
64 #include <unistd.h>
65 #include <time.h>
66 #include <signal.h>
67 #include <string.h>
68 #include <util.h>
69 #include <pwd.h>
70 #include <paths.h>
71 #include <ctype.h>
72
73 #include <sys/types.h>
74 #include <sys/time.h>
75 #include <sys/stat.h>
76 #include <sys/wait.h>
77 #include <sys/queue.h>
78 #include <sys/param.h>
79 #include <sys/select.h>
80
81 #include <X11/cursorfont.h>
82 #include <X11/keysym.h>
83 #include <X11/Xatom.h>
84 #include <X11/Xlib.h>
85 #include <X11/Xproto.h>
86 #include <X11/Xutil.h>
87 #include <X11/extensions/Xrandr.h>
88
89 #ifdef __OSX__
90 #include <osx.h>
91 #endif
92
93 #if RANDR_MAJOR < 1
94 #  error XRandR versions less than 1.0 are not supported
95 #endif
96
97 #if RANDR_MAJOR >= 1
98 #if RANDR_MINOR >= 2
99 #define SWM_XRR_HAS_CRTC
100 #endif
101 #endif
102
103 #define SWM_DEBUG
104 /*#define SWM_DEBUG*/
105 #ifdef SWM_DEBUG
106 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while (0)
107 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while (0)
108 #define SWM_D_MISC              0x0001
109 #define SWM_D_EVENT             0x0002
110 #define SWM_D_WS                0x0004
111 #define SWM_D_FOCUS             0x0008
112 #define SWM_D_MOVE              0x0010
113 #define SWM_D_STACK             0x0020
114 #define SWM_D_MOUSE             0x0040
115 #define SWM_D_PROP              0x0080
116 #define SWM_D_CLASS             0x0100
117 #define SWM_D_KEY               0x0200
118 #define SWM_D_QUIRK             0x0400
119 #define SWM_D_SPAWN             0x0800
120 #define SWM_D_EVENTQ            0x1000
121 #define SWM_D_CONF              0x2000
122
123 u_int32_t               swm_debug = 0
124                             | SWM_D_MISC
125                             | SWM_D_EVENT
126                             | SWM_D_WS
127                             | SWM_D_FOCUS
128                             | SWM_D_MOVE
129                             | SWM_D_STACK
130                             | SWM_D_MOUSE
131                             | SWM_D_PROP
132                             | SWM_D_CLASS
133                             | SWM_D_KEY
134                             | SWM_D_QUIRK
135                             | SWM_D_SPAWN
136                             | SWM_D_EVENTQ
137                             | SWM_D_CONF
138                             ;
139 #else
140 #define DPRINTF(x...)
141 #define DNPRINTF(n,x...)
142 #endif
143
144 #define LENGTH(x)               (sizeof x / sizeof x[0])
145 #define MODKEY                  Mod1Mask
146 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
147 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
148 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
149 #define SWM_PROPLEN             (16)
150 #define SWM_FUNCNAME_LEN        (32)
151 #define SWM_KEYS_LEN            (255)
152 #define SWM_QUIRK_LEN           (64)
153 #define X(r)                    (r)->g.x
154 #define Y(r)                    (r)->g.y
155 #define WIDTH(r)                (r)->g.w
156 #define HEIGHT(r)               (r)->g.h
157 #define SWM_MAX_FONT_STEPS      (3)
158 #define WINID(w)                (w ? w->id : 0)
159
160 #define SWM_FOCUS_DEFAULT       (0)
161 #define SWM_FOCUS_SYNERGY       (1)
162 #define SWM_FOCUS_FOLLOW        (2)
163
164 #ifndef SWM_LIB
165 #define SWM_LIB                 "/usr/local/lib/libswmhack.so"
166 #endif
167
168 char                    **start_argv;
169 Atom                    astate;
170 Atom                    aprot;
171 Atom                    adelete;
172 Atom                    takefocus;
173 Atom                    a_wmname;
174 Atom                    a_utf8_string;
175 Atom                    a_string;
176 Atom                    a_swm_iconic;
177 volatile sig_atomic_t   running = 1;
178 volatile sig_atomic_t   restart_wm = 0;
179 int                     outputs = 0;
180 int                     last_focus_event = FocusOut;
181 int                     (*xerrorxlib)(Display *, XErrorEvent *);
182 int                     other_wm;
183 int                     ss_enabled = 0;
184 int                     xrandr_support;
185 int                     xrandr_eventbase;
186 unsigned int            numlockmask = 0;
187 Display                 *display;
188
189 int                     cycle_empty = 0;
190 int                     cycle_visible = 0;
191 int                     term_width = 0;
192 int                     font_adjusted = 0;
193 unsigned int            mod_key = MODKEY;
194
195 /* dmenu search */
196 struct swm_region       *search_r;
197 int                     select_list_pipe[2];
198 int                     select_resp_pipe[2];
199 pid_t                   searchpid;
200 volatile sig_atomic_t   search_resp;
201
202 /* dialog windows */
203 double                  dialog_ratio = .6;
204 /* status bar */
205 #define SWM_BAR_MAX     (256)
206 char                    *bar_argv[] = { NULL, NULL };
207 int                     bar_pipe[2];
208 char                    bar_ext[SWM_BAR_MAX];
209 char                    bar_vertext[SWM_BAR_MAX];
210 int                     bar_version = 0;
211 sig_atomic_t            bar_alarm = 0;
212 int                     bar_delay = 30;
213 int                     bar_enabled = 1;
214 int                     bar_border_width = 1;
215 int                     bar_at_bottom = 0;
216 int                     bar_extra = 1;
217 int                     bar_extra_running = 0;
218 int                     bar_verbose = 1;
219 int                     bar_height = 0;
220 int                     stack_enabled = 1;
221 int                     clock_enabled = 1;
222 char                    *clock_format = NULL;
223 int                     title_name_enabled = 0;
224 int                     title_class_enabled = 0;
225 int                     window_name_enabled = 0;
226 int                     focus_mode = SWM_FOCUS_DEFAULT;
227 int                     disable_border = 0;
228 int                     border_width = 1;
229 pid_t                   bar_pid;
230 GC                      bar_gc;
231 XGCValues               bar_gcv;
232 int                     bar_fidx = 0;
233 XFontStruct             *bar_fs;
234 char                    *bar_fonts[] = { NULL, NULL, NULL, NULL };/* XXX Make fully dynamic */
235 char                    *spawn_term[] = { NULL, NULL };         /* XXX Make fully dynamic */
236
237 #define SWM_MENU_FN     (2)
238 #define SWM_MENU_NB     (4)
239 #define SWM_MENU_NF     (6)
240 #define SWM_MENU_SB     (8)
241 #define SWM_MENU_SF     (10)
242
243 /* layout manager data */
244 struct swm_geometry {
245         int                     x;
246         int                     y;
247         int                     w;
248         int                     h;
249 };
250
251 struct swm_screen;
252 struct workspace;
253
254 /* virtual "screens" */
255 struct swm_region {
256         TAILQ_ENTRY(swm_region) entry;
257         struct swm_geometry     g;
258         struct workspace        *ws;    /* current workspace on this region */
259         struct workspace        *ws_prior; /* prior workspace on this region */
260         struct swm_screen       *s;     /* screen idx */
261         Window                  bar_window;
262 };
263 TAILQ_HEAD(swm_region_list, swm_region);
264
265 struct ws_win {
266         TAILQ_ENTRY(ws_win)     entry;
267         Window                  id;
268         Window                  transient;
269         struct ws_win           *child_trans;   /* transient child window */
270         struct swm_geometry     g;              /* current geometry */
271         struct swm_geometry     g_float;        /* geometry when floating */
272         struct swm_geometry     rg_float;       /* region geom when floating */
273         int                     g_floatvalid;   /* flag: geometry in g_float is valid */
274         int                     floatmaxed;     /* flag: floater was maxed in max_stack */
275         int                     floating;
276         int                     manual;
277         int                     iconic;
278         unsigned int            ewmh_flags;
279         int                     font_size_boundary[SWM_MAX_FONT_STEPS];
280         int                     font_steps;
281         int                     last_inc;
282         int                     can_delete;
283         int                     take_focus;
284         int                     java;
285         unsigned long           quirks;
286         struct workspace        *ws;    /* always valid */
287         struct swm_screen       *s;     /* always valid, never changes */
288         XWindowAttributes       wa;
289         XSizeHints              sh;
290         XClassHint              ch;
291 };
292 TAILQ_HEAD(ws_win_list, ws_win);
293
294 /* layout handlers */
295 void    stack(void);
296 void    vertical_config(struct workspace *, int);
297 void    vertical_stack(struct workspace *, struct swm_geometry *);
298 void    horizontal_config(struct workspace *, int);
299 void    horizontal_stack(struct workspace *, struct swm_geometry *);
300 void    max_stack(struct workspace *, struct swm_geometry *);
301
302 struct ws_win *find_window(Window);
303
304 void    grabbuttons(struct ws_win *, int);
305 void    new_region(struct swm_screen *, int, int, int, int);
306 void    unmanage_window(struct ws_win *);
307 long    getstate(Window);
308
309 struct layout {
310         void            (*l_stack)(struct workspace *, struct swm_geometry *);
311         void            (*l_config)(struct workspace *, int);
312         u_int32_t       flags;
313 #define SWM_L_FOCUSPREV         (1<<0)
314 #define SWM_L_MAPONFOCUS        (1<<1)
315         char            *name;
316 } layouts[] =  {
317         /* stack,               configure */
318         { vertical_stack,       vertical_config,        0,      "[|]" },
319         { horizontal_stack,     horizontal_config,      0,      "[-]" },
320         { max_stack,            NULL,
321           SWM_L_MAPONFOCUS | SWM_L_FOCUSPREV,                   "[ ]"},
322         { NULL,                 NULL,                   0,      NULL },
323 };
324
325 /* position of max_stack mode in the layouts array */
326 #define SWM_MAX_STACK           2
327
328 #define SWM_H_SLICE             (32)
329 #define SWM_V_SLICE             (32)
330
331 /* define work spaces */
332 struct workspace {
333         int                     idx;            /* workspace index */
334         struct layout           *cur_layout;    /* current layout handlers */
335         struct ws_win           *focus;         /* may be NULL */
336         struct ws_win           *focus_prev;    /* may be NULL */
337         struct swm_region       *r;             /* may be NULL */
338         struct swm_region       *old_r;         /* may be NULL */
339         struct ws_win_list      winlist;        /* list of windows in ws */
340         struct ws_win_list      unmanagedlist;  /* list of dead windows in ws */
341
342         /* stacker state */
343         struct {
344                                 int horizontal_msize;
345                                 int horizontal_mwin;
346                                 int horizontal_stacks;
347                                 int vertical_msize;
348                                 int vertical_mwin;
349                                 int vertical_stacks;
350         } l_state;
351 };
352
353 enum    { SWM_S_COLOR_BAR, SWM_S_COLOR_BAR_BORDER, SWM_S_COLOR_BAR_FONT,
354           SWM_S_COLOR_FOCUS, SWM_S_COLOR_UNFOCUS, SWM_S_COLOR_MAX };
355
356 /* physical screen mapping */
357 #define SWM_WS_MAX              (10)
358 struct swm_screen {
359         int                     idx;    /* screen index */
360         struct swm_region_list  rl;     /* list of regions on this screen */
361         struct swm_region_list  orl;    /* list of old regions */
362         Window                  root;
363         struct workspace        ws[SWM_WS_MAX];
364
365         /* colors */
366         struct {
367                 unsigned long   color;
368                 char            *name;
369         } c[SWM_S_COLOR_MAX];
370 };
371 struct swm_screen       *screens;
372 int                     num_screens;
373
374 /* args to functions */
375 union arg {
376         int                     id;
377 #define SWM_ARG_ID_FOCUSNEXT    (0)
378 #define SWM_ARG_ID_FOCUSPREV    (1)
379 #define SWM_ARG_ID_FOCUSMAIN    (2)
380 #define SWM_ARG_ID_FOCUSCUR     (4)
381 #define SWM_ARG_ID_SWAPNEXT     (10)
382 #define SWM_ARG_ID_SWAPPREV     (11)
383 #define SWM_ARG_ID_SWAPMAIN     (12)
384 #define SWM_ARG_ID_MOVELAST     (13)
385 #define SWM_ARG_ID_MASTERSHRINK (20)
386 #define SWM_ARG_ID_MASTERGROW   (21)
387 #define SWM_ARG_ID_MASTERADD    (22)
388 #define SWM_ARG_ID_MASTERDEL    (23)
389 #define SWM_ARG_ID_STACKRESET   (30)
390 #define SWM_ARG_ID_STACKINIT    (31)
391 #define SWM_ARG_ID_CYCLEWS_UP   (40)
392 #define SWM_ARG_ID_CYCLEWS_DOWN (41)
393 #define SWM_ARG_ID_CYCLESC_UP   (42)
394 #define SWM_ARG_ID_CYCLESC_DOWN (43)
395 #define SWM_ARG_ID_STACKINC     (50)
396 #define SWM_ARG_ID_STACKDEC     (51)
397 #define SWM_ARG_ID_SS_ALL       (60)
398 #define SWM_ARG_ID_SS_WINDOW    (61)
399 #define SWM_ARG_ID_DONTCENTER   (70)
400 #define SWM_ARG_ID_CENTER       (71)
401 #define SWM_ARG_ID_KILLWINDOW   (80)
402 #define SWM_ARG_ID_DELETEWINDOW (81)
403         char                    **argv;
404 };
405
406 void    focus(struct swm_region *, union arg *);
407 void    focus_magic(struct ws_win *);
408
409 /* quirks */
410 struct quirk {
411         char                    *class;
412         char                    *name;
413         unsigned long           quirk;
414 #define SWM_Q_FLOAT             (1<<0)  /* float this window */
415 #define SWM_Q_TRANSSZ           (1<<1)  /* transiend window size too small */
416 #define SWM_Q_ANYWHERE          (1<<2)  /* don't position this window */
417 #define SWM_Q_XTERM_FONTADJ     (1<<3)  /* adjust xterm fonts when resizing */
418 #define SWM_Q_FULLSCREEN        (1<<4)  /* remove border */
419 };
420 int                             quirks_size = 0, quirks_length = 0;
421 struct quirk                    *quirks = NULL;
422
423 /*
424  * Supported EWMH hints should be added to
425  * both the enum and the ewmh array
426  */
427 enum { _NET_ACTIVE_WINDOW, _NET_MOVERESIZE_WINDOW, _NET_CLOSE_WINDOW,
428     _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DOCK,
429     _NET_WM_WINDOW_TYPE_TOOLBAR, _NET_WM_WINDOW_TYPE_UTILITY,
430     _NET_WM_WINDOW_TYPE_SPLASH, _NET_WM_WINDOW_TYPE_DIALOG,
431     _NET_WM_WINDOW_TYPE_NORMAL, _NET_WM_STATE,
432     _NET_WM_STATE_MAXIMIZED_HORZ, _NET_WM_STATE_MAXIMIZED_VERT,
433     _NET_WM_STATE_SKIP_TASKBAR, _NET_WM_STATE_SKIP_PAGER,
434     _NET_WM_STATE_HIDDEN, _NET_WM_STATE_ABOVE, _SWM_WM_STATE_MANUAL,
435     _NET_WM_STATE_FULLSCREEN, _NET_WM_ALLOWED_ACTIONS, _NET_WM_ACTION_MOVE,
436     _NET_WM_ACTION_RESIZE, _NET_WM_ACTION_FULLSCREEN, _NET_WM_ACTION_CLOSE,
437     SWM_EWMH_HINT_MAX };
438
439 struct ewmh_hint {
440         char    *name;
441         Atom     atom;
442 } ewmh[SWM_EWMH_HINT_MAX] =     {
443     /* must be in same order as in the enum */
444     {"_NET_ACTIVE_WINDOW", None},
445     {"_NET_MOVERESIZE_WINDOW", None},
446     {"_NET_CLOSE_WINDOW", None},
447     {"_NET_WM_WINDOW_TYPE", None},
448     {"_NET_WM_WINDOW_TYPE_DOCK", None},
449     {"_NET_WM_WINDOW_TYPE_TOOLBAR", None},
450     {"_NET_WM_WINDOW_TYPE_UTILITY", None},
451     {"_NET_WM_WINDOW_TYPE_SPLASH", None},
452     {"_NET_WM_WINDOW_TYPE_DIALOG", None},
453     {"_NET_WM_WINDOW_TYPE_NORMAL", None},
454     {"_NET_WM_STATE", None},
455     {"_NET_WM_STATE_MAXIMIZED_HORZ", None},
456     {"_NET_WM_STATE_MAXIMIZED_VERT", None},
457     {"_NET_WM_STATE_SKIP_TASKBAR", None},
458     {"_NET_WM_STATE_SKIP_PAGER", None},
459     {"_NET_WM_STATE_HIDDEN", None},
460     {"_NET_WM_STATE_ABOVE", None},
461     {"_SWM_WM_STATE_MANUAL", None},
462     {"_NET_WM_STATE_FULLSCREEN", None},
463     {"_NET_WM_ALLOWED_ACTIONS", None},
464     {"_NET_WM_ACTION_MOVE", None},
465     {"_NET_WM_ACTION_RESIZE", None},
466     {"_NET_WM_ACTION_FULLSCREEN", None},
467     {"_NET_WM_ACTION_CLOSE", None},
468 };
469
470 void    store_float_geom(struct ws_win *win, struct swm_region *r);
471 int     floating_toggle_win(struct ws_win *win);
472 void    spawn_select(struct swm_region *, union arg *, char *, int *);
473
474 int
475 get_property(Window id, Atom atom, long count, Atom type,
476     unsigned long *n, unsigned char **data)
477 {
478         int                     format, status;
479         unsigned long           tmp, extra;
480         unsigned long           *nitems;
481         Atom                    real;
482
483         nitems = n != NULL ? n : &tmp;
484         status = XGetWindowProperty(display, id, atom, 0L, count, False, type,
485             &real, &format, nitems, &extra, data);
486
487         if (status != Success)
488                 return False;
489         if (real != type)
490                 return False;
491
492         return True;
493 }
494
495 void
496 update_iconic(struct ws_win *win, int newv)
497 {
498         int32_t v = newv;
499         Atom iprop;
500
501         win->iconic = newv;
502
503         iprop = XInternAtom(display, "_SWM_ICONIC", False);
504         if (!iprop)
505                 return;
506         if (newv)
507                 XChangeProperty(display, win->id, iprop, XA_INTEGER, 32,
508                     PropModeReplace, (unsigned char *)&v, 1);
509         else
510                 XDeleteProperty(display, win->id, iprop);
511 }
512
513 int
514 get_iconic(struct ws_win *win)
515 {
516         int32_t v = 0;
517         int retfmt, status;
518         Atom iprop, rettype;
519         unsigned long nitems, extra;
520         unsigned char *prop = NULL;
521
522         iprop = XInternAtom(display, "_SWM_ICONIC", False);
523         if (!iprop)
524                 goto out;
525         status = XGetWindowProperty(display, win->id, iprop, 0L, 1L,
526             False, XA_INTEGER, &rettype, &retfmt, &nitems, &extra, &prop);
527         if (status != Success)
528                 goto out;
529         if (rettype != XA_INTEGER || retfmt != 32)
530                 goto out;
531         if (nitems != 1)
532                 goto out;
533         v = *((int32_t *)prop);
534
535 out:
536         if (prop != NULL)
537                 XFree(prop);
538         return (v);
539 }
540
541 void
542 setup_ewmh(void)
543 {
544         int                     i,j;
545         Atom                    sup_list;
546
547         sup_list = XInternAtom(display, "_NET_SUPPORTED", False);
548
549         for (i = 0; i < LENGTH(ewmh); i++)
550                 ewmh[i].atom = XInternAtom(display, ewmh[i].name, False);
551
552         for (i = 0; i < ScreenCount(display); i++) {
553                 /* Support check window will be created by workaround(). */
554
555                 /* Report supported atoms */
556                 XDeleteProperty(display, screens[i].root, sup_list);
557                 for (j = 0; j < LENGTH(ewmh); j++)
558                         XChangeProperty(display, screens[i].root, sup_list, XA_ATOM, 32,
559                             PropModeAppend, (unsigned char *)&ewmh[j].atom,1);
560         }
561 }
562
563 void
564 teardown_ewmh(void)
565 {
566         int                     i, success;
567         unsigned char           *data = NULL;
568         unsigned long           n;
569         Atom                    sup_check, sup_list;
570         Window                  id;
571
572         sup_check = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
573         sup_list = XInternAtom(display, "_NET_SUPPORTED", False);
574
575         for (i = 0; i < ScreenCount(display); i++) {
576                 /* Get the support check window and destroy it */
577                 success = get_property(screens[i].root, sup_check, 1, XA_WINDOW,
578                     &n, &data);
579
580                 if (success) {
581                         id = data[0];
582                         XDestroyWindow(display, id);
583                         XDeleteProperty(display, screens[i].root, sup_check);
584                         XDeleteProperty(display, screens[i].root, sup_list);
585                 }
586
587                 XFree(data);
588         }
589 }
590
591 void
592 ewmh_autoquirk(struct ws_win *win)
593 {
594         int                     success, i;
595         unsigned long           *data = NULL;
596         unsigned long           n;
597         Atom                    type;
598
599         success = get_property(win->id, ewmh[_NET_WM_WINDOW_TYPE].atom, (~0L),
600             XA_ATOM, &n, (unsigned char **)&data);
601
602         if (!success) {
603                 XFree(data);
604                 return;
605         }
606
607         for (i = 0; i < n; i++) {
608                 type = data[i];
609                 if (type == ewmh[_NET_WM_WINDOW_TYPE_NORMAL].atom)
610                         break;
611                 if (type == ewmh[_NET_WM_WINDOW_TYPE_DOCK].atom ||
612                     type == ewmh[_NET_WM_WINDOW_TYPE_TOOLBAR].atom ||
613                     type == ewmh[_NET_WM_WINDOW_TYPE_UTILITY].atom) {
614                         win->floating = 1;
615                         win->quirks = SWM_Q_FLOAT | SWM_Q_ANYWHERE;
616                         break;
617                 }
618                 if (type == ewmh[_NET_WM_WINDOW_TYPE_SPLASH].atom ||
619                     type == ewmh[_NET_WM_WINDOW_TYPE_DIALOG].atom) {
620                         win->floating = 1;
621                         win->quirks = SWM_Q_FLOAT;
622                         break;
623                 }
624         }
625
626         XFree(data);
627 }
628
629 #define SWM_EWMH_ACTION_COUNT_MAX       (6)
630 #define EWMH_F_FULLSCREEN               (1<<0)
631 #define EWMH_F_ABOVE                    (1<<1)
632 #define EWMH_F_HIDDEN                   (1<<2)
633 #define EWMH_F_SKIP_PAGER               (1<<3)
634 #define EWMH_F_SKIP_TASKBAR             (1<<4)
635 #define SWM_F_MANUAL                    (1<<5)
636
637 int
638 ewmh_set_win_fullscreen(struct ws_win *win, int fs)
639 {
640         struct swm_geometry     rg;
641
642         if (!win->ws->r)
643                 return 0;
644
645         if (!win->floating)
646                 return 0;
647
648         DNPRINTF(SWM_D_MISC, "ewmh_set_win_fullscreen: win 0x%lx fs: %d\n",
649             win->id, fs);
650
651         rg = win->ws->r->g;
652
653         if (fs) {
654                 store_float_geom(win, win->ws->r);
655
656                 win->g.x = rg.x;
657                 win->g.y = rg.y;
658                 win->g.w = rg.w;
659                 win->g.h = rg.h;
660         } else {
661                 if (win->g_floatvalid) {
662                         /* refloat at last floating relative position */
663                         win->g.x = win->g_float.x - win->rg_float.x + rg.x;
664                         win->g.y = win->g_float.y - win->rg_float.y + rg.y;
665                         win->g.w = win->g_float.w;
666                         win->g.h = win->g_float.h;
667                 }
668         }
669
670         return 1;
671 }
672
673 void
674 ewmh_update_actions(struct ws_win *win)
675 {
676         Atom                    actions[SWM_EWMH_ACTION_COUNT_MAX];
677         int                     n = 0;
678
679         if (win == NULL)
680                 return;
681
682         actions[n++] = ewmh[_NET_WM_ACTION_CLOSE].atom;
683
684         if (win->floating) {
685                 actions[n++] = ewmh[_NET_WM_ACTION_MOVE].atom;
686                 actions[n++] = ewmh[_NET_WM_ACTION_RESIZE].atom;
687         }
688
689         XChangeProperty(display, win->id, ewmh[_NET_WM_ALLOWED_ACTIONS].atom,
690             XA_ATOM, 32, PropModeReplace, (unsigned char *)actions, n);
691 }
692
693 #define _NET_WM_STATE_REMOVE    0    /* remove/unset property */
694 #define _NET_WM_STATE_ADD       1    /* add/set property */
695 #define _NET_WM_STATE_TOGGLE    2    /* toggle property */
696
697 void
698 ewmh_update_win_state(struct ws_win *win, long state, long action)
699 {
700         unsigned int            mask = 0;
701         unsigned int            changed = 0;
702         unsigned int            orig_flags;
703
704         if (win == NULL)
705                 return;
706
707         if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
708                 mask = EWMH_F_FULLSCREEN;
709         if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
710                 mask = EWMH_F_ABOVE;
711         if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
712                 mask = SWM_F_MANUAL;
713         if (state == ewmh[_NET_WM_STATE_SKIP_PAGER].atom)
714                 mask = EWMH_F_SKIP_PAGER;
715         if (state == ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom)
716                 mask = EWMH_F_SKIP_TASKBAR;
717
718
719         orig_flags = win->ewmh_flags;
720
721         switch (action) {
722         case _NET_WM_STATE_REMOVE:
723                 win->ewmh_flags &= ~mask;
724                 break;
725         case _NET_WM_STATE_ADD:
726                 win->ewmh_flags |= mask;
727                 break;
728         case _NET_WM_STATE_TOGGLE:
729                 win->ewmh_flags ^= mask;
730                 break;
731         }
732
733         changed = (win->ewmh_flags & mask) ^ (orig_flags & mask) ? 1 : 0;
734
735         if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
736                 if (changed)
737                         if (!floating_toggle_win(win))
738                                 win->ewmh_flags = orig_flags; /* revert */
739         if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
740                 if (changed)
741                         win->manual = (win->ewmh_flags & SWM_F_MANUAL) != 0;
742         if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
743                 if (changed)
744                         if (!ewmh_set_win_fullscreen(win, win->ewmh_flags & EWMH_F_FULLSCREEN))
745                                 win->ewmh_flags = orig_flags; /* revert */
746
747         XDeleteProperty(display, win->id, ewmh[_NET_WM_STATE].atom);
748
749         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
750                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
751                     XA_ATOM, 32, PropModeAppend,
752                     (unsigned char *)&ewmh[_NET_WM_STATE_FULLSCREEN].atom, 1);
753         if (win->ewmh_flags & EWMH_F_SKIP_PAGER)
754                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
755                     XA_ATOM, 32, PropModeAppend,
756                     (unsigned char *)&ewmh[_NET_WM_STATE_SKIP_PAGER].atom, 1);
757         if (win->ewmh_flags & EWMH_F_SKIP_TASKBAR)
758                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
759                     XA_ATOM, 32, PropModeAppend,
760                     (unsigned char *)&ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom, 1);
761         if (win->ewmh_flags & EWMH_F_ABOVE)
762                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
763                     XA_ATOM, 32, PropModeAppend,
764                     (unsigned char *)&ewmh[_NET_WM_STATE_ABOVE].atom, 1);
765         if (win->ewmh_flags & SWM_F_MANUAL)
766                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
767                     XA_ATOM, 32, PropModeAppend,
768                     (unsigned char *)&ewmh[_SWM_WM_STATE_MANUAL].atom, 1);
769 }
770
771 void
772 ewmh_get_win_state(struct ws_win *win)
773 {
774         int                     success, i;
775         unsigned long           n;
776         Atom                    *states;
777
778         if (win == NULL)
779                 return;
780
781         win->ewmh_flags = 0;
782         if (win->floating)
783                 win->ewmh_flags |= EWMH_F_ABOVE;
784         if (win->manual)
785                 win->ewmh_flags |= SWM_F_MANUAL;
786
787         success = get_property(win->id, ewmh[_NET_WM_STATE].atom, (~0L), XA_ATOM,
788             &n, (unsigned char **)&states);
789
790         if (!success)
791                 return;
792
793         for (i = 0; i < n; i++)
794                 ewmh_update_win_state(win, states[i], _NET_WM_STATE_ADD);
795
796         XFree(states);
797 }
798
799 /* events */
800 #ifdef SWM_DEBUG
801 void
802 dumpevent(XEvent *e)
803 {
804         char                    *name = NULL;
805
806         switch (e->type) {
807         case KeyPress:
808                 name = "KeyPress";
809                 break;
810         case KeyRelease:
811                 name = "KeyRelease";
812                 break;
813         case ButtonPress:
814                 name = "ButtonPress";
815                 break;
816         case ButtonRelease:
817                 name = "ButtonRelease";
818                 break;
819         case MotionNotify:
820                 name = "MotionNotify";
821                 break;
822         case EnterNotify:
823                 name = "EnterNotify";
824                 break;
825         case LeaveNotify:
826                 name = "LeaveNotify";
827                 break;
828         case FocusIn:
829                 name = "FocusIn";
830                 break;
831         case FocusOut:
832                 name = "FocusOut";
833                 break;
834         case KeymapNotify:
835                 name = "KeymapNotify";
836                 break;
837         case Expose:
838                 name = "Expose";
839                 break;
840         case GraphicsExpose:
841                 name = "GraphicsExpose";
842                 break;
843         case NoExpose:
844                 name = "NoExpose";
845                 break;
846         case VisibilityNotify:
847                 name = "VisibilityNotify";
848                 break;
849         case CreateNotify:
850                 name = "CreateNotify";
851                 break;
852         case DestroyNotify:
853                 name = "DestroyNotify";
854                 break;
855         case UnmapNotify:
856                 name = "UnmapNotify";
857                 break;
858         case MapNotify:
859                 name = "MapNotify";
860                 break;
861         case MapRequest:
862                 name = "MapRequest";
863                 break;
864         case ReparentNotify:
865                 name = "ReparentNotify";
866                 break;
867         case ConfigureNotify:
868                 name = "ConfigureNotify";
869                 break;
870         case ConfigureRequest:
871                 name = "ConfigureRequest";
872                 break;
873         case GravityNotify:
874                 name = "GravityNotify";
875                 break;
876         case ResizeRequest:
877                 name = "ResizeRequest";
878                 break;
879         case CirculateNotify:
880                 name = "CirculateNotify";
881                 break;
882         case CirculateRequest:
883                 name = "CirculateRequest";
884                 break;
885         case PropertyNotify:
886                 name = "PropertyNotify";
887                 break;
888         case SelectionClear:
889                 name = "SelectionClear";
890                 break;
891         case SelectionRequest:
892                 name = "SelectionRequest";
893                 break;
894         case SelectionNotify:
895                 name = "SelectionNotify";
896                 break;
897         case ColormapNotify:
898                 name = "ColormapNotify";
899                 break;
900         case ClientMessage:
901                 name = "ClientMessage";
902                 break;
903         case MappingNotify:
904                 name = "MappingNotify";
905                 break;
906         }
907
908         if (name)
909                 DNPRINTF(SWM_D_EVENTQ ,"window: %lu event: %s (%d), %d "
910                     "remaining\n",
911                     e->xany.window, name, e->type, QLength(display));
912         else
913                 DNPRINTF(SWM_D_EVENTQ, "window: %lu unknown event %d, %d "
914                     "remaining\n",
915                     e->xany.window, e->type, QLength(display));
916 }
917
918 void
919 dumpwins(struct swm_region *r, union arg *args)
920 {
921         struct ws_win           *win;
922         unsigned int            state;
923         XWindowAttributes       wa;
924
925         if (r->ws == NULL) {
926                 fprintf(stderr, "invalid workspace\n");
927                 return;
928         }
929
930         fprintf(stderr, "=== managed window list ws %02d ===\n", r->ws->idx);
931
932         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
933                 state = getstate(win->id);
934                 if (!XGetWindowAttributes(display, win->id, &wa))
935                         fprintf(stderr, "window: %lu failed "
936                             "XGetWindowAttributes\n", win->id);
937                 fprintf(stderr, "window: %lu map_state: %d state: %d "
938                     "transient: %lu\n",
939                     win->id, wa.map_state, state, win->transient);
940         }
941
942         fprintf(stderr, "===== unmanaged window list =====\n");
943         TAILQ_FOREACH(win, &r->ws->unmanagedlist, entry) {
944                 state = getstate(win->id);
945                 if (!XGetWindowAttributes(display, win->id, &wa))
946                         fprintf(stderr, "window: %lu failed "
947                             "XGetWindowAttributes\n", win->id);
948                 fprintf(stderr, "window: %lu map_state: %d state: %d "
949                     "transient: %lu\n",
950                     win->id, wa.map_state, state, win->transient);
951         }
952
953         fprintf(stderr, "=================================\n");
954 }
955 #else
956 #define dumpevent(e)
957 void
958 dumpwins(struct swm_region *r, union arg *args)
959 {
960 }
961 #endif /* SWM_DEBUG */
962
963 void                    expose(XEvent *);
964 void                    keypress(XEvent *);
965 void                    buttonpress(XEvent *);
966 void                    configurerequest(XEvent *);
967 void                    configurenotify(XEvent *);
968 void                    destroynotify(XEvent *);
969 void                    enternotify(XEvent *);
970 void                    focusevent(XEvent *);
971 void                    mapnotify(XEvent *);
972 void                    mappingnotify(XEvent *);
973 void                    maprequest(XEvent *);
974 void                    propertynotify(XEvent *);
975 void                    unmapnotify(XEvent *);
976 void                    visibilitynotify(XEvent *);
977 void                    clientmessage(XEvent *);
978
979 void                    (*handler[LASTEvent])(XEvent *) = {
980                                 [Expose] = expose,
981                                 [KeyPress] = keypress,
982                                 [ButtonPress] = buttonpress,
983                                 [ConfigureRequest] = configurerequest,
984                                 [ConfigureNotify] = configurenotify,
985                                 [DestroyNotify] = destroynotify,
986                                 [EnterNotify] = enternotify,
987                                 [FocusIn] = focusevent,
988                                 [FocusOut] = focusevent,
989                                 [MapNotify] = mapnotify,
990                                 [MappingNotify] = mappingnotify,
991                                 [MapRequest] = maprequest,
992                                 [PropertyNotify] = propertynotify,
993                                 [UnmapNotify] = unmapnotify,
994                                 [VisibilityNotify] = visibilitynotify,
995                                 [ClientMessage] = clientmessage,
996 };
997
998 void
999 sighdlr(int sig)
1000 {
1001         int                     saved_errno, status;
1002         pid_t                   pid;
1003
1004         saved_errno = errno;
1005
1006         switch (sig) {
1007         case SIGCHLD:
1008                 while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
1009                         if (pid == -1) {
1010                                 if (errno == EINTR)
1011                                         continue;
1012 #ifdef SWM_DEBUG
1013                                 if (errno != ECHILD)
1014                                         warn("sighdlr: waitpid");
1015 #endif /* SWM_DEBUG */
1016                                 break;
1017                         }
1018                         if (pid == searchpid)
1019                                 search_resp = 1;
1020
1021 #ifdef SWM_DEBUG
1022                         if (WIFEXITED(status)) {
1023                                 if (WEXITSTATUS(status) != 0)
1024                                         warnx("sighdlr: child exit status: %d",
1025                                             WEXITSTATUS(status));
1026                         } else
1027                                 warnx("sighdlr: child is terminated "
1028                                     "abnormally");
1029 #endif /* SWM_DEBUG */
1030                 }
1031                 break;
1032
1033         case SIGHUP:
1034                 restart_wm = 1;
1035                 break;
1036         case SIGINT:
1037         case SIGTERM:
1038         case SIGQUIT:
1039                 running = 0;
1040                 break;
1041         }
1042
1043         errno = saved_errno;
1044 }
1045
1046 unsigned long
1047 name_to_color(char *colorname)
1048 {
1049         Colormap                cmap;
1050         Status                  status;
1051         XColor                  screen_def, exact_def;
1052         unsigned long           result = 0;
1053         char                    cname[32] = "#";
1054
1055         cmap = DefaultColormap(display, screens[0].idx);
1056         status = XAllocNamedColor(display, cmap, colorname,
1057             &screen_def, &exact_def);
1058         if (!status) {
1059                 strlcat(cname, colorname + 2, sizeof cname - 1);
1060                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
1061                     &exact_def);
1062         }
1063         if (status)
1064                 result = screen_def.pixel;
1065         else
1066                 fprintf(stderr, "color '%s' not found.\n", colorname);
1067
1068         return (result);
1069 }
1070
1071 void
1072 setscreencolor(char *val, int i, int c)
1073 {
1074         if (i > 0 && i <= ScreenCount(display)) {
1075                 screens[i - 1].c[c].color = name_to_color(val);
1076                 free(screens[i - 1].c[c].name);
1077                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
1078                         errx(1, "strdup");
1079         } else if (i == -1) {
1080                 for (i = 0; i < ScreenCount(display); i++) {
1081                         screens[i].c[c].color = name_to_color(val);
1082                         free(screens[i].c[c].name);
1083                         if ((screens[i].c[c].name = strdup(val)) == NULL)
1084                                 errx(1, "strdup");
1085                 }
1086         } else
1087                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
1088                     i, ScreenCount(display));
1089 }
1090
1091 void
1092 custom_region(char *val)
1093 {
1094         unsigned int                    sidx, x, y, w, h;
1095
1096         if (sscanf(val, "screen[%u]:%ux%u+%u+%u", &sidx, &w, &h, &x, &y) != 5)
1097                 errx(1, "invalid custom region, "
1098                     "should be 'screen[<n>]:<n>x<n>+<n>+<n>\n");
1099         if (sidx < 1 || sidx > ScreenCount(display))
1100                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
1101                     sidx, ScreenCount(display));
1102         sidx--;
1103
1104         if (w < 1 || h < 1)
1105                 errx(1, "region %ux%u+%u+%u too small\n", w, h, x, y);
1106
1107         if (x  < 0 || x > DisplayWidth(display, sidx) ||
1108             y < 0 || y > DisplayHeight(display, sidx) ||
1109             w + x > DisplayWidth(display, sidx) ||
1110             h + y > DisplayHeight(display, sidx)) {
1111                 fprintf(stderr, "ignoring region %ux%u+%u+%u - not within screen boundaries "
1112                     "(%ux%u)\n", w, h, x, y,
1113                     DisplayWidth(display, sidx), DisplayHeight(display, sidx));
1114                 return;
1115         }
1116
1117         new_region(&screens[sidx], x, y, w, h);
1118 }
1119
1120 void
1121 socket_setnonblock(int fd)
1122 {
1123         int                     flags;
1124
1125         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
1126                 err(1, "fcntl F_GETFL");
1127         flags |= O_NONBLOCK;
1128         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
1129                 err(1, "fcntl F_SETFL");
1130 }
1131
1132 void
1133 bar_print(struct swm_region *r, char *s)
1134 {
1135         XClearWindow(display, r->bar_window);
1136         XSetForeground(display, bar_gc, r->s->c[SWM_S_COLOR_BAR_FONT].color);
1137         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent, s,
1138             strlen(s));
1139 }
1140
1141 void
1142 bar_extra_stop(void)
1143 {
1144         if (bar_pipe[0]) {
1145                 close(bar_pipe[0]);
1146                 bzero(bar_pipe, sizeof bar_pipe);
1147         }
1148         if (bar_pid) {
1149                 kill(bar_pid, SIGTERM);
1150                 bar_pid = 0;
1151         }
1152         strlcpy(bar_ext, "", sizeof bar_ext);
1153         bar_extra = 0;
1154 }
1155
1156 void
1157 bar_class_name(char *s, ssize_t sz, struct ws_win *cur_focus)
1158 {
1159         int                     do_class, do_name;
1160         Status                  status;
1161         XClassHint              *xch = NULL;
1162
1163         if ((title_name_enabled == 1 || title_class_enabled == 1) &&
1164             cur_focus != NULL) {
1165                 if ((xch = XAllocClassHint()) == NULL)
1166                         goto out;
1167                 status = XGetClassHint(display, cur_focus->id, xch);
1168                 if (status == BadWindow || status == BadAlloc)
1169                         goto out;
1170                 do_class = (title_class_enabled && xch->res_class != NULL);
1171                 do_name = (title_name_enabled && xch->res_name != NULL);
1172                 if (do_class)
1173                         strlcat(s, xch->res_class, sz);
1174                 if (do_class && do_name)
1175                         strlcat(s, ":", sz);
1176                 if (do_name)
1177                         strlcat(s, xch->res_name, sz);
1178                 strlcat(s, "    ", sz);
1179         }
1180 out:
1181         if (xch)
1182                 XFree(xch);
1183 }
1184
1185 void
1186 bar_window_name(char *s, ssize_t sz, struct ws_win *cur_focus)
1187 {
1188         char                    *title;
1189
1190         if (window_name_enabled && cur_focus != NULL) {
1191                 XFetchName(display, cur_focus->id, &title);
1192                 if (title) {
1193                         if (cur_focus->floating)
1194                                 strlcat(s, "(f) ", sz);
1195                         strlcat(s, title, sz);
1196                         strlcat(s, " ", sz);
1197                         XFree(title);
1198                 }
1199         }
1200 }
1201
1202 void
1203 bar_update(void)
1204 {
1205         time_t                  tmt;
1206         struct tm               tm;
1207         struct swm_region       *r;
1208         int                     i, x;
1209         size_t                  len;
1210         char                    s[SWM_BAR_MAX];
1211         char                    cn[SWM_BAR_MAX];
1212         char                    loc[SWM_BAR_MAX];
1213         char                    *b;
1214         char                    *stack = "";
1215
1216         if (bar_enabled == 0)
1217                 return;
1218         if (bar_extra && bar_extra_running) {
1219                 /* ignore short reads; it'll correct itself */
1220                 while ((b = fgetln(stdin, &len)) != NULL)
1221                         if (b && b[len - 1] == '\n') {
1222                                 b[len - 1] = '\0';
1223                                 strlcpy(bar_ext, b, sizeof bar_ext);
1224                         }
1225                 if (b == NULL && errno != EAGAIN) {
1226                         fprintf(stderr, "bar_extra failed: errno: %d %s\n",
1227                             errno, strerror(errno));
1228                         bar_extra_stop();
1229                 }
1230         } else
1231                 strlcpy(bar_ext, "", sizeof bar_ext);
1232
1233         if (clock_enabled == 0)
1234                 strlcpy(s, "", sizeof s);
1235         else {
1236                 time(&tmt);
1237                 localtime_r(&tmt, &tm);
1238                 strftime(s, sizeof s, clock_format, &tm);
1239                 strlcat(s, "    ", sizeof s);
1240         }
1241
1242         for (i = 0; i < ScreenCount(display); i++) {
1243                 x = 1;
1244                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1245                         strlcpy(cn, "", sizeof cn);
1246                         if (r && r->ws) {
1247                                 bar_class_name(cn, sizeof cn, r->ws->focus);
1248                                 bar_window_name(cn, sizeof cn, r->ws->focus);
1249                         }
1250
1251                         if (stack_enabled)
1252                                 stack = r->ws->cur_layout->name;
1253
1254                         snprintf(loc, sizeof loc, "%d:%d %s   %s%s    %s    %s",
1255                             x++, r->ws->idx + 1, stack, s, cn, bar_ext,
1256                             bar_vertext);
1257                         bar_print(r, loc);
1258                 }
1259         }
1260         alarm(bar_delay);
1261 }
1262
1263 void
1264 bar_signal(int sig)
1265 {
1266         bar_alarm = 1;
1267 }
1268
1269 void
1270 bar_toggle(struct swm_region *r, union arg *args)
1271 {
1272         struct swm_region       *tmpr;
1273         int                     i, sc = ScreenCount(display);
1274
1275         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
1276
1277         if (bar_enabled)
1278                 for (i = 0; i < sc; i++)
1279                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1280                                 XUnmapWindow(display, tmpr->bar_window);
1281         else
1282                 for (i = 0; i < sc; i++)
1283                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1284                                 XMapRaised(display, tmpr->bar_window);
1285
1286         bar_enabled = !bar_enabled;
1287
1288         stack();
1289         /* must be after stack */
1290         bar_update();
1291 }
1292
1293 void
1294 bar_refresh(void)
1295 {
1296         XSetWindowAttributes    wa;
1297         struct swm_region       *r;
1298         int                     i;
1299
1300         /* do this here because the conf file is in memory */
1301         if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
1302                 /* launch external status app */
1303                 bar_extra_running = 1;
1304                 if (pipe(bar_pipe) == -1)
1305                         err(1, "pipe error");
1306                 socket_setnonblock(bar_pipe[0]);
1307                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
1308                 if (dup2(bar_pipe[0], 0) == -1)
1309                         errx(1, "dup2");
1310                 if (dup2(bar_pipe[1], 1) == -1)
1311                         errx(1, "dup2");
1312                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1313                         err(1, "could not disable SIGPIPE");
1314                 switch (bar_pid = fork()) {
1315                 case -1:
1316                         err(1, "cannot fork");
1317                         break;
1318                 case 0: /* child */
1319                         close(bar_pipe[0]);
1320                         execvp(bar_argv[0], bar_argv);
1321                         err(1, "%s external app failed", bar_argv[0]);
1322                         break;
1323                 default: /* parent */
1324                         close(bar_pipe[1]);
1325                         break;
1326                 }
1327         }
1328
1329         bzero(&wa, sizeof wa);
1330         for (i = 0; i < ScreenCount(display); i++)
1331                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1332                         wa.border_pixel =
1333                             screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
1334                         wa.background_pixel =
1335                             screens[i].c[SWM_S_COLOR_BAR].color;
1336                         XChangeWindowAttributes(display, r->bar_window,
1337                             CWBackPixel | CWBorderPixel, &wa);
1338                 }
1339         bar_update();
1340 }
1341
1342 void
1343 bar_setup(struct swm_region *r)
1344 {
1345         int                     i, x, y;
1346
1347         if (bar_fs) {
1348                 XFreeFont(display, bar_fs);
1349                 bar_fs = NULL;
1350         }
1351
1352         for (i = 0; bar_fonts[i] != NULL; i++) {
1353                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
1354                 if (bar_fs) {
1355                         bar_fidx = i;
1356                         break;
1357                 }
1358         }
1359         if (bar_fonts[i] == NULL)
1360                         errx(1, "couldn't load font");
1361         if (bar_fs == NULL)
1362                 errx(1, "couldn't create font structure");
1363
1364         bar_height = bar_fs->ascent + bar_fs->descent + 1 + 2 * bar_border_width;
1365         x = X(r);
1366         y = bar_at_bottom ? (Y(r) + HEIGHT(r) - bar_height) : Y(r);
1367
1368         r->bar_window = XCreateSimpleWindow(display,
1369             r->s->root, x, y, WIDTH(r) - 2 * bar_border_width, bar_height - 2 * bar_border_width,
1370             bar_border_width, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
1371             r->s->c[SWM_S_COLOR_BAR].color);
1372         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
1373         XSetFont(display, bar_gc, bar_fs->fid);
1374         XSelectInput(display, r->bar_window, VisibilityChangeMask);
1375         if (bar_enabled)
1376                 XMapRaised(display, r->bar_window);
1377         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
1378
1379         if (signal(SIGALRM, bar_signal) == SIG_ERR)
1380                 err(1, "could not install bar_signal");
1381         bar_refresh();
1382 }
1383
1384 void
1385 set_win_state(struct ws_win *win, long state)
1386 {
1387         long                    data[] = {state, None};
1388
1389         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1390
1391         if (win == NULL)
1392                 return;
1393
1394         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1395             (unsigned char *)data, 2);
1396 }
1397
1398 long
1399 getstate(Window w)
1400 {
1401         long                    result = -1;
1402         unsigned char           *p = NULL;
1403         unsigned long           n;
1404
1405         if (!get_property(w, astate, 2L, astate, &n, &p))
1406                 return (-1);
1407         if (n != 0)
1408                 result = *((long *)p);
1409         XFree(p);
1410         return (result);
1411 }
1412
1413 void
1414 version(struct swm_region *r, union arg *args)
1415 {
1416         bar_version = !bar_version;
1417         if (bar_version)
1418                 snprintf(bar_vertext, sizeof bar_vertext, "Version: %s CVS: %s",
1419                     SWM_VERSION, cvstag);
1420         else
1421                 strlcpy(bar_vertext, "", sizeof bar_vertext);
1422         bar_update();
1423 }
1424
1425 void
1426 client_msg(struct ws_win *win, Atom a)
1427 {
1428         XClientMessageEvent     cm;
1429
1430         if (win == NULL)
1431                 return;
1432
1433         bzero(&cm, sizeof cm);
1434         cm.type = ClientMessage;
1435         cm.window = win->id;
1436         cm.message_type = aprot;
1437         cm.format = 32;
1438         cm.data.l[0] = a;
1439         cm.data.l[1] = CurrentTime;
1440         XSendEvent(display, win->id, False, 0L, (XEvent *)&cm);
1441 }
1442
1443 void
1444 config_win(struct ws_win *win, XConfigureRequestEvent  *ev)
1445 {
1446         XConfigureEvent         ce;
1447
1448         if (win == NULL)
1449                 return;
1450
1451         if (ev == NULL) {
1452                 DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
1453                     win->id, win->g.x, win->g.y, win->g.w, win->g.h);
1454
1455                 ce.type = ConfigureNotify;
1456                 ce.display = display;
1457                 ce.event = win->id;
1458                 ce.window = win->id;
1459                 ce.x = win->g.x;
1460                 ce.y = win->g.y;
1461                 ce.width = win->g.w;
1462                 ce.height = win->g.h;
1463                 ce.border_width = border_width;
1464                 ce.above = None;
1465                 ce.override_redirect = False;
1466         } else {
1467                 DNPRINTF(SWM_D_MISC, "config_win: ev win %lu x %d y %d w %d h %d\n",
1468                     ev->window, ev->x, ev->y, ev->width, ev->height);
1469                 ce.type = ConfigureNotify;
1470                 ce.display = ev->display;
1471                 ce.event = ev->window;
1472                 ce.window = ev->window;
1473                 ce.x = ev->x;
1474                 ce.y = ev->y;
1475                 ce.width = ev->width;
1476                 ce.height = ev->height;
1477                 ce.border_width = ev->border_width;
1478                 ce.above = ev->above;
1479                 ce.override_redirect = False;
1480         }
1481
1482         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
1483 }
1484
1485 int
1486 count_win(struct workspace *ws, int count_transient)
1487 {
1488         struct ws_win           *win;
1489         int                     count = 0;
1490
1491         TAILQ_FOREACH(win, &ws->winlist, entry) {
1492                 if (count_transient == 0 && win->floating)
1493                         continue;
1494                 if (count_transient == 0 && win->transient)
1495                         continue;
1496                 if (win->iconic)
1497                         continue;
1498                 count++;
1499         }
1500         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
1501
1502         return (count);
1503 }
1504
1505 void
1506 quit(struct swm_region *r, union arg *args)
1507 {
1508         DNPRINTF(SWM_D_MISC, "quit\n");
1509         running = 0;
1510 }
1511
1512 void
1513 unmap_window(struct ws_win *win)
1514 {
1515         if (win == NULL)
1516                 return;
1517
1518         /* don't unmap again */
1519         if (getstate(win->id) == IconicState)
1520                 return;
1521
1522         set_win_state(win, InactiveState);
1523
1524         XUnmapWindow(display, win->id);
1525         XSetWindowBorder(display, win->id,
1526             win->s->c[SWM_S_COLOR_UNFOCUS].color);
1527 }
1528
1529 void
1530 unmap_all(void)
1531 {
1532         struct ws_win           *win;
1533         int                     i, j;
1534
1535         for (i = 0; i < ScreenCount(display); i++)
1536                 for (j = 0; j < SWM_WS_MAX; j++)
1537                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1538                                 unmap_window(win);
1539 }
1540
1541 void
1542 fake_keypress(struct ws_win *win, int keysym, int modifiers)
1543 {
1544         XKeyEvent event;
1545
1546         if (win == NULL)
1547                 return;
1548
1549         event.display = display;        /* Ignored, but what the hell */
1550         event.window = win->id;
1551         event.root = win->s->root;
1552         event.subwindow = None;
1553         event.time = CurrentTime;
1554         event.x = win->g.x;
1555         event.y = win->g.y;
1556         event.x_root = 1;
1557         event.y_root = 1;
1558         event.same_screen = True;
1559         event.keycode = XKeysymToKeycode(display, keysym);
1560         event.state = modifiers;
1561
1562         event.type = KeyPress;
1563         XSendEvent(event.display, event.window, True,
1564             KeyPressMask, (XEvent *)&event);
1565
1566         event.type = KeyRelease;
1567         XSendEvent(event.display, event.window, True,
1568             KeyPressMask, (XEvent *)&event);
1569
1570 }
1571
1572 void
1573 restart(struct swm_region *r, union arg *args)
1574 {
1575         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
1576
1577         /* disable alarm because the following code may not be interrupted */
1578         alarm(0);
1579         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
1580                 errx(1, "can't disable alarm");
1581
1582         bar_extra_stop();
1583         bar_extra = 1;
1584         unmap_all();
1585         XCloseDisplay(display);
1586         execvp(start_argv[0], start_argv);
1587         fprintf(stderr, "execvp failed\n");
1588         perror(" failed");
1589         quit(NULL, NULL);
1590 }
1591
1592 struct swm_region *
1593 root_to_region(Window root)
1594 {
1595         struct swm_region       *r = NULL;
1596         Window                  rr, cr;
1597         int                     i, x, y, wx, wy;
1598         unsigned int            mask;
1599
1600         for (i = 0; i < ScreenCount(display); i++)
1601                 if (screens[i].root == root)
1602                         break;
1603
1604         if (XQueryPointer(display, screens[i].root,
1605             &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
1606                 /* choose a region based on pointer location */
1607                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1608                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
1609                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
1610                                 break;
1611         }
1612
1613         if (r == NULL)
1614                 r = TAILQ_FIRST(&screens[i].rl);
1615
1616         return (r);
1617 }
1618
1619 struct ws_win *
1620 find_unmanaged_window(Window id)
1621 {
1622         struct ws_win           *win;
1623         int                     i, j;
1624
1625         for (i = 0; i < ScreenCount(display); i++)
1626                 for (j = 0; j < SWM_WS_MAX; j++)
1627                         TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
1628                             entry)
1629                                 if (id == win->id)
1630                                         return (win);
1631         return (NULL);
1632 }
1633
1634 struct ws_win *
1635 find_window(Window id)
1636 {
1637         struct ws_win           *win;
1638         Window                  wrr, wpr, *wcr = NULL;
1639         int                     i, j;
1640         unsigned int            nc;
1641
1642         for (i = 0; i < ScreenCount(display); i++)
1643                 for (j = 0; j < SWM_WS_MAX; j++)
1644                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1645                                 if (id == win->id)
1646                                         return (win);
1647
1648         /* if we were looking for the parent return that window instead */
1649         if (XQueryTree(display, id, &wrr, &wpr, &wcr, &nc) == 0)
1650                 return (NULL);
1651         if (wcr)
1652                 XFree(wcr);
1653
1654         /* ignore not found and root */
1655         if (wpr == 0 || wrr == wpr)
1656                 return (NULL);
1657
1658         /* look for parent */
1659         for (i = 0; i < ScreenCount(display); i++)
1660                 for (j = 0; j < SWM_WS_MAX; j++)
1661                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1662                                 if (wpr == win->id)
1663                                         return (win);
1664
1665         return (NULL);
1666 }
1667
1668 void
1669 spawn(struct swm_region *r, union arg *args, int close_fd)
1670 {
1671         int                     fd;
1672         char                    *ret = NULL;
1673
1674         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
1675
1676         if (display)
1677                 close(ConnectionNumber(display));
1678
1679         setenv("LD_PRELOAD", SWM_LIB, 1);
1680
1681         if (asprintf(&ret, "%d", r->ws->idx) == -1) {
1682                 perror("_SWM_WS");
1683                 _exit(1);
1684         }
1685         setenv("_SWM_WS", ret, 1);
1686         free(ret);
1687         ret = NULL;
1688
1689         if (asprintf(&ret, "%d", getpid()) == -1) {
1690                 perror("_SWM_PID");
1691                 _exit(1);
1692         }
1693         setenv("_SWM_PID", ret, 1);
1694         free(ret);
1695         ret = NULL;
1696
1697         if (setsid() == -1) {
1698                 perror("setsid");
1699                 _exit(1);
1700         }
1701
1702         if (close_fd) {
1703                 /*
1704                  * close stdin and stdout to prevent interaction between apps
1705                  * and the baraction script
1706                  * leave stderr open to record errors
1707                 */
1708                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
1709                         perror("open");
1710                         _exit(1);
1711                 }
1712                 dup2(fd, STDIN_FILENO);
1713                 dup2(fd, STDOUT_FILENO);
1714                 if (fd > 2)
1715                         close(fd);
1716         }
1717
1718         execvp(args->argv[0], args->argv);
1719
1720         perror("execvp");
1721         _exit(1);
1722 }
1723
1724 void
1725 spawnterm(struct swm_region *r, union arg *args)
1726 {
1727         DNPRINTF(SWM_D_MISC, "spawnterm\n");
1728
1729         if (term_width)
1730                 setenv("_SWM_XTERM_FONTADJ", "", 1);
1731         if (fork() == 0)
1732                 spawn(r, args, 1);
1733 }
1734
1735 void
1736 kill_refs(struct ws_win *win)
1737 {
1738         int                     i, x;
1739         struct swm_region       *r;
1740         struct workspace        *ws;
1741
1742         if (win == NULL)
1743                 return;
1744
1745         for (i = 0; i < ScreenCount(display); i++)
1746                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1747                         for (x = 0; x < SWM_WS_MAX; x++) {
1748                                 ws = &r->s->ws[x];
1749                                 if (win == ws->focus)
1750                                         ws->focus = NULL;
1751                                 if (win == ws->focus_prev)
1752                                         ws->focus_prev = NULL;
1753                         }
1754 }
1755
1756 int
1757 validate_win(struct ws_win *testwin)
1758 {
1759         struct ws_win           *win;
1760         struct workspace        *ws;
1761         struct swm_region       *r;
1762         int                     i, x, foundit = 0;
1763
1764         if (testwin == NULL)
1765                 return(0);
1766
1767         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1768                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1769                         for (x = 0; x < SWM_WS_MAX; x++) {
1770                                 ws = &r->s->ws[x];
1771                                 TAILQ_FOREACH(win, &ws->winlist, entry)
1772                                         if (win == testwin)
1773                                                 return (0);
1774                         }
1775         return (1);
1776 }
1777
1778 int
1779 validate_ws(struct workspace *testws)
1780 {
1781         struct swm_region       *r;
1782         struct workspace        *ws;
1783         int                     foundit, i, x;
1784
1785         /* validate all ws */
1786         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1787                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1788                         for (x = 0; x < SWM_WS_MAX; x++) {
1789                                 ws = &r->s->ws[x];
1790                                 if (ws == testws)
1791                                         return (0);
1792                         }
1793         return (1);
1794 }
1795
1796 void
1797 unfocus_win(struct ws_win *win)
1798 {
1799         XEvent                  cne;
1800         Window                  none = None;
1801
1802         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", WINID(win));
1803
1804         if (win == NULL)
1805                 return;
1806         if (win->ws == NULL)
1807                 return;
1808
1809         if (validate_ws(win->ws))
1810                 return; /* XXX this gets hit with thunderbird, needs fixing */
1811
1812         if (win->ws->r == NULL)
1813                 return;
1814
1815         if (validate_win(win)) {
1816                 kill_refs(win);
1817                 return;
1818         }
1819
1820         if (win->ws->focus == win) {
1821                 win->ws->focus = NULL;
1822                 win->ws->focus_prev = win;
1823         }
1824
1825         if (validate_win(win->ws->focus)) {
1826                 kill_refs(win->ws->focus);
1827                 win->ws->focus = NULL;
1828         }
1829         if (validate_win(win->ws->focus_prev)) {
1830                 kill_refs(win->ws->focus_prev);
1831                 win->ws->focus_prev = NULL;
1832         }
1833
1834         /* drain all previous unfocus events */
1835         while (XCheckTypedEvent(display, FocusOut, &cne) == True)
1836                 ;
1837
1838         grabbuttons(win, 0);
1839         XSetWindowBorder(display, win->id,
1840             win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1841
1842         XChangeProperty(display, win->s->root,
1843             ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1844             PropModeReplace, (unsigned char *)&none,1);
1845 }
1846
1847 void
1848 unfocus_all(void)
1849 {
1850         struct ws_win           *win;
1851         int                     i, j;
1852
1853         DNPRINTF(SWM_D_FOCUS, "unfocus_all\n");
1854
1855         for (i = 0; i < ScreenCount(display); i++)
1856                 for (j = 0; j < SWM_WS_MAX; j++)
1857                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1858                                 unfocus_win(win);
1859 }
1860
1861 void
1862 focus_win(struct ws_win *win)
1863 {
1864         XEvent                  cne;
1865         Window                  cur_focus;
1866         int                     rr;
1867         struct ws_win           *cfw = NULL;
1868
1869
1870         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
1871
1872         if (win == NULL)
1873                 return;
1874         if (win->ws == NULL)
1875                 return;
1876
1877         if (validate_ws(win->ws))
1878                 return; /* XXX this gets hit with thunderbird, needs fixing */
1879
1880         if (validate_win(win)) {
1881                 kill_refs(win);
1882                 return;
1883         }
1884
1885         if (validate_win(win)) {
1886                 kill_refs(win);
1887                 return;
1888         }
1889
1890         XGetInputFocus(display, &cur_focus, &rr);
1891         if ((cfw = find_window(cur_focus)) != NULL)
1892                 unfocus_win(cfw);
1893
1894         win->ws->focus = win;
1895
1896         if (win->ws->r != NULL) {
1897                 /* drain all previous focus events */
1898                 while (XCheckTypedEvent(display, FocusIn, &cne) == True)
1899                         ;
1900
1901                 if (win->java == 0)
1902                         XSetInputFocus(display, win->id,
1903                             RevertToParent, CurrentTime);
1904                 XMapRaised(display, win->id);
1905                 grabbuttons(win, 1);
1906                 XSetWindowBorder(display, win->id,
1907                     win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
1908                 if (win->ws->cur_layout->flags & SWM_L_MAPONFOCUS)
1909                         XMapRaised(display, win->id);
1910
1911                 XChangeProperty(display, win->s->root,
1912                     ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1913                     PropModeReplace, (unsigned char *)&win->id,1);
1914         }
1915
1916         if (window_name_enabled)
1917                 bar_update();
1918 }
1919
1920 void
1921 switchws(struct swm_region *r, union arg *args)
1922 {
1923         int                     wsid = args->id, unmap_old = 0;
1924         struct swm_region       *this_r, *other_r;
1925         struct ws_win           *win;
1926         struct workspace        *new_ws, *old_ws;
1927         union arg               a;
1928
1929         if (!(r && r->s))
1930                 return;
1931
1932         this_r = r;
1933         old_ws = this_r->ws;
1934         new_ws = &this_r->s->ws[wsid];
1935
1936         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
1937             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
1938             old_ws->idx, wsid);
1939
1940         if (new_ws == NULL || old_ws == NULL)
1941                 return;
1942         if (new_ws == old_ws)
1943                 return;
1944
1945         other_r = new_ws->r;
1946         if (other_r == NULL) {
1947                 /* the other workspace is hidden, hide this one */
1948                 old_ws->r = NULL;
1949                 unmap_old = 1;
1950         } else {
1951                 /* the other ws is visible in another region, exchange them */
1952                 other_r->ws_prior = new_ws;
1953                 other_r->ws = old_ws;
1954                 old_ws->r = other_r;
1955         }
1956         this_r->ws_prior = old_ws;
1957         this_r->ws = new_ws;
1958         new_ws->r = this_r;
1959
1960         stack();
1961         a.id = SWM_ARG_ID_FOCUSCUR;
1962         focus(new_ws->r, &a);
1963         bar_update();
1964
1965         /* unmap old windows */
1966         if (unmap_old)
1967                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
1968                         unmap_window(win);
1969 }
1970
1971 void
1972 cyclews(struct swm_region *r, union arg *args)
1973 {
1974         union                   arg a;
1975         struct swm_screen       *s = r->s;
1976
1977         DNPRINTF(SWM_D_WS, "cyclews id %d "
1978             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
1979             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1980
1981         a.id = r->ws->idx;
1982         do {
1983                 switch (args->id) {
1984                 case SWM_ARG_ID_CYCLEWS_UP:
1985                         if (a.id < SWM_WS_MAX - 1)
1986                                 a.id++;
1987                         else
1988                                 a.id = 0;
1989                         break;
1990                 case SWM_ARG_ID_CYCLEWS_DOWN:
1991                         if (a.id > 0)
1992                                 a.id--;
1993                         else
1994                                 a.id = SWM_WS_MAX - 1;
1995                         break;
1996                 default:
1997                         return;
1998                 };
1999
2000                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
2001                         continue;
2002                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
2003                         continue;
2004
2005                 switchws(r, &a);
2006         } while (a.id != r->ws->idx);
2007 }
2008
2009 void
2010 priorws(struct swm_region *r, union arg *args)
2011 {
2012         union arg               a;
2013
2014         DNPRINTF(SWM_D_WS, "priorws id %d "
2015             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
2016             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2017
2018         if (r->ws_prior == NULL)
2019                 return;
2020
2021         a.id = r->ws_prior->idx;
2022         switchws(r, &a);
2023 }
2024
2025 void
2026 cyclescr(struct swm_region *r, union arg *args)
2027 {
2028         struct swm_region       *rr = NULL;
2029         union arg               a;
2030         int                     i, x, y;
2031
2032         /* do nothing if we don't have more than one screen */
2033         if (!(ScreenCount(display) > 1 || outputs > 1))
2034                 return;
2035
2036         i = r->s->idx;
2037         switch (args->id) {
2038         case SWM_ARG_ID_CYCLESC_UP:
2039                 rr = TAILQ_NEXT(r, entry);
2040                 if (rr == NULL)
2041                         rr = TAILQ_FIRST(&screens[i].rl);
2042                 break;
2043         case SWM_ARG_ID_CYCLESC_DOWN:
2044                 rr = TAILQ_PREV(r, swm_region_list, entry);
2045                 if (rr == NULL)
2046                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2047                 break;
2048         default:
2049                 return;
2050         };
2051         if (rr == NULL)
2052                 return;
2053
2054         /* move mouse to region */
2055         x = rr->g.x + 1;
2056         y = rr->g.y + 1 + (bar_enabled ? bar_height : 0);
2057         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2058
2059         a.id = SWM_ARG_ID_FOCUSCUR;
2060         focus(rr, &a);
2061
2062         if (rr->ws->focus) {
2063                 /* move to focus window */
2064                 x = rr->ws->focus->g.x + 1;
2065                 y = rr->ws->focus->g.y + 1;
2066                 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2067         }
2068 }
2069
2070 void
2071 sort_windows(struct ws_win_list *wl)
2072 {
2073         struct ws_win           *win, *parent, *nxt;
2074
2075         if (wl == NULL)
2076                 return;
2077
2078         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
2079                 nxt = TAILQ_NEXT(win, entry);
2080                 if (win->transient) {
2081                         parent = find_window(win->transient);
2082                         if (parent == NULL) {
2083                                 fprintf(stderr, "not possible bug\n");
2084                                 continue;
2085                         }
2086                         TAILQ_REMOVE(wl, win, entry);
2087                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
2088                 }
2089         }
2090
2091 }
2092
2093 void
2094 swapwin(struct swm_region *r, union arg *args)
2095 {
2096         struct ws_win           *target, *source;
2097         struct ws_win           *cur_focus;
2098         struct ws_win_list      *wl;
2099
2100
2101         DNPRINTF(SWM_D_WS, "swapwin id %d "
2102             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
2103             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2104
2105         cur_focus = r->ws->focus;
2106         if (cur_focus == NULL)
2107                 return;
2108
2109         source = cur_focus;
2110         wl = &source->ws->winlist;
2111
2112         switch (args->id) {
2113         case SWM_ARG_ID_SWAPPREV:
2114                 if (source->transient)
2115                         source = find_window(source->transient);
2116                 target = TAILQ_PREV(source, ws_win_list, entry);
2117                 if (target && target->transient)
2118                         target = find_window(target->transient);
2119                 TAILQ_REMOVE(wl, source, entry);
2120                 if (target == NULL)
2121                         TAILQ_INSERT_TAIL(wl, source, entry);
2122                 else
2123                         TAILQ_INSERT_BEFORE(target, source, entry);
2124                 break;
2125         case SWM_ARG_ID_SWAPNEXT:
2126                 target = TAILQ_NEXT(source, entry);
2127                 /* move the parent and let the sort handle the move */
2128                 if (source->transient)
2129                         source = find_window(source->transient);
2130                 TAILQ_REMOVE(wl, source, entry);
2131                 if (target == NULL)
2132                         TAILQ_INSERT_HEAD(wl, source, entry);
2133                 else
2134                         TAILQ_INSERT_AFTER(wl, target, source, entry);
2135                 break;
2136         case SWM_ARG_ID_SWAPMAIN:
2137                 target = TAILQ_FIRST(wl);
2138                 if (target == source) {
2139                         if (source->ws->focus_prev != NULL &&
2140                             source->ws->focus_prev != target)
2141
2142                                 source = source->ws->focus_prev;
2143                         else
2144                                 return;
2145                 }
2146                 if (target == NULL || source == NULL)
2147                         return;
2148                 source->ws->focus_prev = target;
2149                 TAILQ_REMOVE(wl, target, entry);
2150                 TAILQ_INSERT_BEFORE(source, target, entry);
2151                 TAILQ_REMOVE(wl, source, entry);
2152                 TAILQ_INSERT_HEAD(wl, source, entry);
2153                 break;
2154         case SWM_ARG_ID_MOVELAST:
2155                 TAILQ_REMOVE(wl, source, entry);
2156                 TAILQ_INSERT_TAIL(wl, source, entry);
2157                 break;
2158         default:
2159                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
2160                 return;
2161         }
2162
2163         sort_windows(wl);
2164
2165         stack();
2166 }
2167
2168 void
2169 focus_prev(struct ws_win *win)
2170 {
2171         struct ws_win           *winfocus = NULL, *winlostfocus = NULL;
2172         struct ws_win           *cur_focus = NULL;
2173         struct ws_win_list      *wl = NULL;
2174         struct workspace        *ws = NULL;
2175
2176         DNPRINTF(SWM_D_FOCUS, "focus_prev: id %lu\n", WINID(win));
2177
2178         if (!(win && win->ws))
2179                 return;
2180
2181         ws = win->ws;
2182         wl = &ws->winlist;
2183         cur_focus = ws->focus;
2184         winlostfocus = cur_focus;
2185
2186         /* pickle, just focus on whatever */
2187         if (cur_focus == NULL) {
2188                 /* use prev_focus if valid */
2189                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
2190                     find_window(WINID(ws->focus_prev)))
2191                         winfocus = ws->focus_prev;
2192                 if (winfocus == NULL)
2193                         winfocus = TAILQ_FIRST(wl);
2194                 goto done;
2195         }
2196
2197         /* if transient focus on parent */
2198         if (cur_focus->transient) {
2199                 winfocus = find_window(cur_focus->transient);
2200                 goto done;
2201         }
2202
2203         /* if in max_stack try harder */
2204         if (ws->cur_layout->flags & SWM_L_FOCUSPREV) {
2205                 if (cur_focus != ws->focus_prev)
2206                         winfocus = ws->focus_prev;
2207                 else if (cur_focus != ws->focus)
2208                         winfocus = ws->focus;
2209                 else
2210                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
2211                 if (winfocus)
2212                         goto done;
2213         }
2214
2215         if (cur_focus == win)
2216                 winfocus = TAILQ_PREV(win, ws_win_list, entry);
2217         if (winfocus == NULL)
2218                 winfocus = TAILQ_LAST(wl, ws_win_list);
2219         if (winfocus == NULL || winfocus == win)
2220                 winfocus = TAILQ_NEXT(cur_focus, entry);
2221 done:
2222         if (winfocus == winlostfocus || winfocus == NULL)
2223                 return;
2224
2225         focus_magic(winfocus);
2226 }
2227
2228 void
2229 focus(struct swm_region *r, union arg *args)
2230 {
2231         struct ws_win           *winfocus = NULL, *winlostfocus = NULL, *head;
2232         struct ws_win           *cur_focus = NULL;
2233         struct ws_win_list      *wl = NULL;
2234         struct workspace        *ws = NULL;
2235
2236         if (!(r && r->ws))
2237                 return;
2238
2239         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
2240
2241         /* treat FOCUS_CUR special */
2242         if (args->id == SWM_ARG_ID_FOCUSCUR) {
2243                 if (r->ws->focus && r->ws->focus->iconic == 0)
2244                         winfocus = r->ws->focus;
2245                 else if (r->ws->focus_prev && r->ws->focus_prev->iconic == 0)
2246                         winfocus = r->ws->focus_prev;
2247                 else
2248                         TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
2249                                 if (winfocus->iconic == 0)
2250                                         break;
2251
2252                 focus_magic(winfocus);
2253                 return;
2254         }
2255
2256         if ((cur_focus = r->ws->focus) == NULL)
2257                 return;
2258         ws = r->ws;
2259         wl = &ws->winlist;
2260
2261         winlostfocus = cur_focus;
2262
2263         switch (args->id) {
2264         case SWM_ARG_ID_FOCUSPREV:
2265                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
2266                 if (head == NULL)
2267                         head = TAILQ_LAST(wl, ws_win_list);
2268                 winfocus = head;
2269                 if (WINID(winfocus) == cur_focus->transient) {
2270                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
2271                         if (head == NULL)
2272                                 head = TAILQ_LAST(wl, ws_win_list);
2273                         winfocus = head;
2274                 }
2275
2276                 /* skip iconics */
2277                 if (winfocus && winfocus->iconic) {
2278                         TAILQ_FOREACH_REVERSE(winfocus, wl, ws_win_list, entry)
2279                                 if (winfocus->iconic == 0)
2280                                         break;
2281                 }
2282                 break;
2283
2284         case SWM_ARG_ID_FOCUSNEXT:
2285                 head = TAILQ_NEXT(cur_focus, entry);
2286                 if (head == NULL)
2287                         head = TAILQ_FIRST(wl);
2288                 winfocus = head;
2289
2290                 /* skip iconics */
2291                 if (winfocus && winfocus->iconic) {
2292                         TAILQ_FOREACH(winfocus, wl, entry)
2293                                 if (winfocus->iconic == 0)
2294                                         break;
2295                 }
2296                 break;
2297
2298         case SWM_ARG_ID_FOCUSMAIN:
2299                 winfocus = TAILQ_FIRST(wl);
2300                 if (winfocus == cur_focus)
2301                         winfocus = cur_focus->ws->focus_prev;
2302                 break;
2303
2304         default:
2305                 return;
2306         }
2307         if (winfocus == winlostfocus || winfocus == NULL)
2308                 return;
2309
2310         focus_magic(winfocus);
2311 }
2312
2313 void
2314 cycle_layout(struct swm_region *r, union arg *args)
2315 {
2316         struct workspace        *ws = r->ws;
2317         struct ws_win           *winfocus;
2318         union arg               a;
2319
2320         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
2321
2322         winfocus = ws->focus;
2323
2324         ws->cur_layout++;
2325         if (ws->cur_layout->l_stack == NULL)
2326                 ws->cur_layout = &layouts[0];
2327
2328         stack();
2329         a.id = SWM_ARG_ID_FOCUSCUR;
2330         focus(r, &a);
2331         bar_update();
2332 }
2333
2334 void
2335 stack_config(struct swm_region *r, union arg *args)
2336 {
2337         struct workspace        *ws = r->ws;
2338
2339         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
2340             args->id, ws->idx);
2341
2342         if (ws->cur_layout->l_config != NULL)
2343                 ws->cur_layout->l_config(ws, args->id);
2344
2345         if (args->id != SWM_ARG_ID_STACKINIT);
2346                 stack();
2347 }
2348
2349 void
2350 stack(void) {
2351         struct swm_geometry     g;
2352         struct swm_region       *r;
2353         int                     i, j;
2354
2355         DNPRINTF(SWM_D_STACK, "stack\n");
2356
2357         for (i = 0; i < ScreenCount(display); i++) {
2358                 j = 0;
2359                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2360                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
2361                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
2362
2363                         /* start with screen geometry, adjust for bar */
2364                         g = r->g;
2365                         g.w -= 2 * border_width;
2366                         g.h -= 2 * border_width;
2367                         if (bar_enabled) {
2368                                 if (!bar_at_bottom)
2369                                         g.y += bar_height;
2370                                 g.h -= bar_height;
2371                         }
2372                         r->ws->cur_layout->l_stack(r->ws, &g);
2373                         /* save r so we can track region changes */
2374                         r->ws->old_r = r;
2375                 }
2376         }
2377         if (font_adjusted)
2378                 font_adjusted--;
2379 }
2380
2381 void
2382 store_float_geom(struct ws_win *win, struct swm_region *r)
2383 {
2384         /* retain window geom and region geom */
2385         win->g_float.x = win->g.x;
2386         win->g_float.y = win->g.y;
2387         win->g_float.w = win->g.w;
2388         win->g_float.h = win->g.h;
2389         win->rg_float.x = r->g.x;
2390         win->rg_float.y = r->g.y;
2391         win->rg_float.w = r->g.w;
2392         win->rg_float.h = r->g.h;
2393         win->g_floatvalid = 1;
2394 }
2395
2396 void
2397 stack_floater(struct ws_win *win, struct swm_region *r)
2398 {
2399         unsigned int            mask;
2400         XWindowChanges          wc;
2401
2402         if (win == NULL)
2403                 return;
2404
2405         bzero(&wc, sizeof wc);
2406         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
2407
2408         /*
2409          * to allow windows to change their size (e.g. mplayer fs) only retrieve
2410          * geom on ws switches or return from max mode
2411          */
2412
2413         if (win->floatmaxed || (r != r->ws->old_r && win->g_floatvalid
2414             && !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
2415                 /*
2416                  * use stored g and rg to set relative position and size
2417                  * as in old region or before max stack mode
2418                  */
2419                 win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
2420                 win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
2421                 win->g.w = win->g_float.w;
2422                 win->g.h = win->g_float.h;
2423                 win->g_floatvalid = 0;
2424         }
2425
2426         win->floatmaxed = 0;
2427
2428         if ((win->quirks & SWM_Q_FULLSCREEN) && (win->g.w >= WIDTH(r)) &&
2429             (win->g.h >= HEIGHT(r)))
2430                 wc.border_width = 0;
2431         else
2432                 wc.border_width = border_width;
2433         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
2434                 win->g.w = (double)WIDTH(r) * dialog_ratio;
2435                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
2436         }
2437
2438         if (!win->manual) {
2439                 /*
2440                  * floaters and transients are auto-centred unless moved
2441                  * or resized
2442                  */
2443                 win->g.x = r->g.x + (WIDTH(r) - win->g.w) / 2 - wc.border_width;
2444                 win->g.y = r->g.y + (HEIGHT(r) - win->g.h) / 2 - wc.border_width;
2445         }
2446
2447         /* win can be outside r if new r smaller than old r */
2448         /* Ensure top left corner inside r (move probs otherwise) */
2449         if (win->g.x < r->g.x - wc.border_width)
2450                 win->g.x = r->g.x - wc.border_width;
2451         if (win->g.x > r->g.x + r->g.w - 1)
2452                 win->g.x = (win->g.w > r->g.w) ? r->g.x :
2453                     (r->g.x + r->g.w - win->g.w - 2 * wc.border_width);
2454         if (win->g.y < r->g.y - wc.border_width)
2455                 win->g.y = r->g.y - wc.border_width;
2456         if (win->g.y > r->g.y + r->g.h - 1)
2457                 win->g.y = (win->g.h > r->g.h) ? r->g.y :
2458                     (r->g.y + r->g.h - win->g.h - 2 * wc.border_width);
2459
2460         wc.x = win->g.x;
2461         wc.y = win->g.y;
2462         wc.width = win->g.w;
2463         wc.height = win->g.h;
2464
2465         /*
2466          * Retain floater and transient geometry for correct positioning
2467          * when ws changes region
2468          */
2469         if (!(win->ewmh_flags & EWMH_F_FULLSCREEN))
2470                 store_float_geom(win, r);
2471
2472         DNPRINTF(SWM_D_MISC, "stack_floater: win %lu x %d y %d w %d h %d\n",
2473             win->id, wc.x, wc.y, wc.width, wc.height);
2474
2475         XConfigureWindow(display, win->id, mask, &wc);
2476 }
2477
2478 /*
2479  * Send keystrokes to terminal to decrease/increase the font size as the
2480  * window size changes.
2481  */
2482 void
2483 adjust_font(struct ws_win *win)
2484 {
2485         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
2486             win->floating || win->transient)
2487                 return;
2488
2489         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
2490             win->g.w / win->sh.width_inc < term_width &&
2491             win->font_steps < SWM_MAX_FONT_STEPS) {
2492                 win->font_size_boundary[win->font_steps] =
2493                     (win->sh.width_inc * term_width) + win->sh.base_width;
2494                 win->font_steps++;
2495                 font_adjusted++;
2496                 win->last_inc = win->sh.width_inc;
2497                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
2498         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
2499             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
2500                 win->font_steps--;
2501                 font_adjusted++;
2502                 win->last_inc = win->sh.width_inc;
2503                 fake_keypress(win, XK_KP_Add, ShiftMask);
2504         }
2505 }
2506
2507 #define SWAPXY(g)       do {                            \
2508         int tmp;                                        \
2509         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
2510         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
2511 } while (0)
2512 void
2513 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
2514 {
2515         XWindowChanges          wc;
2516         XWindowAttributes       wa;
2517         struct swm_geometry     win_g, r_g = *g;
2518         struct ws_win           *win, *fs_win = 0;
2519         int                     i, j, s, stacks;
2520         int                     w_inc = 1, h_inc, w_base = 1, h_base;
2521         int                     hrh, extra = 0, h_slice, last_h = 0;
2522         int                     split, colno, winno, mwin, msize, mscale;
2523         int                     remain, missing, v_slice, reconfigure;
2524         unsigned int            mask;
2525
2526         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
2527             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
2528
2529         winno = count_win(ws, 0);
2530         if (winno == 0 && count_win(ws, 1) == 0)
2531                 return;
2532
2533         TAILQ_FOREACH(win, &ws->winlist, entry)
2534                 if (win->transient == 0 && win->floating == 0 && win->iconic == 0)
2535                         break;
2536
2537         if (win == NULL)
2538                 goto notiles;
2539
2540         if (rot) {
2541                 w_inc = win->sh.width_inc;
2542                 w_base = win->sh.base_width;
2543                 mwin = ws->l_state.horizontal_mwin;
2544                 mscale = ws->l_state.horizontal_msize;
2545                 stacks = ws->l_state.horizontal_stacks;
2546                 SWAPXY(&r_g);
2547         } else {
2548                 w_inc = win->sh.height_inc;
2549                 w_base = win->sh.base_height;
2550                 mwin = ws->l_state.vertical_mwin;
2551                 mscale = ws->l_state.vertical_msize;
2552                 stacks = ws->l_state.vertical_stacks;
2553         }
2554         win_g = r_g;
2555
2556         if (stacks > winno - mwin)
2557                 stacks = winno - mwin;
2558         if (stacks < 1)
2559                 stacks = 1;
2560
2561         h_slice = r_g.h / SWM_H_SLICE;
2562         if (mwin && winno > mwin) {
2563                 v_slice = r_g.w / SWM_V_SLICE;
2564
2565                 split = mwin;
2566                 colno = split;
2567                 win_g.w = v_slice * mscale;
2568
2569                 if (w_inc > 1 && w_inc < v_slice) {
2570                         /* adjust for window's requested size increment */
2571                         remain = (win_g.w - w_base) % w_inc;
2572                         missing = w_inc - remain;
2573                         win_g.w -= remain;
2574                         extra += remain;
2575                 }
2576
2577                 msize = win_g.w;
2578                 if (flip)
2579                         win_g.x += r_g.w - msize;
2580         } else {
2581                 msize = -2;
2582                 colno = split = winno / stacks;
2583                 win_g.w = ((r_g.w - (stacks * 2 * border_width) + 2 * border_width) / stacks);
2584         }
2585         hrh = r_g.h / colno;
2586         extra = r_g.h - (colno * hrh);
2587         win_g.h = hrh - 2 * border_width;
2588
2589         /*  stack all the tiled windows */
2590         i = j = 0, s = stacks;
2591         TAILQ_FOREACH(win, &ws->winlist, entry) {
2592                 if (win->transient != 0 || win->floating != 0)
2593                         continue;
2594                 if (win->iconic != 0)
2595                         continue;
2596
2597                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2598                         fs_win = win;
2599                         continue;
2600                 }
2601
2602                 if (split && i == split) {
2603                         colno = (winno - mwin) / stacks;
2604                         if (s <= (winno - mwin) % stacks)
2605                                 colno++;
2606                         split = split + colno;
2607                         hrh = (r_g.h / colno);
2608                         extra = r_g.h - (colno * hrh);
2609                         if (flip)
2610                                 win_g.x = r_g.x;
2611                         else
2612                                 win_g.x += win_g.w + 2 * border_width;
2613                         win_g.w = (r_g.w - msize - (stacks * 2 * border_width)) / stacks;
2614                         if (s == 1)
2615                                 win_g.w += (r_g.w - msize - (stacks * 2 * border_width)) %
2616                                     stacks;
2617                         s--;
2618                         j = 0;
2619                 }
2620                 win_g.h = hrh - 2 * border_width;
2621                 if (rot) {
2622                         h_inc = win->sh.width_inc;
2623                         h_base = win->sh.base_width;
2624                 } else {
2625                         h_inc = win->sh.height_inc;
2626                         h_base = win->sh.base_height;
2627                 }
2628                 if (j == colno - 1) {
2629                         win_g.h = hrh + extra;
2630                 } else if (h_inc > 1 && h_inc < h_slice) {
2631                         /* adjust for window's requested size increment */
2632                         remain = (win_g.h - h_base) % h_inc;
2633                         missing = h_inc - remain;
2634
2635                         if (missing <= extra || j == 0) {
2636                                 extra -= missing;
2637                                 win_g.h += missing;
2638                         } else {
2639                                 win_g.h -= remain;
2640                                 extra += remain;
2641                         }
2642                 }
2643
2644                 if (j == 0)
2645                         win_g.y = r_g.y;
2646                 else
2647                         win_g.y += last_h + 2 * border_width;
2648
2649                 bzero(&wc, sizeof wc);
2650                 if (disable_border && bar_enabled == 0 && winno == 1){
2651                         wc.border_width = 0;
2652                         win_g.w += 2 * border_width;
2653                         win_g.h += 2 * border_width;
2654                 } else
2655                         wc.border_width = border_width;
2656                 reconfigure = 0;
2657                 if (rot) {
2658                         if (win->g.x != win_g.y || win->g.y != win_g.x ||
2659                             win->g.w != win_g.h || win->g.h != win_g.w) {
2660                                 reconfigure = 1;
2661                                 win->g.x = wc.x = win_g.y;
2662                                 win->g.y = wc.y = win_g.x;
2663                                 win->g.w = wc.width = win_g.h;
2664                                 win->g.h = wc.height = win_g.w;
2665                         }
2666                 } else {
2667                         if (win->g.x != win_g.x || win->g.y != win_g.y ||
2668                             win->g.w != win_g.w || win->g.h != win_g.h) {
2669                                 reconfigure = 1;
2670                                 win->g.x = wc.x = win_g.x;
2671                                 win->g.y = wc.y = win_g.y;
2672                                 win->g.w = wc.width = win_g.w;
2673                                 win->g.h = wc.height = win_g.h;
2674                         }
2675                 }
2676                 if (reconfigure) {
2677                         adjust_font(win);
2678                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2679                         XConfigureWindow(display, win->id, mask, &wc);
2680                 }
2681
2682                 if (XGetWindowAttributes(display, win->id, &wa))
2683                         if (wa.map_state == IsUnmapped)
2684                                 XMapRaised(display, win->id);
2685
2686                 last_h = win_g.h;
2687                 i++;
2688                 j++;
2689         }
2690
2691 notiles:
2692         /* now, stack all the floaters and transients */
2693         TAILQ_FOREACH(win, &ws->winlist, entry) {
2694                 if (win->transient == 0 && win->floating == 0)
2695                         continue;
2696                 if (win->iconic == 1)
2697                         continue;
2698                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2699                         fs_win = win;
2700                         continue;
2701                 }
2702
2703                 stack_floater(win, ws->r);
2704                 XMapRaised(display, win->id);
2705         }
2706
2707         if (fs_win) {
2708                 stack_floater(fs_win, ws->r);
2709                 XMapRaised(display, fs_win->id);
2710         }
2711 }
2712
2713 void
2714 vertical_config(struct workspace *ws, int id)
2715 {
2716         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
2717
2718         switch (id) {
2719         case SWM_ARG_ID_STACKRESET:
2720         case SWM_ARG_ID_STACKINIT:
2721                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
2722                 ws->l_state.vertical_mwin = 1;
2723                 ws->l_state.vertical_stacks = 1;
2724                 break;
2725         case SWM_ARG_ID_MASTERSHRINK:
2726                 if (ws->l_state.vertical_msize > 1)
2727                         ws->l_state.vertical_msize--;
2728                 break;
2729         case SWM_ARG_ID_MASTERGROW:
2730                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
2731                         ws->l_state.vertical_msize++;
2732                 break;
2733         case SWM_ARG_ID_MASTERADD:
2734                 ws->l_state.vertical_mwin++;
2735                 break;
2736         case SWM_ARG_ID_MASTERDEL:
2737                 if (ws->l_state.vertical_mwin > 0)
2738                         ws->l_state.vertical_mwin--;
2739                 break;
2740         case SWM_ARG_ID_STACKINC:
2741                 ws->l_state.vertical_stacks++;
2742                 break;
2743         case SWM_ARG_ID_STACKDEC:
2744                 if (ws->l_state.vertical_stacks > 1)
2745                         ws->l_state.vertical_stacks--;
2746                 break;
2747         default:
2748                 return;
2749         }
2750 }
2751
2752 void
2753 vertical_stack(struct workspace *ws, struct swm_geometry *g)
2754 {
2755         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
2756
2757         stack_master(ws, g, 0, 0);
2758 }
2759
2760 void
2761 horizontal_config(struct workspace *ws, int id)
2762 {
2763         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
2764
2765         switch (id) {
2766         case SWM_ARG_ID_STACKRESET:
2767         case SWM_ARG_ID_STACKINIT:
2768                 ws->l_state.horizontal_mwin = 1;
2769                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
2770                 ws->l_state.horizontal_stacks = 1;
2771                 break;
2772         case SWM_ARG_ID_MASTERSHRINK:
2773                 if (ws->l_state.horizontal_msize > 1)
2774                         ws->l_state.horizontal_msize--;
2775                 break;
2776         case SWM_ARG_ID_MASTERGROW:
2777                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
2778                         ws->l_state.horizontal_msize++;
2779                 break;
2780         case SWM_ARG_ID_MASTERADD:
2781                 ws->l_state.horizontal_mwin++;
2782                 break;
2783         case SWM_ARG_ID_MASTERDEL:
2784                 if (ws->l_state.horizontal_mwin > 0)
2785                         ws->l_state.horizontal_mwin--;
2786                 break;
2787         case SWM_ARG_ID_STACKINC:
2788                 ws->l_state.horizontal_stacks++;
2789                 break;
2790         case SWM_ARG_ID_STACKDEC:
2791                 if (ws->l_state.horizontal_stacks > 1)
2792                         ws->l_state.horizontal_stacks--;
2793                 break;
2794         default:
2795                 return;
2796         }
2797 }
2798
2799 void
2800 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
2801 {
2802         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
2803
2804         stack_master(ws, g, 1, 0);
2805 }
2806
2807 /* fullscreen view */
2808 void
2809 max_stack(struct workspace *ws, struct swm_geometry *g)
2810 {
2811         XWindowChanges          wc;
2812         struct swm_geometry     gg = *g;
2813         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
2814         unsigned int            mask;
2815         int                     winno;
2816
2817         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
2818
2819         if (ws == NULL)
2820                 return;
2821
2822         winno = count_win(ws, 0);
2823         if (winno == 0 && count_win(ws, 1) == 0)
2824                 return;
2825
2826         TAILQ_FOREACH(win, &ws->winlist, entry) {
2827                 if (win->transient) {
2828                         wintrans = win;
2829                         parent = find_window(win->transient);
2830                         continue;
2831                 }
2832
2833                 if (win->floating && win->floatmaxed == 0 ) {
2834                         /*
2835                          * retain geometry for retrieval on exit from
2836                          * max_stack mode
2837                          */
2838                         store_float_geom(win, ws->r);
2839                         win->floatmaxed = 1;
2840                 }
2841
2842                 /* only reconfigure if necessary */
2843                 if (win->g.x != gg.x || win->g.y != gg.y || win->g.w != gg.w ||
2844                     win->g.h != gg.h) {
2845                         bzero(&wc, sizeof wc);
2846                         win->g.x = wc.x = gg.x;
2847                         win->g.y = wc.y = gg.y;
2848                         if (bar_enabled){
2849                                 wc.border_width = border_width;
2850                                 win->g.w = wc.width = gg.w;
2851                                 win->g.h = wc.height = gg.h;
2852                         } else {
2853                                 wc.border_width = 0;
2854                                 win->g.w = wc.width = gg.w + 2 * border_width;
2855                                 win->g.h = wc.height = gg.h + 2 * border_width;
2856                         }
2857                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2858                         XConfigureWindow(display, win->id, mask, &wc);
2859                 }
2860                 /* unmap only if we don't have multi screen */
2861                 if (win != ws->focus)
2862                         if (!(ScreenCount(display) > 1 || outputs > 1))
2863                                 unmap_window(win);
2864         }
2865
2866         /* put the last transient on top */
2867         if (wintrans) {
2868                 if (parent)
2869                         XMapRaised(display, parent->id);
2870                 stack_floater(wintrans, ws->r);
2871                 focus_magic(wintrans);
2872         }
2873 }
2874
2875 void
2876 send_to_ws(struct swm_region *r, union arg *args)
2877 {
2878         int                     wsid = args->id;
2879         struct ws_win           *win = NULL, *parent;
2880         struct workspace        *ws, *nws;
2881         Atom                    ws_idx_atom = 0;
2882         unsigned char           ws_idx_str[SWM_PROPLEN];
2883         union arg               a;
2884
2885         if (r && r->ws)
2886                 win = r->ws->focus;
2887         else
2888                 return;
2889         if (win == NULL)
2890                 return;
2891         if (win->ws->idx == wsid)
2892                 return;
2893
2894         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
2895
2896         ws = win->ws;
2897         nws = &win->s->ws[wsid];
2898
2899         a.id = SWM_ARG_ID_FOCUSPREV;
2900         focus(r, &a);
2901         if (win->transient) {
2902                 parent = find_window(win->transient);
2903                 if (parent) {
2904                         unmap_window(parent);
2905                         TAILQ_REMOVE(&ws->winlist, parent, entry);
2906                         TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
2907                         parent->ws = nws;
2908                 }
2909         }
2910         unmap_window(win);
2911         TAILQ_REMOVE(&ws->winlist, win, entry);
2912         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
2913         win->ws = nws;
2914
2915         /* Try to update the window's workspace property */
2916         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2917         if (ws_idx_atom &&
2918             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
2919                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2920                     ws_idx_str);
2921                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2922                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2923         }
2924
2925         stack();
2926 }
2927
2928 void
2929 iconify(struct swm_region *r, union arg *args)
2930 {
2931         union arg a;
2932
2933         if (r->ws->focus == NULL)
2934                 return;
2935         unmap_window(r->ws->focus);
2936         update_iconic(r->ws->focus, 1);
2937         stack();
2938         r->ws->focus = NULL;
2939         a.id = SWM_ARG_ID_FOCUSCUR;
2940         focus(r, &a);
2941 }
2942
2943 unsigned char *
2944 get_win_name(Display *dpy, Window win, Atom wname, Atom stype,
2945     unsigned long *slen)
2946 {
2947         int                     status, retfmt;
2948         unsigned long           nitems, nbytes, nextra;
2949         unsigned char           *prop = NULL;
2950         Atom                    rettype;
2951
2952         status = XGetWindowProperty(dpy, win, wname, 0L, 0L, False, stype,
2953             &rettype, &retfmt,  &nitems, &nbytes, &prop);
2954         if (status != Success)
2955                 return (NULL);
2956         XFree(prop);
2957
2958         status = XGetWindowProperty(dpy, win, wname, 0L, nbytes, False,
2959             stype, &rettype, &retfmt, &nitems, &nextra, &prop);
2960         if (status != Success) {
2961                 XFree(prop);
2962                 return (NULL);
2963         }
2964         if (rettype != stype) {
2965                 XFree(prop);
2966                 return (NULL);
2967         }
2968         *slen = nitems;
2969         return (prop);
2970 }
2971
2972 void
2973 uniconify(struct swm_region *r, union arg *args)
2974 {
2975         struct ws_win           *win;
2976         FILE                    *lfile;
2977         char                    *name;
2978         int                     count = 0;
2979         unsigned long           len;
2980
2981         DNPRINTF(SWM_D_MISC, "uniconify\n");
2982
2983         if (r && r->ws == NULL)
2984                 return;
2985
2986         /* make sure we have anything to uniconify */
2987         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
2988                 if (win->ws == NULL)
2989                         continue; /* should never happen */
2990                 if (win->iconic == 0)
2991                         continue;
2992                 count++;
2993         }
2994         if (count == 0)
2995                 return;
2996
2997         search_r = r;
2998
2999         spawn_select(r, args, "uniconify", &searchpid);
3000
3001         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3002                 return;
3003
3004         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3005                 if (win->ws == NULL)
3006                         continue; /* should never happen */
3007                 if (win->iconic == 0)
3008                         continue;
3009
3010                 name = get_win_name(display, win->id, a_wmname, a_string,
3011                     &len);
3012                 if (name == NULL)
3013                         continue;
3014                 fprintf(lfile, "%s.%lu\n", name, win->id);
3015                 XFree(name);
3016         }
3017
3018         fclose(lfile);
3019 }
3020
3021 #define MAX_RESP_LEN    1024
3022
3023 void
3024 search_do_resp(void)
3025 {
3026         ssize_t                 rbytes;
3027         struct ws_win           *win;
3028         char                    *name, *resp, *s;
3029         unsigned long           len;
3030
3031         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
3032
3033         search_resp = 0;
3034         searchpid = 0;
3035
3036         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
3037                 fprintf(stderr, "search: calloc\n");
3038                 return;
3039         }
3040
3041         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
3042         if (rbytes <= 0) {
3043                 fprintf(stderr, "search: read error: %s\n", strerror(errno));
3044                 goto done;
3045         }
3046         resp[rbytes] = '\0';
3047         len = strlen(resp);
3048
3049         DNPRINTF(SWM_D_MISC, "search_do_resp: resp %s\n", resp);
3050         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
3051                 if (win->iconic == 0)
3052                         continue;
3053                 name = get_win_name(display, win->id, a_wmname, a_string, &len);
3054                 if (name == NULL)
3055                         continue;
3056                 if (asprintf(&s, "%s.%lu", name, win->id) == -1) {
3057                         XFree(name);
3058                         continue;
3059                 }
3060                 XFree(name);
3061                 if (strncmp(s, resp, len) == 0) {
3062                         /* XXX this should be a callback to generalize */
3063                         update_iconic(win, 0);
3064                         free(s);
3065                         break;
3066                 }
3067                 free(s);
3068         }
3069 done:
3070         free(resp);
3071 }
3072
3073 void
3074 wkill(struct swm_region *r, union arg *args)
3075 {
3076         DNPRINTF(SWM_D_MISC, "wkill %d\n", args->id);
3077
3078         if (r->ws->focus == NULL)
3079                 return;
3080
3081         if (args->id == SWM_ARG_ID_KILLWINDOW)
3082                 XKillClient(display, r->ws->focus->id);
3083         else
3084                 if (r->ws->focus->can_delete)
3085                         client_msg(r->ws->focus, adelete);
3086 }
3087
3088
3089 int
3090 floating_toggle_win(struct ws_win *win)
3091 {
3092         struct swm_region       *r;
3093
3094         if (win == NULL)
3095                 return 0;
3096
3097         if (!win->ws->r)
3098                 return 0;
3099
3100         r = win->ws->r;
3101
3102         /* reject floating toggles in max stack mode */
3103         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
3104                 return 0;
3105
3106         if (win->floating) {
3107                 if (!win->floatmaxed) {
3108                         /* retain position for refloat */
3109                         store_float_geom(win, r);
3110                 }
3111                 win->floating = 0;
3112         } else {
3113                 if (win->g_floatvalid) {
3114                         /* refloat at last floating relative position */
3115                         win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
3116                         win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
3117                         win->g.w = win->g_float.w;
3118                         win->g.h = win->g_float.h;
3119                 }
3120                 win->floating = 1;
3121         }
3122
3123         ewmh_update_actions(win);
3124
3125         return 1;
3126 }
3127
3128 void
3129 floating_toggle(struct swm_region *r, union arg *args)
3130 {
3131         struct ws_win           *win = r->ws->focus;
3132         union arg               a;
3133
3134         if (win == NULL)
3135                 return;
3136
3137         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3138             _NET_WM_STATE_TOGGLE);
3139
3140         stack();
3141
3142         if (win == win->ws->focus) {
3143                 a.id = SWM_ARG_ID_FOCUSCUR;
3144                 focus(win->ws->r, &a);
3145         }
3146 }
3147
3148 void
3149 resize_window(struct ws_win *win, int center)
3150 {
3151         unsigned int            mask;
3152         XWindowChanges          wc;
3153         struct swm_region       *r;
3154
3155         r = root_to_region(win->wa.root);
3156         bzero(&wc, sizeof wc);
3157         mask = CWBorderWidth | CWWidth | CWHeight;
3158         wc.border_width = border_width;
3159         wc.width = win->g.w;
3160         wc.height = win->g.h;
3161         if (center == SWM_ARG_ID_CENTER) {
3162                 wc.x = (WIDTH(r) - win->g.w) / 2 - border_width;
3163                 wc.y = (HEIGHT(r) - win->g.h) / 2 - border_width;
3164                 mask |= CWX | CWY;
3165         }
3166
3167         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
3168             win->id, wc.x, wc.y, wc.width, wc.height);
3169
3170         XConfigureWindow(display, win->id, mask, &wc);
3171 }
3172
3173 void
3174 resize(struct ws_win *win, union arg *args)
3175 {
3176         XEvent                  ev;
3177         Time                    time = 0;
3178         struct swm_region       *r = win->ws->r;
3179         int                     relx, rely;
3180         union arg               a;
3181
3182
3183         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %lu\n",
3184             win->id, win->floating, win->transient);
3185
3186         if (!(win->transient != 0 || win->floating != 0))
3187                 return;
3188
3189         /* reject resizes in max mode for floaters (transient ok) */
3190         if (win->floatmaxed)
3191                 return;
3192
3193         win->manual = 1;
3194         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3195             _NET_WM_STATE_ADD);
3196         /* raise the window = move to last in window list */
3197         a.id = SWM_ARG_ID_MOVELAST;
3198         swapwin(r, &a);
3199         stack();
3200
3201         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3202             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3203                 return;
3204
3205         /* place pointer at bottom left corner or nearest point inside r */
3206         if ( win->g.x + win->g.w < r->g.x + r->g.w - 1)
3207                 relx = win->g.w - 1;
3208         else
3209                 relx = r->g.x + r->g.w - win->g.x - 1;
3210
3211         if ( win->g.y + win->g.h < r->g.y + r->g.h - 1)
3212                 rely = win->g.h - 1;
3213         else
3214                 rely = r->g.y + r->g.h - win->g.y - 1;
3215
3216         XWarpPointer(display, None, win->id, 0, 0, 0, 0, relx, rely);
3217         do {
3218                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3219                     SubstructureRedirectMask, &ev);
3220                 switch(ev.type) {
3221                 case ConfigureRequest:
3222                 case Expose:
3223                 case MapRequest:
3224                         handler[ev.type](&ev);
3225                         break;
3226                 case MotionNotify:
3227                         /* do not allow resize outside of region */
3228                         if (    ev.xmotion.x_root < r->g.x ||
3229                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3230                                 ev.xmotion.y_root < r->g.y ||
3231                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3232                                 continue;
3233
3234                         if (ev.xmotion.x <= 1)
3235                                 ev.xmotion.x = 1;
3236                         if (ev.xmotion.y <= 1)
3237                                 ev.xmotion.y = 1;
3238                         win->g.w = ev.xmotion.x + 1;
3239                         win->g.h = ev.xmotion.y + 1;
3240
3241                         /* not free, don't sync more than 120 times / second */
3242                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3243                                 time = ev.xmotion.time;
3244                                 XSync(display, False);
3245                                 resize_window(win, args->id);
3246                         }
3247                         break;
3248                 }
3249         } while (ev.type != ButtonRelease);
3250         if (time) {
3251                 XSync(display, False);
3252                 resize_window(win, args->id);
3253         }
3254         store_float_geom(win,r);
3255
3256         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
3257             win->g.h - 1);
3258         XUngrabPointer(display, CurrentTime);
3259
3260         /* drain events */
3261         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
3262 }
3263
3264 void
3265 move_window(struct ws_win *win)
3266 {
3267         unsigned int            mask;
3268         XWindowChanges          wc;
3269         struct swm_region       *r;
3270
3271         r = root_to_region(win->wa.root);
3272         bzero(&wc, sizeof wc);
3273         mask = CWX | CWY;
3274         wc.x = win->g.x;
3275         wc.y = win->g.y;
3276         wc.border_width = border_width;
3277
3278         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
3279             win->id, wc.x, wc.y, wc.width, wc.height);
3280
3281         XConfigureWindow(display, win->id, mask, &wc);
3282 }
3283
3284 void
3285 move(struct ws_win *win, union arg *args)
3286 {
3287         XEvent                  ev;
3288         Time                    time = 0;
3289         struct swm_region       *r = win->ws->r;
3290         union arg               a;
3291
3292         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %lu\n",
3293             win->id, win->floating, win->transient);
3294
3295         /* in max_stack mode should only move transients */
3296         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
3297                 return;
3298
3299         win->manual = 1;
3300         if (win->floating == 0 && !win->transient) {
3301                 win->floating = 1;
3302                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3303                     _NET_WM_STATE_ADD);
3304         }
3305         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3306             _NET_WM_STATE_ADD);
3307
3308         /* raise the window = move to last in window list */
3309         a.id = SWM_ARG_ID_MOVELAST;
3310         swapwin(r, &a);
3311         stack();
3312
3313         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3314             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3315                 return;
3316         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3317         do {
3318                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3319                     SubstructureRedirectMask, &ev);
3320                 switch(ev.type) {
3321                 case ConfigureRequest:
3322                 case Expose:
3323                 case MapRequest:
3324                         handler[ev.type](&ev);
3325                         break;
3326                 case MotionNotify:
3327                         /* don't allow to move window origin out of region */
3328                         if (    ev.xmotion.x_root < r->g.x ||
3329                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3330                                 ev.xmotion.y_root < r->g.y ||
3331                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3332                                 continue;
3333
3334                         win->g.x = ev.xmotion.x_root - border_width;
3335                         win->g.y = ev.xmotion.y_root - border_width;
3336
3337                         /* not free, don't sync more than 120 times / second */
3338                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3339                                 time = ev.xmotion.time;
3340                                 XSync(display, False);
3341                                 move_window(win);
3342                         }
3343                         break;
3344                 }
3345         } while (ev.type != ButtonRelease);
3346         if (time) {
3347                 XSync(display, False);
3348                 move_window(win);
3349         }
3350         store_float_geom(win,r);
3351         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3352         XUngrabPointer(display, CurrentTime);
3353
3354         /* drain events */
3355         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
3356 }
3357
3358 /* user/key callable function IDs */
3359 enum keyfuncid {
3360         kf_cycle_layout,
3361         kf_stack_reset,
3362         kf_master_shrink,
3363         kf_master_grow,
3364         kf_master_add,
3365         kf_master_del,
3366         kf_stack_inc,
3367         kf_stack_dec,
3368         kf_swap_main,
3369         kf_focus_next,
3370         kf_focus_prev,
3371         kf_swap_next,
3372         kf_swap_prev,
3373         kf_spawn_term,
3374         kf_spawn_menu,
3375         kf_quit,
3376         kf_restart,
3377         kf_focus_main,
3378         kf_ws_1,
3379         kf_ws_2,
3380         kf_ws_3,
3381         kf_ws_4,
3382         kf_ws_5,
3383         kf_ws_6,
3384         kf_ws_7,
3385         kf_ws_8,
3386         kf_ws_9,
3387         kf_ws_10,
3388         kf_ws_next,
3389         kf_ws_prev,
3390         kf_ws_prior,
3391         kf_screen_next,
3392         kf_screen_prev,
3393         kf_mvws_1,
3394         kf_mvws_2,
3395         kf_mvws_3,
3396         kf_mvws_4,
3397         kf_mvws_5,
3398         kf_mvws_6,
3399         kf_mvws_7,
3400         kf_mvws_8,
3401         kf_mvws_9,
3402         kf_mvws_10,
3403         kf_bar_toggle,
3404         kf_wind_kill,
3405         kf_wind_del,
3406         kf_screenshot_all,
3407         kf_screenshot_wind,
3408         kf_float_toggle,
3409         kf_version,
3410         kf_spawn_lock,
3411         kf_spawn_initscr,
3412         kf_spawn_custom,
3413         kf_iconify,
3414         kf_uniconify,
3415         kf_dumpwins, /* MUST BE LAST */
3416         kf_invalid
3417 };
3418
3419 /* key definitions */
3420 void
3421 dummykeyfunc(struct swm_region *r, union arg *args)
3422 {
3423 };
3424
3425 void
3426 legacyfunc(struct swm_region *r, union arg *args)
3427 {
3428 };
3429
3430 struct keyfunc {
3431         char                    name[SWM_FUNCNAME_LEN];
3432         void                    (*func)(struct swm_region *r, union arg *);
3433         union arg               args;
3434 } keyfuncs[kf_invalid + 1] = {
3435         /* name                 function        argument */
3436         { "cycle_layout",       cycle_layout,   {0} },
3437         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
3438         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
3439         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
3440         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
3441         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
3442         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
3443         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
3444         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
3445         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
3446         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
3447         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
3448         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
3449         { "spawn_term",         spawnterm,      {.argv = spawn_term} },
3450         { "spawn_menu",         legacyfunc,     {0} },
3451         { "quit",               quit,           {0} },
3452         { "restart",            restart,        {0} },
3453         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
3454         { "ws_1",               switchws,       {.id = 0} },
3455         { "ws_2",               switchws,       {.id = 1} },
3456         { "ws_3",               switchws,       {.id = 2} },
3457         { "ws_4",               switchws,       {.id = 3} },
3458         { "ws_5",               switchws,       {.id = 4} },
3459         { "ws_6",               switchws,       {.id = 5} },
3460         { "ws_7",               switchws,       {.id = 6} },
3461         { "ws_8",               switchws,       {.id = 7} },
3462         { "ws_9",               switchws,       {.id = 8} },
3463         { "ws_10",              switchws,       {.id = 9} },
3464         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
3465         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
3466         { "ws_prior",           priorws,        {0} },
3467         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
3468         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
3469         { "mvws_1",             send_to_ws,     {.id = 0} },
3470         { "mvws_2",             send_to_ws,     {.id = 1} },
3471         { "mvws_3",             send_to_ws,     {.id = 2} },
3472         { "mvws_4",             send_to_ws,     {.id = 3} },
3473         { "mvws_5",             send_to_ws,     {.id = 4} },
3474         { "mvws_6",             send_to_ws,     {.id = 5} },
3475         { "mvws_7",             send_to_ws,     {.id = 6} },
3476         { "mvws_8",             send_to_ws,     {.id = 7} },
3477         { "mvws_9",             send_to_ws,     {.id = 8} },
3478         { "mvws_10",            send_to_ws,     {.id = 9} },
3479         { "bar_toggle",         bar_toggle,     {0} },
3480         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
3481         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
3482         { "screenshot_all",     legacyfunc,     {0} },
3483         { "screenshot_wind",    legacyfunc,     {0} },
3484         { "float_toggle",       floating_toggle,{0} },
3485         { "version",            version,        {0} },
3486         { "spawn_lock",         legacyfunc,     {0} },
3487         { "spawn_initscr",      legacyfunc,     {0} },
3488         { "spawn_custom",       dummykeyfunc,   {0} },
3489         { "iconify",            iconify,        {0} },
3490         { "uniconify",          uniconify,      {0} },
3491         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
3492         { "invalid key func",   NULL,           {0} },
3493 };
3494 struct key {
3495         unsigned int            mod;
3496         KeySym                  keysym;
3497         enum keyfuncid          funcid;
3498         char                    *spawn_name;
3499 };
3500 int                             keys_size = 0, keys_length = 0;
3501 struct key                      *keys = NULL;
3502
3503 /* mouse */
3504 enum { client_click, root_click };
3505 struct button {
3506         unsigned int            action;
3507         unsigned int            mask;
3508         unsigned int            button;
3509         void                    (*func)(struct ws_win *, union arg *);
3510         union arg               args;
3511 } buttons[] = {
3512           /* action     key             mouse button    func    args */
3513         { client_click, MODKEY,         Button3,        resize, {.id = SWM_ARG_ID_DONTCENTER} },
3514         { client_click, MODKEY | ShiftMask, Button3,    resize, {.id = SWM_ARG_ID_CENTER} },
3515         { client_click, MODKEY,         Button1,        move,   {0} },
3516 };
3517
3518 void
3519 update_modkey(unsigned int mod)
3520 {
3521         int                     i;
3522
3523         mod_key = mod;
3524         for (i = 0; i < keys_length; i++)
3525                 if (keys[i].mod & ShiftMask)
3526                         keys[i].mod = mod | ShiftMask;
3527                 else
3528                         keys[i].mod = mod;
3529
3530         for (i = 0; i < LENGTH(buttons); i++)
3531                 if (buttons[i].mask & ShiftMask)
3532                         buttons[i].mask = mod | ShiftMask;
3533                 else
3534                         buttons[i].mask = mod;
3535 }
3536
3537 /* spawn */
3538 struct spawn_prog {
3539         char                    *name;
3540         int                     argc;
3541         char                    **argv;
3542 };
3543
3544 int                             spawns_size = 0, spawns_length = 0;
3545 struct spawn_prog               *spawns = NULL;
3546
3547 int
3548 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
3549     char ***ret_args)
3550 {
3551         struct spawn_prog       *prog = NULL;
3552         int                     i;
3553         char                    *ap, **real_args;
3554
3555         DNPRINTF(SWM_D_SPAWN, "spawn_expand %s\n", spawn_name);
3556
3557         /* find program */
3558         for (i = 0; i < spawns_length; i++) {
3559                 if (!strcasecmp(spawn_name, spawns[i].name))
3560                         prog = &spawns[i];
3561         }
3562         if (prog == NULL) {
3563                 fprintf(stderr, "spawn_custom: program %s not found\n",
3564                     spawn_name);
3565                 return (-1);
3566         }
3567
3568         /* make room for expanded args */
3569         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
3570                 err(1, "spawn_custom: calloc real_args");
3571
3572         /* expand spawn_args into real_args */
3573         for (i = 0; i < prog->argc; i++) {
3574                 ap = prog->argv[i];
3575                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg = %s\n", ap);
3576                 if (!strcasecmp(ap, "$bar_border")) {
3577                         if ((real_args[i] =
3578                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
3579                             == NULL)
3580                                 err(1,  "spawn_custom border color");
3581                 } else if (!strcasecmp(ap, "$bar_color")) {
3582                         if ((real_args[i] =
3583                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
3584                             == NULL)
3585                                 err(1, "spawn_custom bar color");
3586                 } else if (!strcasecmp(ap, "$bar_font")) {
3587                         if ((real_args[i] = strdup(bar_fonts[bar_fidx]))
3588                             == NULL)
3589                                 err(1, "spawn_custom bar fonts");
3590                 } else if (!strcasecmp(ap, "$bar_font_color")) {
3591                         if ((real_args[i] =
3592                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
3593                             == NULL)
3594                                 err(1, "spawn_custom color font");
3595                 } else if (!strcasecmp(ap, "$color_focus")) {
3596                         if ((real_args[i] =
3597                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
3598                             == NULL)
3599                                 err(1, "spawn_custom color focus");
3600                 } else if (!strcasecmp(ap, "$color_unfocus")) {
3601                         if ((real_args[i] =
3602                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
3603                             == NULL)
3604                                 err(1, "spawn_custom color unfocus");
3605                 } else {
3606                         /* no match --> copy as is */
3607                         if ((real_args[i] = strdup(ap)) == NULL)
3608                                 err(1, "spawn_custom strdup(ap)");
3609                 }
3610                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg = %s\n",
3611                     real_args[i]);
3612         }
3613
3614 #ifdef SWM_DEBUG
3615         if ((swm_debug & SWM_D_SPAWN) != 0) {
3616                 fprintf(stderr, "spawn_custom: result = ");
3617                 for (i = 0; i < prog->argc; i++)
3618                         fprintf(stderr, "\"%s\" ", real_args[i]);
3619                 fprintf(stderr, "\n");
3620         }
3621 #endif
3622         *ret_args = real_args;
3623         return (prog->argc);
3624 }
3625
3626 void
3627 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
3628 {
3629         union arg               a;
3630         char                    **real_args;
3631         int                     spawn_argc, i;
3632
3633         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3634                 return;
3635         a.argv = real_args;
3636         if (fork() == 0)
3637                 spawn(r, &a, 1);
3638
3639         for (i = 0; i < spawn_argc; i++)
3640                 free(real_args[i]);
3641         free(real_args);
3642 }
3643
3644 void
3645 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
3646 {
3647         union arg               a;
3648         char                    **real_args;
3649         int                     i, spawn_argc;
3650
3651         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3652                 return;
3653         a.argv = real_args;
3654
3655         if (pipe(select_list_pipe) == -1)
3656                 err(1, "pipe error");
3657         if (pipe(select_resp_pipe) == -1)
3658                 err(1, "pipe error");
3659
3660         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3661                 err(1, "could not disable SIGPIPE");
3662         switch (*pid = fork()) {
3663         case -1:
3664                 err(1, "cannot fork");
3665                 break;
3666         case 0: /* child */
3667                 if (dup2(select_list_pipe[0], 0) == -1)
3668                         errx(1, "dup2");
3669                 if (dup2(select_resp_pipe[1], 1) == -1)
3670                         errx(1, "dup2");
3671                 close(select_list_pipe[1]);
3672                 close(select_resp_pipe[0]);
3673                 spawn(r, &a, 0);
3674                 break;
3675         default: /* parent */
3676                 close(select_list_pipe[0]);
3677                 close(select_resp_pipe[1]);
3678                 break;
3679         }
3680
3681         for (i = 0; i < spawn_argc; i++)
3682                 free(real_args[i]);
3683         free(real_args);
3684 }
3685
3686 void
3687 setspawn(struct spawn_prog *prog)
3688 {
3689         int                     i, j;
3690
3691         if (prog == NULL || prog->name == NULL)
3692                 return;
3693
3694         /* find existing */
3695         for (i = 0; i < spawns_length; i++) {
3696                 if (!strcmp(spawns[i].name, prog->name)) {
3697                         /* found */
3698                         if (prog->argv == NULL) {
3699                                 /* delete */
3700                                 DNPRINTF(SWM_D_SPAWN,
3701                                     "setspawn: delete #%d %s\n",
3702                                     i, spawns[i].name);
3703                                 free(spawns[i].name);
3704                                 for (j = 0; j < spawns[i].argc; j++)
3705                                         free(spawns[i].argv[j]);
3706                                 free(spawns[i].argv);
3707                                 j = spawns_length - 1;
3708                                 if (i < j)
3709                                         spawns[i] = spawns[j];
3710                                 spawns_length--;
3711                                 free(prog->name);
3712                         } else {
3713                                 /* replace */
3714                                 DNPRINTF(SWM_D_SPAWN,
3715                                     "setspawn: replace #%d %s\n",
3716                                     i, spawns[i].name);
3717                                 free(spawns[i].name);
3718                                 for (j = 0; j < spawns[i].argc; j++)
3719                                         free(spawns[i].argv[j]);
3720                                 free(spawns[i].argv);
3721                                 spawns[i] = *prog;
3722                         }
3723                         /* found case handled */
3724                         free(prog);
3725                         return;
3726                 }
3727         }
3728
3729         if (prog->argv == NULL) {
3730                 fprintf(stderr,
3731                     "error: setspawn: cannot find program %s", prog->name);
3732                 free(prog);
3733                 return;
3734         }
3735
3736         /* not found: add */
3737         if (spawns_size == 0 || spawns == NULL) {
3738                 spawns_size = 4;
3739                 DNPRINTF(SWM_D_SPAWN, "setspawn: init list %d\n", spawns_size);
3740                 spawns = malloc((size_t)spawns_size *
3741                     sizeof(struct spawn_prog));
3742                 if (spawns == NULL) {
3743                         fprintf(stderr, "setspawn: malloc failed\n");
3744                         perror(" failed");
3745                         quit(NULL, NULL);
3746                 }
3747         } else if (spawns_length == spawns_size) {
3748                 spawns_size *= 2;
3749                 DNPRINTF(SWM_D_SPAWN, "setspawn: grow list %d\n", spawns_size);
3750                 spawns = realloc(spawns, (size_t)spawns_size *
3751                     sizeof(struct spawn_prog));
3752                 if (spawns == NULL) {
3753                         fprintf(stderr, "setspawn: realloc failed\n");
3754                         perror(" failed");
3755                         quit(NULL, NULL);
3756                 }
3757         }
3758
3759         if (spawns_length < spawns_size) {
3760                 DNPRINTF(SWM_D_SPAWN, "setspawn: add #%d %s\n",
3761                     spawns_length, prog->name);
3762                 i = spawns_length++;
3763                 spawns[i] = *prog;
3764         } else {
3765                 fprintf(stderr, "spawns array problem?\n");
3766                 if (spawns == NULL) {
3767                         fprintf(stderr, "spawns array is NULL!\n");
3768                         quit(NULL, NULL);
3769                 }
3770         }
3771         free(prog);
3772 }
3773
3774 int
3775 setconfspawn(char *selector, char *value, int flags)
3776 {
3777         struct spawn_prog       *prog;
3778         char                    *vp, *cp, *word;
3779
3780         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
3781         if ((prog = calloc(1, sizeof *prog)) == NULL)
3782                 err(1, "setconfspawn: calloc prog");
3783         prog->name = strdup(selector);
3784         if (prog->name == NULL)
3785                 err(1, "setconfspawn prog->name");
3786         if ((cp = vp = strdup(value)) == NULL)
3787                 err(1, "setconfspawn: strdup(value) ");
3788         while ((word = strsep(&cp, " \t")) != NULL) {
3789                 DNPRINTF(SWM_D_SPAWN, "setconfspawn: arg [%s]\n", word);
3790                 if (cp)
3791                         cp += (long)strspn(cp, " \t");
3792                 if (strlen(word) > 0) {
3793                         prog->argc++;
3794                         prog->argv = realloc(prog->argv,
3795                             prog->argc * sizeof(char *));
3796                         if ((prog->argv[prog->argc - 1] = strdup(word)) == NULL)
3797                                 err(1, "setconfspawn: strdup");
3798                 }
3799         }
3800         free(vp);
3801
3802         setspawn(prog);
3803
3804         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
3805         return (0);
3806 }
3807
3808 void
3809 setup_spawn(void)
3810 {
3811         setconfspawn("term",            "xterm",                0);
3812         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
3813         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
3814         setconfspawn("lock",            "xlock",                0);
3815         setconfspawn("initscr",         "initscreen.sh",        0);
3816         setconfspawn("menu",            "dmenu_run"
3817                                         " -fn $bar_font"
3818                                         " -nb $bar_color"
3819                                         " -nf $bar_font_color"
3820                                         " -sb $bar_border"
3821                                         " -sf $bar_color",      0);
3822         setconfspawn("uniconify",       "dmenu"
3823                                         " -i"
3824                                         " -fn $bar_font"
3825                                         " -nb $bar_color"
3826                                         " -nf $bar_font_color"
3827                                         " -sb $bar_border"
3828                                         " -sf $bar_color",      0);
3829 }
3830
3831 /* key bindings */
3832 #define SWM_MODNAME_SIZE        32
3833 #define SWM_KEY_WS              "\n+ \t"
3834 int
3835 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
3836 {
3837         char                    *cp, *name;
3838         KeySym                  uks;
3839         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
3840         if (mod == NULL || ks == NULL) {
3841                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
3842                 return (1);
3843         }
3844         if (keystr == NULL || strlen(keystr) == 0) {
3845                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
3846                 return (1);
3847         }
3848         cp = keystr;
3849         *ks = NoSymbol;
3850         *mod = 0;
3851         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
3852                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
3853                 if (cp)
3854                         cp += (long)strspn(cp, SWM_KEY_WS);
3855                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
3856                         *mod |= currmod;
3857                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
3858                         *mod |= Mod1Mask;
3859                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
3860                         *mod += Mod2Mask;
3861                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
3862                         *mod |= Mod3Mask;
3863                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
3864                         *mod |= Mod4Mask;
3865                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
3866                         *mod |= ShiftMask;
3867                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
3868                         *mod |= ControlMask;
3869                 else {
3870                         *ks = XStringToKeysym(name);
3871                         XConvertCase(*ks, ks, &uks);
3872                         if (ks == NoSymbol) {
3873                                 DNPRINTF(SWM_D_KEY,
3874                                     "parsekeys: invalid key %s\n",
3875                                     name);
3876                                 return (1);
3877                         }
3878                 }
3879         }
3880         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
3881         return (0);
3882 }
3883
3884 char *
3885 strdupsafe(char *str)
3886 {
3887         if (str == NULL)
3888                 return (NULL);
3889         else
3890                 return (strdup(str));
3891 }
3892
3893 void
3894 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid, char *spawn_name)
3895 {
3896         int                     i, j;
3897         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
3898             keyfuncs[kfid].name, spawn_name);
3899         /* find existing */
3900         for (i = 0; i < keys_length; i++) {
3901                 if (keys[i].mod == mod && keys[i].keysym == ks) {
3902                         if (kfid == kf_invalid) {
3903                                 /* found: delete */
3904                                 DNPRINTF(SWM_D_KEY,
3905                                     "setkeybinding: delete #%d %s\n",
3906                                     i, keyfuncs[keys[i].funcid].name);
3907                                 free(keys[i].spawn_name);
3908                                 j = keys_length - 1;
3909                                 if (i < j)
3910                                         keys[i] = keys[j];
3911                                 keys_length--;
3912                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3913                                 return;
3914                         } else {
3915                                 /* found: replace */
3916                                 DNPRINTF(SWM_D_KEY,
3917                                     "setkeybinding: replace #%d %s %s\n",
3918                                     i, keyfuncs[keys[i].funcid].name,
3919                                     spawn_name);
3920                                 free(keys[i].spawn_name);
3921                                 keys[i].mod = mod;
3922                                 keys[i].keysym = ks;
3923                                 keys[i].funcid = kfid;
3924                                 keys[i].spawn_name = strdupsafe(spawn_name);
3925                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3926                                 return;
3927                         }
3928                 }
3929         }
3930         if (kfid == kf_invalid) {
3931                 fprintf(stderr,
3932                     "error: setkeybinding: cannot find mod/key combination");
3933                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3934                 return;
3935         }
3936         /* not found: add */
3937         if (keys_size == 0 || keys == NULL) {
3938                 keys_size = 4;
3939                 DNPRINTF(SWM_D_KEY, "setkeybinding: init list %d\n", keys_size);
3940                 keys = malloc((size_t)keys_size * sizeof(struct key));
3941                 if (!keys) {
3942                         fprintf(stderr, "malloc failed\n");
3943                         perror(" failed");
3944                         quit(NULL, NULL);
3945                 }
3946         } else if (keys_length == keys_size) {
3947                 keys_size *= 2;
3948                 DNPRINTF(SWM_D_KEY, "setkeybinding: grow list %d\n", keys_size);
3949                 keys = realloc(keys, (size_t)keys_size * sizeof(struct key));
3950                 if (!keys) {
3951                         fprintf(stderr, "realloc failed\n");
3952                         perror(" failed");
3953                         quit(NULL, NULL);
3954                 }
3955         }
3956         if (keys_length < keys_size) {
3957                 j = keys_length++;
3958                 DNPRINTF(SWM_D_KEY, "setkeybinding: add #%d %s %s\n",
3959                     j, keyfuncs[kfid].name, spawn_name);
3960                 keys[j].mod = mod;
3961                 keys[j].keysym = ks;
3962                 keys[j].funcid = kfid;
3963                 keys[j].spawn_name = strdupsafe(spawn_name);
3964         } else {
3965                 fprintf(stderr, "keys array problem?\n");
3966                 if (!keys) {
3967                         fprintf(stderr, "keys array problem\n");
3968                         quit(NULL, NULL);
3969                 }
3970         }
3971         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3972 }
3973
3974 int
3975 setconfbinding(char *selector, char *value, int flags)
3976 {
3977         enum keyfuncid          kfid;
3978         unsigned int            mod;
3979         KeySym                  ks;
3980         int                     i;
3981         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
3982         if (selector == NULL) {
3983                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
3984                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
3985                         kfid = kf_invalid;
3986                         setkeybinding(mod, ks, kfid, NULL);
3987                         return (0);
3988                 } else
3989                         return (1);
3990         }
3991         /* search by key function name */
3992         for (kfid = 0; kfid < kf_invalid; (kfid)++) {
3993                 if (strncasecmp(selector, keyfuncs[kfid].name,
3994                     SWM_FUNCNAME_LEN) == 0) {
3995                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
3996                             selector);
3997                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
3998                                 setkeybinding(mod, ks, kfid, NULL);
3999                                 return (0);
4000                         } else
4001                                 return (1);
4002                 }
4003         }
4004         /* search by custom spawn name */
4005         for (i = 0; i < spawns_length; i++) {
4006                 if (strcasecmp(selector, spawns[i].name) == 0) {
4007                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4008                             selector);
4009                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4010                                 setkeybinding(mod, ks, kf_spawn_custom,
4011                                     spawns[i].name);
4012                                 return (0);
4013                         } else
4014                                 return (1);
4015                 }
4016         }
4017         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
4018         return (1);
4019 }
4020
4021 void
4022 setup_keys(void)
4023 {
4024         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout,NULL);
4025         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset, NULL);
4026         setkeybinding(MODKEY,           XK_h,           kf_master_shrink,NULL);
4027         setkeybinding(MODKEY,           XK_l,           kf_master_grow, NULL);
4028         setkeybinding(MODKEY,           XK_comma,       kf_master_add,  NULL);
4029         setkeybinding(MODKEY,           XK_period,      kf_master_del,  NULL);
4030         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc,   NULL);
4031         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec,   NULL);
4032         setkeybinding(MODKEY,           XK_Return,      kf_swap_main,   NULL);
4033         setkeybinding(MODKEY,           XK_j,           kf_focus_next,  NULL);
4034         setkeybinding(MODKEY,           XK_k,           kf_focus_prev,  NULL);
4035         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next,   NULL);
4036         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev,   NULL);
4037         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_term,  NULL);
4038         setkeybinding(MODKEY,           XK_p,           kf_spawn_custom,        "menu");
4039         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit,        NULL);
4040         setkeybinding(MODKEY,           XK_q,           kf_restart,     NULL);
4041         setkeybinding(MODKEY,           XK_m,           kf_focus_main,  NULL);
4042         setkeybinding(MODKEY,           XK_1,           kf_ws_1,        NULL);
4043         setkeybinding(MODKEY,           XK_2,           kf_ws_2,        NULL);
4044         setkeybinding(MODKEY,           XK_3,           kf_ws_3,        NULL);
4045         setkeybinding(MODKEY,           XK_4,           kf_ws_4,        NULL);
4046         setkeybinding(MODKEY,           XK_5,           kf_ws_5,        NULL);
4047         setkeybinding(MODKEY,           XK_6,           kf_ws_6,        NULL);
4048         setkeybinding(MODKEY,           XK_7,           kf_ws_7,        NULL);
4049         setkeybinding(MODKEY,           XK_8,           kf_ws_8,        NULL);
4050         setkeybinding(MODKEY,           XK_9,           kf_ws_9,        NULL);
4051         setkeybinding(MODKEY,           XK_0,           kf_ws_10,       NULL);
4052         setkeybinding(MODKEY,           XK_Right,       kf_ws_next,     NULL);
4053         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev,     NULL);
4054         setkeybinding(MODKEY,           XK_a,           kf_ws_prior,    NULL);
4055         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next, NULL);
4056         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev, NULL);
4057         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1,      NULL);
4058         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2,      NULL);
4059         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3,      NULL);
4060         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4,      NULL);
4061         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5,      NULL);
4062         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6,      NULL);
4063         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7,      NULL);
4064         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8,      NULL);
4065         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9,      NULL);
4066         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10,     NULL);
4067         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle,  NULL);
4068         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next,  NULL);
4069         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev,  NULL);
4070         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill,   NULL);
4071         setkeybinding(MODKEY,           XK_x,           kf_wind_del,    NULL);
4072         setkeybinding(MODKEY,           XK_s,           kf_spawn_custom,        "screenshot_all");
4073         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_spawn_custom,        "screenshot_wind");
4074         setkeybinding(MODKEY,           XK_t,           kf_float_toggle,NULL);
4075         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version,     NULL);
4076         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_custom,        "lock");
4077         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_custom,        "initscr");
4078         setkeybinding(MODKEY,           XK_w,           kf_iconify,     NULL);
4079         setkeybinding(MODKEY|ShiftMask, XK_w,           kf_uniconify,   NULL);
4080 #ifdef SWM_DEBUG
4081         setkeybinding(MODKEY|ShiftMask, XK_d,           kf_dumpwins,    NULL);
4082 #endif
4083 }
4084
4085 void
4086 updatenumlockmask(void)
4087 {
4088         unsigned int            i, j;
4089         XModifierKeymap         *modmap;
4090
4091         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
4092         numlockmask = 0;
4093         modmap = XGetModifierMapping(display);
4094         for (i = 0; i < 8; i++)
4095                 for (j = 0; j < modmap->max_keypermod; j++)
4096                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
4097                           == XKeysymToKeycode(display, XK_Num_Lock))
4098                                 numlockmask = (1 << i);
4099
4100         XFreeModifiermap(modmap);
4101 }
4102
4103 void
4104 grabkeys(void)
4105 {
4106         unsigned int            i, j, k;
4107         KeyCode                 code;
4108         unsigned int            modifiers[] =
4109             { 0, LockMask, numlockmask, numlockmask | LockMask };
4110
4111         DNPRINTF(SWM_D_MISC, "grabkeys\n");
4112         updatenumlockmask();
4113
4114         for (k = 0; k < ScreenCount(display); k++) {
4115                 if (TAILQ_EMPTY(&screens[k].rl))
4116                         continue;
4117                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
4118                 for (i = 0; i < keys_length; i++) {
4119                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
4120                                 for (j = 0; j < LENGTH(modifiers); j++)
4121                                         XGrabKey(display, code,
4122                                             keys[i].mod | modifiers[j],
4123                                             screens[k].root, True,
4124                                             GrabModeAsync, GrabModeAsync);
4125                 }
4126         }
4127 }
4128
4129 void
4130 grabbuttons(struct ws_win *win, int focused)
4131 {
4132         unsigned int            i, j;
4133         unsigned int            modifiers[] =
4134             { 0, LockMask, numlockmask, numlockmask|LockMask };
4135
4136         updatenumlockmask();
4137         XUngrabButton(display, AnyButton, AnyModifier, win->id);
4138         if (focused) {
4139                 for (i = 0; i < LENGTH(buttons); i++)
4140                         if (buttons[i].action == client_click)
4141                                 for (j = 0; j < LENGTH(modifiers); j++)
4142                                         XGrabButton(display, buttons[i].button,
4143                                             buttons[i].mask | modifiers[j],
4144                                             win->id, False, BUTTONMASK,
4145                                             GrabModeAsync, GrabModeSync, None,
4146                                             None);
4147         } else
4148                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
4149                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
4150 }
4151
4152 const char *quirkname[] = {
4153         "NONE",         /* config string for "no value" */
4154         "FLOAT",
4155         "TRANSSZ",
4156         "ANYWHERE",
4157         "XTERM_FONTADJ",
4158         "FULLSCREEN",
4159 };
4160
4161 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
4162 #define SWM_Q_WS                "\n|+ \t"
4163 int
4164 parsequirks(char *qstr, unsigned long *quirk)
4165 {
4166         char                    *cp, *name;
4167         int                     i;
4168
4169         if (quirk == NULL)
4170                 return (1);
4171
4172         cp = qstr;
4173         *quirk = 0;
4174         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
4175                 if (cp)
4176                         cp += (long)strspn(cp, SWM_Q_WS);
4177                 for (i = 0; i < LENGTH(quirkname); i++) {
4178                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
4179                                 DNPRINTF(SWM_D_QUIRK, "parsequirks: %s\n", name);
4180                                 if (i == 0) {
4181                                         *quirk = 0;
4182                                         return (0);
4183                                 }
4184                                 *quirk |= 1 << (i-1);
4185                                 break;
4186                         }
4187                 }
4188                 if (i >= LENGTH(quirkname)) {
4189                         DNPRINTF(SWM_D_QUIRK,
4190                             "parsequirks: invalid quirk [%s]\n", name);
4191                         return (1);
4192                 }
4193         }
4194         return (0);
4195 }
4196
4197 void
4198 setquirk(const char *class, const char *name, const int quirk)
4199 {
4200         int                     i, j;
4201
4202         /* find existing */
4203         for (i = 0; i < quirks_length; i++) {
4204                 if (!strcmp(quirks[i].class, class) &&
4205                     !strcmp(quirks[i].name, name)) {
4206                         if (!quirk) {
4207                                 /* found: delete */
4208                                 DNPRINTF(SWM_D_QUIRK,
4209                                     "setquirk: delete #%d %s:%s\n",
4210                                     i, quirks[i].class, quirks[i].name);
4211                                 free(quirks[i].class);
4212                                 free(quirks[i].name);
4213                                 j = quirks_length - 1;
4214                                 if (i < j)
4215                                         quirks[i] = quirks[j];
4216                                 quirks_length--;
4217                                 return;
4218                         } else {
4219                                 /* found: replace */
4220                                 DNPRINTF(SWM_D_QUIRK,
4221                                     "setquirk: replace #%d %s:%s\n",
4222                                     i, quirks[i].class, quirks[i].name);
4223                                 free(quirks[i].class);
4224                                 free(quirks[i].name);
4225                                 quirks[i].class = strdup(class);
4226                                 quirks[i].name = strdup(name);
4227                                 quirks[i].quirk = quirk;
4228                                 return;
4229                         }
4230                 }
4231         }
4232         if (!quirk) {
4233                 fprintf(stderr,
4234                     "error: setquirk: cannot find class/name combination");
4235                 return;
4236         }
4237         /* not found: add */
4238         if (quirks_size == 0 || quirks == NULL) {
4239                 quirks_size = 4;
4240                 DNPRINTF(SWM_D_QUIRK, "setquirk: init list %d\n", quirks_size);
4241                 quirks = malloc((size_t)quirks_size * sizeof(struct quirk));
4242                 if (!quirks) {
4243                         fprintf(stderr, "setquirk: malloc failed\n");
4244                         perror(" failed");
4245                         quit(NULL, NULL);
4246                 }
4247         } else if (quirks_length == quirks_size) {
4248                 quirks_size *= 2;
4249                 DNPRINTF(SWM_D_QUIRK, "setquirk: grow list %d\n", quirks_size);
4250                 quirks = realloc(quirks, (size_t)quirks_size * sizeof(struct quirk));
4251                 if (!quirks) {
4252                         fprintf(stderr, "setquirk: realloc failed\n");
4253                         perror(" failed");
4254                         quit(NULL, NULL);
4255                 }
4256         }
4257         if (quirks_length < quirks_size) {
4258                 DNPRINTF(SWM_D_QUIRK, "setquirk: add %d\n", quirks_length);
4259                 j = quirks_length++;
4260                 quirks[j].class = strdup(class);
4261                 quirks[j].name = strdup(name);
4262                 quirks[j].quirk = quirk;
4263         } else {
4264                 fprintf(stderr, "quirks array problem?\n");
4265                 if (!quirks) {
4266                         fprintf(stderr, "quirks array problem!\n");
4267                         quit(NULL, NULL);
4268                 }
4269         }
4270 }
4271
4272 int
4273 setconfquirk(char *selector, char *value, int flags)
4274 {
4275         char                    *cp, *class, *name;
4276         int                     retval;
4277         unsigned long           quirks;
4278         if (selector == NULL)
4279                 return (0);
4280         if ((cp = strchr(selector, ':')) == NULL)
4281                 return (0);
4282         *cp = '\0';
4283         class = selector;
4284         name = cp + 1;
4285         if ((retval = parsequirks(value, &quirks)) == 0)
4286                 setquirk(class, name, quirks);
4287         return (retval);
4288 }
4289
4290 void
4291 setup_quirks(void)
4292 {
4293         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
4294         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
4295         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
4296         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
4297         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4298         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
4299         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4300         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4301         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4302         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4303         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
4304         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
4305 }
4306
4307 /* conf file stuff */
4308 #define SWM_CONF_FILE   "scrotwm.conf"
4309
4310 enum    { SWM_S_BAR_DELAY, SWM_S_BAR_ENABLED, SWM_S_BAR_BORDER_WIDTH, SWM_S_STACK_ENABLED,
4311           SWM_S_CLOCK_ENABLED, SWM_S_CLOCK_FORMAT, SWM_S_CYCLE_EMPTY,
4312           SWM_S_CYCLE_VISIBLE, SWM_S_SS_ENABLED, SWM_S_TERM_WIDTH,
4313           SWM_S_TITLE_CLASS_ENABLED, SWM_S_TITLE_NAME_ENABLED, SWM_S_WINDOW_NAME_ENABLED,
4314           SWM_S_FOCUS_MODE, SWM_S_DISABLE_BORDER, SWM_S_BORDER_WIDTH, SWM_S_BAR_FONT,
4315           SWM_S_BAR_ACTION, SWM_S_SPAWN_TERM, SWM_S_SS_APP, SWM_S_DIALOG_RATIO,
4316           SWM_S_BAR_AT_BOTTOM
4317         };
4318
4319 int
4320 setconfvalue(char *selector, char *value, int flags)
4321 {
4322         switch (flags) {
4323         case SWM_S_BAR_DELAY:
4324                 bar_delay = atoi(value);
4325                 break;
4326         case SWM_S_BAR_ENABLED:
4327                 bar_enabled = atoi(value);
4328                 break;
4329         case SWM_S_BAR_BORDER_WIDTH:
4330                 bar_border_width = atoi(value);
4331                 break;
4332         case SWM_S_BAR_AT_BOTTOM:
4333                 bar_at_bottom = atoi(value);
4334                 break;
4335         case SWM_S_STACK_ENABLED:
4336                 stack_enabled = atoi(value);
4337                 break;
4338         case SWM_S_CLOCK_ENABLED:
4339                 clock_enabled = atoi(value);
4340                 break;
4341         case SWM_S_CLOCK_FORMAT:
4342 #ifndef SWM_DENY_CLOCK_FORMAT
4343                 free(clock_format);
4344                 if ((clock_format = strdup(value)) == NULL)
4345                         err(1, "setconfvalue: clock_format");
4346 #endif
4347                 break;
4348         case SWM_S_CYCLE_EMPTY:
4349                 cycle_empty = atoi(value);
4350                 break;
4351         case SWM_S_CYCLE_VISIBLE:
4352                 cycle_visible = atoi(value);
4353                 break;
4354         case SWM_S_SS_ENABLED:
4355                 ss_enabled = atoi(value);
4356                 break;
4357         case SWM_S_TERM_WIDTH:
4358                 term_width = atoi(value);
4359                 break;
4360         case SWM_S_TITLE_CLASS_ENABLED:
4361                 title_class_enabled = atoi(value);
4362                 break;
4363         case SWM_S_WINDOW_NAME_ENABLED:
4364                 window_name_enabled = atoi(value);
4365                 break;
4366         case SWM_S_TITLE_NAME_ENABLED:
4367                 title_name_enabled = atoi(value);
4368                 break;
4369         case SWM_S_FOCUS_MODE:
4370                 if (!strcmp(value, "default"))
4371                         focus_mode = SWM_FOCUS_DEFAULT;
4372                 else if (!strcmp(value, "follow_cursor"))
4373                         focus_mode = SWM_FOCUS_FOLLOW;
4374                 else if (!strcmp(value, "synergy"))
4375                         focus_mode = SWM_FOCUS_SYNERGY;
4376                 else
4377                         err(1, "focus_mode");
4378                 break;
4379         case SWM_S_DISABLE_BORDER:
4380                 disable_border = atoi(value);
4381                 break;
4382         case SWM_S_BORDER_WIDTH:
4383                 border_width = atoi(value);
4384                 break;
4385         case SWM_S_BAR_FONT:
4386                 free(bar_fonts[0]);
4387                 if ((bar_fonts[0] = strdup(value)) == NULL)
4388                         err(1, "setconfvalue: bar_font");
4389                 break;
4390         case SWM_S_BAR_ACTION:
4391                 free(bar_argv[0]);
4392                 if ((bar_argv[0] = strdup(value)) == NULL)
4393                         err(1, "setconfvalue: bar_action");
4394                 break;
4395         case SWM_S_SPAWN_TERM:
4396                 free(spawn_term[0]);
4397                 if ((spawn_term[0] = strdup(value)) == NULL)
4398                         err(1, "setconfvalue: spawn_term");
4399                 break;
4400         case SWM_S_SS_APP:
4401                 break;
4402         case SWM_S_DIALOG_RATIO:
4403                 dialog_ratio = atof(value);
4404                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
4405                         dialog_ratio = .6;
4406                 break;
4407         default:
4408                 return (1);
4409         }
4410         return (0);
4411 }
4412
4413 int
4414 setconfmodkey(char *selector, char *value, int flags)
4415 {
4416         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
4417                 update_modkey(Mod1Mask);
4418         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
4419                 update_modkey(Mod2Mask);
4420         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
4421                 update_modkey(Mod3Mask);
4422         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
4423                 update_modkey(Mod4Mask);
4424         else
4425                 return (1);
4426         return (0);
4427 }
4428
4429 int
4430 setconfcolor(char *selector, char *value, int flags)
4431 {
4432         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
4433         return (0);
4434 }
4435
4436 int
4437 setconfregion(char *selector, char *value, int flags)
4438 {
4439         custom_region(value);
4440         return (0);
4441 }
4442
4443 /* config options */
4444 struct config_option {
4445         char                    *optname;
4446         int (*func)(char*, char*, int);
4447         int funcflags;
4448 };
4449 struct config_option configopt[] = {
4450         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
4451         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
4452         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
4453         { "bar_border_width",                   setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
4454         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
4455         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
4456         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
4457         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
4458         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
4459         { "bind",                       setconfbinding, 0 },
4460         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
4461         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
4462         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
4463         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
4464         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
4465         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
4466         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
4467         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
4468         { "modkey",                     setconfmodkey,  0 },
4469         { "program",                    setconfspawn,   0 },
4470         { "quirk",                      setconfquirk,   0 },
4471         { "region",                     setconfregion,  0 },
4472         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
4473         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
4474         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
4475         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
4476         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
4477         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
4478         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
4479         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
4480         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
4481         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
4482 };
4483
4484
4485 int
4486 conf_load(char *filename)
4487 {
4488         FILE                    *config;
4489         char                    *line, *cp, *optsub, *optval;
4490         size_t                  linelen, lineno = 0;
4491         int                     wordlen, i, optind;
4492         struct config_option    *opt;
4493
4494         DNPRINTF(SWM_D_CONF, "conf_load begin\n");
4495
4496         if (filename == NULL) {
4497                 fprintf(stderr, "conf_load: no filename\n");
4498                 return (1);
4499         }
4500         if ((config = fopen(filename, "r")) == NULL) {
4501                 warn("conf_load: fopen");
4502                 return (1);
4503         }
4504
4505         while (!feof(config)) {
4506                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
4507                     == NULL) {
4508                         if (ferror(config))
4509                                 err(1, "%s", filename);
4510                         else
4511                                 continue;
4512                 }
4513                 cp = line;
4514                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4515                 if (cp[0] == '\0') {
4516                         /* empty line */
4517                         free(line);
4518                         continue;
4519                 }
4520                 /* get config option */
4521                 wordlen = strcspn(cp, "=[ \t\n");
4522                 if (wordlen == 0) {
4523                         warnx("%s: line %zd: no option found",
4524                             filename, lineno);
4525                         return (1);
4526                 }
4527                 optind = -1;
4528                 for (i = 0; i < LENGTH(configopt); i++) {
4529                         opt = &configopt[i];
4530                         if (!strncasecmp(cp, opt->optname, wordlen) &&
4531                             strlen(opt->optname) == wordlen) {
4532                                 optind = i;
4533                                 break;
4534                         }
4535                 }
4536                 if (optind == -1) {
4537                         warnx("%s: line %zd: unknown option %.*s",
4538                             filename, lineno, wordlen, cp);
4539                         return (1);
4540                 }
4541                 cp += wordlen;
4542                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4543                 /* get [selector] if any */
4544                 optsub = NULL;
4545                 if (*cp == '[') {
4546                         cp++;
4547                         wordlen = strcspn(cp, "]");
4548                         if (*cp != ']') {
4549                                 if (wordlen == 0) {
4550                                         warnx("%s: line %zd: syntax error",
4551                                             filename, lineno);
4552                                         return (1);
4553                                 }
4554                                 asprintf(&optsub, "%.*s", wordlen, cp);
4555                         }
4556                         cp += wordlen;
4557                         cp += strspn(cp, "] \t\n"); /* eat trailing */
4558                 }
4559                 cp += strspn(cp, "= \t\n"); /* eat trailing */
4560                 /* get RHS value */
4561                 optval = strdup(cp);
4562                 /* call function to deal with it all */
4563                 if (configopt[optind].func(optsub, optval,
4564                     configopt[optind].funcflags) != 0) {
4565                         fprintf(stderr, "%s line %zd: %s\n",
4566                             filename, lineno, line);
4567                         errx(1, "%s: line %zd: invalid data for %s",
4568                             filename, lineno, configopt[optind].optname);
4569                 }
4570                 free(optval);
4571                 free(optsub);
4572                 free(line);
4573         }
4574
4575         fclose(config);
4576         DNPRINTF(SWM_D_CONF, "conf_load end\n");
4577
4578         return (0);
4579 }
4580
4581 void
4582 set_child_transient(struct ws_win *win)
4583 {
4584         struct ws_win           *parent;
4585
4586         parent = find_window(win->transient);
4587         if (parent)
4588                 parent->child_trans = win;
4589 }
4590
4591 struct ws_win *
4592 manage_window(Window id)
4593 {
4594         Window                  trans = 0;
4595         struct workspace        *ws;
4596         struct ws_win           *win, *ww;
4597         int                     format, i, ws_idx, n, border_me = 0;
4598         unsigned long           nitems, bytes;
4599         Atom                    ws_idx_atom = 0, type;
4600         Atom                    *prot = NULL, *pp;
4601         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
4602         struct swm_region       *r;
4603         long                    mask;
4604         const char              *errstr;
4605         XWindowChanges          wc;
4606
4607         if ((win = find_window(id)) != NULL)
4608                 return (win);   /* already being managed */
4609
4610         /* see if we are on the unmanaged list */
4611         if ((win = find_unmanaged_window(id)) != NULL) {
4612                 DNPRINTF(SWM_D_MISC, "manage previously unmanaged window "
4613                     "%lu\n", win->id);
4614                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4615                 if (win->transient)
4616                         set_child_transient(win);
4617                 if (trans && (ww = find_window(trans)))
4618                         TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
4619                 else
4620                         TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
4621                 ewmh_update_actions(win);
4622                 return (win);
4623         }
4624
4625         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
4626                 errx(1, "calloc: failed to allocate memory for new window");
4627
4628         win->id = id;
4629
4630         /* Get all the window data in one shot */
4631         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
4632         if (ws_idx_atom)
4633                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
4634                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
4635         XGetWindowAttributes(display, id, &win->wa);
4636         XGetWMNormalHints(display, id, &win->sh, &mask);
4637         XGetTransientForHint(display, id, &trans);
4638         if (trans) {
4639                 win->transient = trans;
4640                 set_child_transient(win);
4641                 DNPRINTF(SWM_D_MISC, "manage_window: win %lu transient %lu\n",
4642                     win->id, win->transient);
4643         }
4644
4645         /* get supported protocols */
4646         if (XGetWMProtocols(display, id, &prot, &n)) {
4647                 for (i = 0, pp = prot; i < n; i++, pp++) {
4648                         if (*pp == takefocus)
4649                                 win->take_focus = 1;
4650                         if (*pp == adelete)
4651                                 win->can_delete = 1;
4652                 }
4653                 if (prot)
4654                         XFree(prot);
4655         }
4656
4657         win->iconic = get_iconic(win);
4658
4659         /*
4660          * Figure out where to put the window. If it was previously assigned to
4661          * a workspace (either by spawn() or manually moving), and isn't
4662          * transient, * put it in the same workspace
4663          */
4664         r = root_to_region(win->wa.root);
4665         if (prop && win->transient == 0) {
4666                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
4667                 ws_idx = strtonum(prop, 0, 9, &errstr);
4668                 if (errstr) {
4669                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
4670                             errstr, prop);
4671                 }
4672                 ws = &r->s->ws[ws_idx];
4673         } else {
4674                 ws = r->ws;
4675                 /* this should launch transients in the same ws as parent */
4676                 if (id && trans)
4677                         if ((ww = find_window(trans)) != NULL)
4678                                 if (ws->r) {
4679                                         ws = ww->ws;
4680                                         if (ww->ws->r)
4681                                                 r = ww->ws->r;
4682                                         else
4683                                                 fprintf(stderr,
4684                                                     "fix this bug mcbride\n");
4685                                         border_me = 1;
4686                                 }
4687         }
4688
4689         /* set up the window layout */
4690         win->id = id;
4691         win->ws = ws;
4692         win->s = r->s;  /* this never changes */
4693         if (trans && (ww = find_window(trans)))
4694                 TAILQ_INSERT_AFTER(&ws->winlist, ww, win, entry);
4695         else
4696                 TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
4697
4698         win->g.w = win->wa.width;
4699         win->g.h = win->wa.height;
4700         win->g.x = win->wa.x;
4701         win->g.y = win->wa.y;
4702         win->g_floatvalid = 0;
4703         win->floatmaxed = 0;
4704         win->ewmh_flags = 0;
4705
4706         /* Set window properties so we can remember this after reincarnation */
4707         if (ws_idx_atom && prop == NULL &&
4708             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
4709                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
4710                     ws_idx_str);
4711                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
4712                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
4713         }
4714         if (prop)
4715                 XFree(prop);
4716
4717         ewmh_autoquirk(win);
4718
4719         if (XGetClassHint(display, win->id, &win->ch)) {
4720                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
4721                     win->ch.res_class, win->ch.res_name);
4722
4723                 /* java is retarded so treat it special */
4724                 if (strstr(win->ch.res_name, "sun-awt")) {
4725                         win->java = 1;
4726                         border_me = 1;
4727                 }
4728
4729                 for (i = 0; i < quirks_length; i++){
4730                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
4731                             !strcmp(win->ch.res_name, quirks[i].name)) {
4732                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
4733                                     win->ch.res_class, win->ch.res_name);
4734                                 if (quirks[i].quirk & SWM_Q_FLOAT) {
4735                                         win->floating = 1;
4736                                         border_me = 1;
4737                                 }
4738                                 win->quirks = quirks[i].quirk;
4739                         }
4740                 }
4741         }
4742
4743         /* alter window position if quirky */
4744         if (win->quirks & SWM_Q_ANYWHERE) {
4745                 win->manual = 1; /* don't center the quirky windows */
4746                 bzero(&wc, sizeof wc);
4747                 mask = 0;
4748                 if (bar_enabled && win->g.y < bar_height) {
4749                         win->g.y = wc.y = bar_height;
4750                         mask |= CWY;
4751                 }
4752                 if (win->g.w + win->g.x > WIDTH(r)) {
4753                         win->g.x = wc.x = WIDTH(r) - win->g.w - 2;
4754                         mask |= CWX;
4755                 }
4756                 border_me = 1;
4757         }
4758
4759         /* Reset font sizes (the bruteforce way; no default keybinding). */
4760         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
4761                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4762                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
4763                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4764                         fake_keypress(win, XK_KP_Add, ShiftMask);
4765         }
4766
4767         ewmh_get_win_state(win);
4768         ewmh_update_actions(win);
4769         ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
4770
4771         /* border me */
4772         if (border_me) {
4773                 bzero(&wc, sizeof wc);
4774                 wc.border_width = border_width;
4775                 mask = CWBorderWidth;
4776                 XConfigureWindow(display, win->id, mask, &wc);
4777         }
4778
4779         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
4780             PropertyChangeMask | StructureNotifyMask);
4781         if (win->iconic)
4782                 set_win_state(win, IconicState);
4783         else
4784                 set_win_state(win, NormalState);
4785
4786         /* floaters need to be mapped if they are in the current workspace */
4787         if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
4788                 XMapRaised(display, win->id);
4789
4790         return (win);
4791 }
4792
4793 void
4794 free_window(struct ws_win *win)
4795 {
4796         DNPRINTF(SWM_D_MISC, "free_window:  %lu\n", win->id);
4797
4798         if (win == NULL)
4799                 return;
4800
4801         /* needed for restart wm */
4802         set_win_state(win, WithdrawnState);
4803
4804         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4805
4806         if (win->ch.res_class)
4807                 XFree(win->ch.res_class);
4808         if (win->ch.res_name)
4809                 XFree(win->ch.res_name);
4810
4811         kill_refs(win);
4812
4813         /* paint memory */
4814         memset(win, 0xff, sizeof *win); /* XXX kill later */
4815
4816         free(win);
4817 }
4818
4819 void
4820 unmanage_window(struct ws_win *win)
4821 {
4822         struct ws_win           *parent;
4823
4824         if (win == NULL)
4825                 return;
4826
4827         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
4828
4829         if (win->transient) {
4830                 parent = find_window(win->transient);
4831                 if (parent)
4832                         parent->child_trans = NULL;
4833         }
4834
4835         /* focus on root just in case */
4836         XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
4837
4838         focus_prev(win);
4839
4840         TAILQ_REMOVE(&win->ws->winlist, win, entry);
4841         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
4842
4843         kill_refs(win);
4844 }
4845
4846 void
4847 focus_magic(struct ws_win *win)
4848 {
4849         DNPRINTF(SWM_D_FOCUS, "focus_magic: %lu\n", WINID(win));
4850
4851         if (win == NULL)
4852                 return;
4853
4854         if (win->child_trans) {
4855                 /* win = parent & has a transient so focus on that */
4856                 if (win->java) {
4857                         focus_win(win->child_trans);
4858                         if (win->child_trans->take_focus)
4859                                 client_msg(win, takefocus);
4860                 } else {
4861                         /* make sure transient hasn't dissapeared */
4862                         if (validate_win(win->child_trans) == 0) {
4863                                 focus_win(win->child_trans);
4864                                 if (win->child_trans->take_focus)
4865                                         client_msg(win->child_trans, takefocus);
4866                         } else {
4867                                 win->child_trans = NULL;
4868                                 focus_win(win);
4869                                 if (win->take_focus)
4870                                         client_msg(win, takefocus);
4871                         }
4872                 }
4873         } else {
4874                 /* regular focus */
4875                 focus_win(win);
4876                 if (win->take_focus)
4877                         client_msg(win, takefocus);
4878         }
4879 }
4880
4881 void
4882 expose(XEvent *e)
4883 {
4884         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
4885 }
4886
4887 void
4888 keypress(XEvent *e)
4889 {
4890         unsigned int            i;
4891         KeySym                  keysym;
4892         XKeyEvent               *ev = &e->xkey;
4893
4894         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
4895
4896         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
4897         for (i = 0; i < keys_length; i++)
4898                 if (keysym == keys[i].keysym
4899                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
4900                    && keyfuncs[keys[i].funcid].func) {
4901                         if (keys[i].funcid == kf_spawn_custom)
4902                                 spawn_custom(
4903                                     root_to_region(ev->root),
4904                                     &(keyfuncs[keys[i].funcid].args),
4905                                     keys[i].spawn_name
4906                                     );
4907                         else
4908                                 keyfuncs[keys[i].funcid].func(
4909                                     root_to_region(ev->root),
4910                                     &(keyfuncs[keys[i].funcid].args)
4911                                     );
4912                 }
4913 }
4914
4915 void
4916 buttonpress(XEvent *e)
4917 {
4918         struct ws_win           *win;
4919         int                     i, action;
4920         XButtonPressedEvent     *ev = &e->xbutton;
4921
4922         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
4923
4924         action = root_click;
4925         if ((win = find_window(ev->window)) == NULL)
4926                 return;
4927
4928         focus_magic(win);
4929         action = client_click;
4930
4931         for (i = 0; i < LENGTH(buttons); i++)
4932                 if (action == buttons[i].action && buttons[i].func &&
4933                     buttons[i].button == ev->button &&
4934                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
4935                         buttons[i].func(win, &buttons[i].args);
4936 }
4937
4938 void
4939 configurerequest(XEvent *e)
4940 {
4941         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
4942         struct ws_win           *win;
4943         int                     new = 0;
4944         XWindowChanges          wc;
4945
4946         if ((win = find_window(ev->window)) == NULL)
4947                 if ((win = find_unmanaged_window(ev->window)) == NULL)
4948                         new = 1;
4949
4950         if (new) {
4951                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
4952                     ev->window);
4953                 bzero(&wc, sizeof wc);
4954                 wc.x = ev->x;
4955                 wc.y = ev->y;
4956                 wc.width = ev->width;
4957                 wc.height = ev->height;
4958                 wc.border_width = ev->border_width;
4959                 wc.sibling = ev->above;
4960                 wc.stack_mode = ev->detail;
4961                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
4962         } else {
4963                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
4964                     ev->window);
4965                 config_win(win, ev);
4966         }
4967 }
4968
4969 void
4970 configurenotify(XEvent *e)
4971 {
4972         struct ws_win           *win;
4973         long                    mask;
4974
4975         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
4976             e->xconfigure.window);
4977
4978         win = find_window(e->xconfigure.window);
4979         if (win) {
4980                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
4981                 adjust_font(win);
4982                 if (font_adjusted)
4983                         stack();
4984         }
4985 }
4986
4987 void
4988 destroynotify(XEvent *e)
4989 {
4990         struct ws_win           *win;
4991         XDestroyWindowEvent     *ev = &e->xdestroywindow;
4992
4993         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
4994
4995         if ((win = find_window(ev->window)) == NULL) {
4996                 if ((win = find_unmanaged_window(ev->window)) == NULL)
4997                         return;
4998                 free_window(win);
4999                 return;
5000         }
5001
5002         /* make sure we focus on something */
5003         win->floating = 0;
5004
5005         unmanage_window(win);
5006         stack();
5007         free_window(win);
5008 }
5009
5010 void
5011 enternotify(XEvent *e)
5012 {
5013         XCrossingEvent          *ev = &e->xcrossing;
5014         XEvent                  cne;
5015         struct ws_win           *win;
5016 #if 0
5017         struct ws_win           *w;
5018         Window                  focus_return;
5019         int                     revert_to_return;
5020 #endif
5021         DNPRINTF(SWM_D_FOCUS, "enternotify: window: %lu mode %d detail %d root "
5022             "%lu subwindow %lu same_screen %d focus %d state %d\n",
5023             ev->window, ev->mode, ev->detail, ev->root, ev->subwindow,
5024             ev->same_screen, ev->focus, ev->state);
5025
5026         switch (focus_mode) {
5027         case SWM_FOCUS_DEFAULT:
5028                 if (QLength(display)) {
5029                         DNPRINTF(SWM_D_EVENT, "ignore enternotify %d\n",
5030                             QLength(display));
5031                         return;
5032                 }
5033                 break;
5034         case SWM_FOCUS_FOLLOW:
5035                 break;
5036         case SWM_FOCUS_SYNERGY:
5037 #if 0
5038         /*
5039          * all these checks need to be in this order because the
5040          * XCheckTypedWindowEvent relies on weeding out the previous events
5041          *
5042          * making this code an option would enable a follow mouse for focus
5043          * feature
5044          */
5045
5046         /*
5047          * state is set when we are switching workspaces and focus is set when
5048          * the window or a subwindow already has focus (occurs during restart).
5049          *
5050          * Only honor the focus flag if last_focus_event is not FocusOut,
5051          * this allows scrotwm to continue to control focus when another
5052          * program is also playing with it.
5053          */
5054         if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
5055                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
5056                 return;
5057         }
5058
5059         /*
5060          * happens when a window is created or destroyed and the border
5061          * crosses the mouse pointer and when switching ws
5062          *
5063          * we need the subwindow test to see if we came from root in order
5064          * to give focus to floaters
5065          */
5066         if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
5067             ev->subwindow == 0) {
5068                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
5069                 return;
5070         }
5071
5072         /* this window already has focus */
5073         if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
5074                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
5075                 return;
5076         }
5077
5078         /* this window is being deleted or moved to another ws */
5079         if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
5080             &cne) == True) {
5081                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
5082                 XPutBackEvent(display, &cne);
5083                 return;
5084         }
5085
5086         if ((win = find_window(ev->window)) == NULL) {
5087                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5088                 return;
5089         }
5090
5091         /*
5092          * In fullstack kill all enters unless they come from a different ws
5093          * (i.e. another region) or focus has been grabbed externally.
5094          */
5095         if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
5096             last_focus_event != FocusOut) {
5097                 XGetInputFocus(display, &focus_return, &revert_to_return);
5098                 if ((w = find_window(focus_return)) == NULL ||
5099                     w->ws == win->ws) {
5100                         DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
5101                         return;
5102                 }
5103         }
5104 #endif
5105                 break;
5106         }
5107
5108         if ((win = find_window(ev->window)) == NULL) {
5109                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5110                 return;
5111         }
5112
5113         /*
5114          * if we have more enternotifies let them handle it in due time
5115          */
5116         if (XCheckTypedEvent(display, EnterNotify, &cne) == True) {
5117                 DNPRINTF(SWM_D_EVENT,
5118                     "ignoring enternotify: got more enternotify\n");
5119                 XPutBackEvent(display, &cne);
5120                 return;
5121         }
5122
5123         focus_magic(win);
5124 }
5125
5126 /* lets us use one switch statement for arbitrary mode/detail combinations */
5127 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
5128
5129 void
5130 focusevent(XEvent *e)
5131 {
5132 #if 0
5133         struct ws_win           *win;
5134         u_int32_t               mode_detail;
5135         XFocusChangeEvent       *ev = &e->xfocus;
5136
5137         DNPRINTF(SWM_D_EVENT, "focusevent: %s window: %lu mode %d detail %d\n",
5138             ev->type == FocusIn ? "entering" : "leaving",
5139             ev->window, ev->mode, ev->detail);
5140
5141         if (last_focus_event == ev->type) {
5142                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent: bad ordering\n");
5143                 return;
5144         }
5145
5146         last_focus_event = ev->type;
5147         mode_detail = MERGE_MEMBERS(ev->mode, ev->detail);
5148
5149         switch (mode_detail) {
5150         /* synergy client focus operations */
5151         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinear):
5152         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinearVirtual):
5153
5154         /* synergy server focus operations */
5155         case MERGE_MEMBERS(NotifyWhileGrabbed, NotifyNonlinear):
5156
5157         /* Entering applications like rdesktop that mangle the pointer */
5158         case MERGE_MEMBERS(NotifyNormal, NotifyPointer):
5159
5160                 if ((win = find_window(e->xfocus.window)) != NULL && win->ws->r)
5161                         XSetWindowBorder(display, win->id,
5162                             win->ws->r->s->c[ev->type == FocusIn ?
5163                             SWM_S_COLOR_FOCUS : SWM_S_COLOR_UNFOCUS].color);
5164                 break;
5165         default:
5166                 fprintf(stderr, "ignoring focusevent\n");
5167                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent\n");
5168                 break;
5169         }
5170 #endif
5171 }
5172
5173 void
5174 mapnotify(XEvent *e)
5175 {
5176         struct ws_win           *win;
5177         XMapEvent               *ev = &e->xmap;
5178
5179         DNPRINTF(SWM_D_EVENT, "mapnotify: window: %lu\n", ev->window);
5180
5181         win = manage_window(ev->window);
5182         if (win)
5183                 set_win_state(win, NormalState);
5184 }
5185
5186 void
5187 mappingnotify(XEvent *e)
5188 {
5189         XMappingEvent           *ev = &e->xmapping;
5190
5191         XRefreshKeyboardMapping(ev);
5192         if (ev->request == MappingKeyboard)
5193                 grabkeys();
5194 }
5195
5196 void
5197 maprequest(XEvent *e)
5198 {
5199         struct ws_win           *win;
5200         struct swm_region       *r;
5201         XWindowAttributes       wa;
5202         XMapRequestEvent        *ev = &e->xmaprequest;
5203
5204         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
5205             e->xmaprequest.window);
5206
5207         if (!XGetWindowAttributes(display, ev->window, &wa))
5208                 return;
5209         if (wa.override_redirect)
5210                 return;
5211
5212         win = manage_window(e->xmaprequest.window);
5213         if (win == NULL)
5214                 return; /* can't happen */
5215
5216         stack();
5217
5218         /* make new win focused */
5219         r = root_to_region(win->wa.root);
5220         if (win->ws == r->ws)
5221                 focus_magic(win);
5222 }
5223
5224 void
5225 propertynotify(XEvent *e)
5226 {
5227         struct ws_win           *win;
5228         XPropertyEvent          *ev = &e->xproperty;
5229
5230         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
5231             ev->window);
5232
5233         win = find_window(ev->window);
5234         if (win == NULL)
5235                 return;
5236
5237         if (ev->state == PropertyDelete && ev->atom == a_swm_iconic) {
5238                 update_iconic(win, 0);
5239                 XMapRaised(display, win->id);
5240                 stack();
5241                 focus_win(win);
5242                 return;
5243         }
5244
5245         switch (ev->atom) {
5246         case XA_WM_NORMAL_HINTS:
5247 #if 0
5248                 long            mask;
5249                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5250                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
5251                 if (win->sh.flags & PMinSize) {
5252                         win->g.w = win->sh.min_width;
5253                         win->g.h = win->sh.min_height;
5254                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
5255                 }
5256                 XMoveResizeWindow(display, win->id,
5257                     win->g.x, win->g.y, win->g.w, win->g.h);
5258 #endif
5259                 if (window_name_enabled)
5260                         bar_update();
5261                 break;
5262         default:
5263                 break;
5264         }
5265 }
5266
5267 void
5268 unmapnotify(XEvent *e)
5269 {
5270         struct ws_win           *win;
5271
5272         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
5273
5274         /* determine if we need to help unmanage this window */
5275         win = find_window(e->xunmap.window);
5276         if (win == NULL)
5277                 return;
5278
5279         if (getstate(e->xunmap.window) == NormalState) {
5280                 unmanage_window(win);
5281                 stack();
5282         }
5283 }
5284
5285 void
5286 visibilitynotify(XEvent *e)
5287 {
5288         int                     i;
5289         struct swm_region       *r;
5290
5291         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
5292             e->xvisibility.window);
5293         if (e->xvisibility.state == VisibilityUnobscured)
5294                 for (i = 0; i < ScreenCount(display); i++)
5295                         TAILQ_FOREACH(r, &screens[i].rl, entry)
5296                                 if (e->xvisibility.window == r->bar_window)
5297                                         bar_update();
5298 }
5299
5300 void
5301 clientmessage(XEvent *e)
5302 {
5303         XClientMessageEvent *ev;
5304         struct ws_win *win;
5305
5306         ev = &e->xclient;
5307
5308         win = find_window(ev->window);
5309         if (win == NULL)
5310                 return;
5311
5312         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%lx type: %ld \n",
5313             ev->window, ev->message_type);
5314
5315         if (ev->message_type == ewmh[_NET_ACTIVE_WINDOW].atom) {
5316                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW \n");
5317                 focus_win(win);
5318         }
5319         if (ev->message_type == ewmh[_NET_CLOSE_WINDOW].atom) {
5320                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW \n");
5321                 if (win->can_delete)
5322                         client_msg(win, adelete);
5323                 else
5324                         XKillClient(display, win->id);
5325         }
5326         if (ev->message_type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
5327                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_MOVERESIZE_WINDOW \n");
5328                 if (win->floating) {
5329                         if (ev->data.l[0] & (1<<8)) /* x */
5330                                 win->g.x = ev->data.l[1];
5331                         if (ev->data.l[0] & (1<<9)) /* y */
5332                                 win->g.y = ev->data.l[2];
5333                         if (ev->data.l[0] & (1<<10)) /* width */
5334                                 win->g.w = ev->data.l[3];
5335                         if (ev->data.l[0] & (1<<11)) /* height */
5336                                 win->g.h = ev->data.l[4];
5337                 }
5338                 else {
5339                         /* TODO: Change stack sizes */
5340                 }
5341                 config_win(win, NULL);
5342         }
5343         if (ev->message_type == ewmh[_NET_WM_STATE].atom) {
5344                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE \n");
5345                 ewmh_update_win_state(win, ev->data.l[1], ev->data.l[0]);
5346                 if (ev->data.l[2])
5347                         ewmh_update_win_state(win, ev->data.l[2], ev->data.l[0]);
5348
5349                 stack();
5350         }
5351 }
5352
5353 int
5354 xerror_start(Display *d, XErrorEvent *ee)
5355 {
5356         other_wm = 1;
5357         return (-1);
5358 }
5359
5360 int
5361 xerror(Display *d, XErrorEvent *ee)
5362 {
5363         /* fprintf(stderr, "error: %p %p\n", display, ee); */
5364         return (-1);
5365 }
5366
5367 int
5368 active_wm(void)
5369 {
5370         other_wm = 0;
5371         xerrorxlib = XSetErrorHandler(xerror_start);
5372
5373         /* this causes an error if some other window manager is running */
5374         XSelectInput(display, DefaultRootWindow(display),
5375             SubstructureRedirectMask);
5376         XSync(display, False);
5377         if (other_wm)
5378                 return (1);
5379
5380         XSetErrorHandler(xerror);
5381         XSync(display, False);
5382         return (0);
5383 }
5384
5385 void
5386 new_region(struct swm_screen *s, int x, int y, int w, int h)
5387 {
5388         struct swm_region       *r, *n;
5389         struct workspace        *ws = NULL;
5390         int                     i;
5391
5392         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
5393              s->idx, w, h, x, y);
5394
5395         /* remove any conflicting regions */
5396         n = TAILQ_FIRST(&s->rl);
5397         while (n) {
5398                 r = n;
5399                 n = TAILQ_NEXT(r, entry);
5400                 if (X(r) < (x + w) &&
5401                     (X(r) + WIDTH(r)) > x &&
5402                     Y(r) < (y + h) &&
5403                     (Y(r) + HEIGHT(r)) > y) {
5404                         if (r->ws->r != NULL)
5405                                 r->ws->old_r = r->ws->r;
5406                         r->ws->r = NULL;
5407                         XDestroyWindow(display, r->bar_window);
5408                         TAILQ_REMOVE(&s->rl, r, entry);
5409                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
5410                 }
5411         }
5412
5413         /* search old regions for one to reuse */
5414
5415         /* size + location match */
5416         TAILQ_FOREACH(r, &s->orl, entry)
5417                 if (X(r) == x && Y(r) == y &&
5418                     HEIGHT(r) == h && WIDTH(r) == w)
5419                         break;
5420
5421         /* size match */
5422         TAILQ_FOREACH(r, &s->orl, entry)
5423                 if (HEIGHT(r) == h && WIDTH(r) == w)
5424                         break;
5425
5426         if (r != NULL) {
5427                 TAILQ_REMOVE(&s->orl, r, entry);
5428                 /* try to use old region's workspace */
5429                 if (r->ws->r == NULL)
5430                         ws = r->ws;
5431         } else
5432                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
5433                         errx(1, "calloc: failed to allocate memory for screen");
5434
5435         /* if we don't have a workspace already, find one */
5436         if (ws == NULL) {
5437                 for (i = 0; i < SWM_WS_MAX; i++)
5438                         if (s->ws[i].r == NULL) {
5439                                 ws = &s->ws[i];
5440                                 break;
5441                         }
5442         }
5443
5444         if (ws == NULL)
5445                 errx(1, "no free workspaces\n");
5446
5447         X(r) = x;
5448         Y(r) = y;
5449         WIDTH(r) = w;
5450         HEIGHT(r) = h;
5451         r->s = s;
5452         r->ws = ws;
5453         r->ws_prior = NULL;
5454         ws->r = r;
5455         outputs++;
5456         TAILQ_INSERT_TAIL(&s->rl, r, entry);
5457 }
5458
5459 void
5460 scan_xrandr(int i)
5461 {
5462 #ifdef SWM_XRR_HAS_CRTC
5463         XRRCrtcInfo             *ci;
5464         XRRScreenResources      *sr;
5465         int                     c;
5466         int                     ncrtc = 0;
5467 #endif /* SWM_XRR_HAS_CRTC */
5468         struct swm_region       *r;
5469
5470
5471         if (i >= ScreenCount(display))
5472                 errx(1, "invalid screen");
5473
5474         /* remove any old regions */
5475         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
5476                 r->ws->old_r = r->ws->r = NULL;
5477                 XDestroyWindow(display, r->bar_window);
5478                 TAILQ_REMOVE(&screens[i].rl, r, entry);
5479                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
5480         }
5481         outputs = 0;
5482
5483         /* map virtual screens onto physical screens */
5484 #ifdef SWM_XRR_HAS_CRTC
5485         if (xrandr_support) {
5486                 sr = XRRGetScreenResources(display, screens[i].root);
5487                 if (sr == NULL)
5488                         new_region(&screens[i], 0, 0,
5489                             DisplayWidth(display, i),
5490                             DisplayHeight(display, i));
5491                 else
5492                         ncrtc = sr->ncrtc;
5493
5494                 for (c = 0, ci = NULL; c < ncrtc; c++) {
5495                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
5496                         if (ci->noutput == 0)
5497                                 continue;
5498
5499                         if (ci != NULL && ci->mode == None)
5500                                 new_region(&screens[i], 0, 0,
5501                                     DisplayWidth(display, i),
5502                                     DisplayHeight(display, i));
5503                         else
5504                                 new_region(&screens[i],
5505                                     ci->x, ci->y, ci->width, ci->height);
5506                 }
5507                 if (ci)
5508                         XRRFreeCrtcInfo(ci);
5509                 XRRFreeScreenResources(sr);
5510         } else
5511 #endif /* SWM_XRR_HAS_CRTC */
5512         {
5513                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
5514                     DisplayHeight(display, i));
5515         }
5516 }
5517
5518 void
5519 screenchange(XEvent *e) {
5520         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
5521         struct swm_region               *r;
5522         int                             i;
5523
5524         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
5525
5526         if (!XRRUpdateConfiguration(e))
5527                 return;
5528
5529         /* silly event doesn't include the screen index */
5530         for (i = 0; i < ScreenCount(display); i++)
5531                 if (screens[i].root == xe->root)
5532                         break;
5533         if (i >= ScreenCount(display))
5534                 errx(1, "screenchange: screen not found\n");
5535
5536         /* brute force for now, just re-enumerate the regions */
5537         scan_xrandr(i);
5538
5539         /* add bars to all regions */
5540         for (i = 0; i < ScreenCount(display); i++)
5541                 TAILQ_FOREACH(r, &screens[i].rl, entry)
5542                         bar_setup(r);
5543         stack();
5544 }
5545
5546 void
5547 grab_windows(void)
5548 {
5549         Window                  d1, d2, *wins = NULL;
5550         XWindowAttributes       wa;
5551         unsigned int            no;
5552         int                     i, j;
5553         long                    state, manage;
5554
5555         for (i = 0; i < ScreenCount(display); i++) {
5556                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
5557                         continue;
5558
5559                 /* attach windows to a region */
5560                 /* normal windows */
5561                 for (j = 0; j < no; j++) {
5562                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5563                             wa.override_redirect ||
5564                             XGetTransientForHint(display, wins[j], &d1))
5565                                 continue;
5566
5567                         state = getstate(wins[j]);
5568                         manage = state == IconicState || InactiveState;
5569                         if (wa.map_state == IsViewable || manage)
5570                                 manage_window(wins[j]);
5571                 }
5572                 /* transient windows */
5573                 for (j = 0; j < no; j++) {
5574                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5575                             wa.override_redirect)
5576                                 continue;
5577
5578                         state = getstate(wins[j]);
5579                         manage = state == IconicState || InactiveState;
5580                         if (XGetTransientForHint(display, wins[j], &d1) &&
5581                             manage)
5582                                 manage_window(wins[j]);
5583                 }
5584                 if (wins) {
5585                         XFree(wins);
5586                         wins = NULL;
5587                 }
5588         }
5589 }
5590
5591 void
5592 setup_screens(void)
5593 {
5594         int                     i, j, k;
5595         int                     errorbase, major, minor;
5596         struct workspace        *ws;
5597         int                     ws_idx_atom;
5598
5599         if ((screens = calloc(ScreenCount(display),
5600              sizeof(struct swm_screen))) == NULL)
5601                 errx(1, "calloc: screens");
5602
5603         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
5604
5605         /* initial Xrandr setup */
5606         xrandr_support = XRRQueryExtension(display,
5607             &xrandr_eventbase, &errorbase);
5608         if (xrandr_support)
5609                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
5610                         xrandr_support = 0;
5611
5612         /* map physical screens */
5613         for (i = 0; i < ScreenCount(display); i++) {
5614                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
5615                 screens[i].idx = i;
5616                 TAILQ_INIT(&screens[i].rl);
5617                 TAILQ_INIT(&screens[i].orl);
5618                 screens[i].root = RootWindow(display, i);
5619
5620                 /* set default colors */
5621                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
5622                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
5623                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
5624                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
5625                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
5626
5627                 /* set default cursor */
5628                 XDefineCursor(display, screens[i].root,
5629                     XCreateFontCursor(display, XC_left_ptr));
5630
5631                 /* init all workspaces */
5632                 /* XXX these should be dynamically allocated too */
5633                 for (j = 0; j < SWM_WS_MAX; j++) {
5634                         ws = &screens[i].ws[j];
5635                         ws->idx = j;
5636                         ws->focus = NULL;
5637                         ws->r = NULL;
5638                         ws->old_r = NULL;
5639                         TAILQ_INIT(&ws->winlist);
5640                         TAILQ_INIT(&ws->unmanagedlist);
5641
5642                         for (k = 0; layouts[k].l_stack != NULL; k++)
5643                                 if (layouts[k].l_config != NULL)
5644                                         layouts[k].l_config(ws,
5645                                             SWM_ARG_ID_STACKINIT);
5646                         ws->cur_layout = &layouts[0];
5647                 }
5648
5649                 scan_xrandr(i);
5650
5651                 if (xrandr_support)
5652                         XRRSelectInput(display, screens[i].root,
5653                             RRScreenChangeNotifyMask);
5654         }
5655 }
5656
5657 void
5658 setup_globals(void)
5659 {
5660         if ((bar_fonts[0] = strdup("-*-terminus-medium-*-*-*-*-*-*-*-*-*-*-*"))
5661             == NULL)
5662                 err(1, "setup_globals: strdup");
5663         if ((bar_fonts[1] = strdup("-*-times-medium-r-*-*-*-*-*-*-*-*-*-*"))
5664             == NULL)
5665                 err(1, "setup_globals: strdup");
5666         if ((bar_fonts[2] = strdup("-misc-fixed-medium-r-*-*-*-*-*-*-*-*-*-*"))
5667             == NULL)
5668                 err(1, "setup_globals: strdup");
5669         if ((spawn_term[0] = strdup("xterm")) == NULL)
5670                 err(1, "setup_globals: strdup");
5671         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
5672                 errx(1, "strdup");
5673 }
5674
5675 void
5676 workaround(void)
5677 {
5678         int                     i;
5679         Atom                    netwmcheck, netwmname, utf8_string;
5680         Window                  root, win;
5681
5682         /* work around sun jdk bugs, code from wmname */
5683         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
5684         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
5685         utf8_string = XInternAtom(display, "UTF8_STRING", False);
5686         for (i = 0; i < ScreenCount(display); i++) {
5687                 root = screens[i].root;
5688                 win = XCreateSimpleWindow(display,root, 0, 0, 1, 1, 0,
5689                     screens[i].c[SWM_S_COLOR_UNFOCUS].color,
5690                     screens[i].c[SWM_S_COLOR_UNFOCUS].color);
5691
5692                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
5693                     PropModeReplace, (unsigned char *)&win,1);
5694                 XChangeProperty(display, win, netwmcheck, XA_WINDOW, 32,
5695                     PropModeReplace, (unsigned char *)&win,1);
5696                 XChangeProperty(display, win, netwmname, utf8_string, 8,
5697                     PropModeReplace, (unsigned char*)"LG3D", strlen("LG3D"));
5698         }
5699 }
5700
5701 int
5702 main(int argc, char *argv[])
5703 {
5704         struct passwd           *pwd;
5705         struct swm_region       *r, *rr;
5706         struct ws_win           *winfocus = NULL;
5707         struct timeval          tv;
5708         union arg               a;
5709         char                    conf[PATH_MAX], *cfile = NULL;
5710         struct stat             sb;
5711         XEvent                  e;
5712         int                     xfd, i;
5713         fd_set                  rd;
5714         struct sigaction        sact;
5715
5716         start_argv = argv;
5717         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
5718             SWM_VERSION, cvstag);
5719         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
5720                 warnx("no locale support");
5721
5722         if (!(display = XOpenDisplay(0)))
5723                 errx(1, "can not open display");
5724
5725         if (active_wm())
5726                 errx(1, "other wm running");
5727
5728         /* handle some signals */
5729         bzero(&sact, sizeof(sact));
5730         sigemptyset(&sact.sa_mask);
5731         sact.sa_flags = 0;
5732         sact.sa_handler = sighdlr;
5733         sigaction(SIGINT, &sact, NULL);
5734         sigaction(SIGQUIT, &sact, NULL);
5735         sigaction(SIGTERM, &sact, NULL);
5736         sigaction(SIGHUP, &sact, NULL);
5737
5738         sact.sa_handler = sighdlr;
5739         sact.sa_flags = SA_NOCLDSTOP;
5740         sigaction(SIGCHLD, &sact, NULL);
5741
5742         astate = XInternAtom(display, "WM_STATE", False);
5743         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
5744         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
5745         takefocus = XInternAtom(display, "WM_TAKE_FOCUS", False);
5746         a_wmname = XInternAtom(display, "WM_NAME", False);
5747         a_utf8_string = XInternAtom(display, "UTF8_STRING", False);
5748         a_string = XInternAtom(display, "STRING", False);
5749         a_swm_iconic = XInternAtom(display, "_SWM_ICONIC", False);
5750
5751         /* look for local and global conf file */
5752         pwd = getpwuid(getuid());
5753         if (pwd == NULL)
5754                 errx(1, "invalid user %d", getuid());
5755
5756         setup_screens();
5757         setup_globals();
5758         setup_keys();
5759         setup_quirks();
5760         setup_spawn();
5761
5762         /* load config */
5763         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
5764         if (stat(conf, &sb) != -1) {
5765                 if (S_ISREG(sb.st_mode))
5766                         cfile = conf;
5767         } else {
5768                 /* try global conf file */
5769                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
5770                 if (!stat(conf, &sb))
5771                         if (S_ISREG(sb.st_mode))
5772                                 cfile = conf;
5773         }
5774         if (cfile)
5775                 conf_load(cfile);
5776
5777         setup_ewmh();
5778         /* set some values to work around bad programs */
5779         workaround();
5780
5781         /* grab existing windows (before we build the bars) */
5782         grab_windows();
5783
5784         /* setup all bars */
5785         for (i = 0; i < ScreenCount(display); i++)
5786                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
5787                         if (winfocus == NULL)
5788                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
5789                         bar_setup(r);
5790                 }
5791
5792         unfocus_all();
5793
5794         grabkeys();
5795         stack();
5796
5797         xfd = ConnectionNumber(display);
5798         while (running) {
5799                 while (XPending(display)) {
5800                         XNextEvent(display, &e);
5801                         if (running == 0)
5802                                 goto done;
5803                         if (e.type < LASTEvent) {
5804                                 dumpevent(&e);
5805                                 if (handler[e.type])
5806                                         handler[e.type](&e);
5807                                 else
5808                                         DNPRINTF(SWM_D_EVENT,
5809                                             "win: %lu unknown event: %d\n",
5810                                             e.xany.window, e.type);
5811                         } else {
5812                                 switch (e.type - xrandr_eventbase) {
5813                                 case RRScreenChangeNotify:
5814                                         screenchange(&e);
5815                                         break;
5816                                 default:
5817                                         DNPRINTF(SWM_D_EVENT,
5818                                             "win: %lu unknown xrandr event: "
5819                                             "%d\n", e.xany.window, e.type);
5820                                         break;
5821                                 }
5822                         }
5823                 }
5824
5825                 /* if we are being restarted go focus on first window */
5826                 if (winfocus) {
5827                         rr = winfocus->ws->r;
5828                         if (rr == NULL) {
5829                                 /* not a visible window */
5830                                 winfocus = NULL;
5831                                 continue;
5832                         }
5833                         /* move pointer to first screen if multi screen */
5834                         if (ScreenCount(display) > 1 || outputs > 1)
5835                                 XWarpPointer(display, None, rr->s[0].root,
5836                                     0, 0, 0, 0, rr->g.x,
5837                                     rr->g.y + (bar_enabled ? bar_height : 0));
5838
5839                         a.id = SWM_ARG_ID_FOCUSCUR;
5840                         focus(rr, &a);
5841                         winfocus = NULL;
5842                         continue;
5843                 }
5844
5845                 FD_ZERO(&rd);
5846                 FD_SET(xfd, &rd);
5847                 tv.tv_sec = 1;
5848                 tv.tv_usec = 0;
5849                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
5850                         if (errno != EINTR)
5851                                 DNPRINTF(SWM_D_MISC, "select failed");
5852                 if (restart_wm == 1)
5853                         restart(NULL, NULL);
5854                 if (search_resp == 1)
5855                         search_do_resp();
5856                 if (running == 0)
5857                         goto done;
5858                 if (bar_alarm) {
5859                         bar_alarm = 0;
5860                         bar_update();
5861                 }
5862         }
5863 done:
5864         teardown_ewmh();
5865         bar_extra_stop();
5866         XFreeGC(display, bar_gc);
5867         XCloseDisplay(display);
5868
5869         return (0);
5870 }