JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
958f6523bda10802532be38d834fb73a554dccba
[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 #ifdef SWM_DEBUG
105 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while (0)
106 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while (0)
107 #define SWM_D_MISC              0x0001
108 #define SWM_D_EVENT             0x0002
109 #define SWM_D_WS                0x0004
110 #define SWM_D_FOCUS             0x0008
111 #define SWM_D_MOVE              0x0010
112 #define SWM_D_STACK             0x0020
113 #define SWM_D_MOUSE             0x0040
114 #define SWM_D_PROP              0x0080
115 #define SWM_D_CLASS             0x0100
116 #define SWM_D_KEY               0x0200
117 #define SWM_D_QUIRK             0x0400
118 #define SWM_D_SPAWN             0x0800
119 #define SWM_D_EVENTQ            0x1000
120 #define SWM_D_CONF              0x2000
121
122 u_int32_t               swm_debug = 0
123                             | SWM_D_MISC
124                             | SWM_D_EVENT
125                             | SWM_D_WS
126                             | SWM_D_FOCUS
127                             | SWM_D_MOVE
128                             | SWM_D_STACK
129                             | SWM_D_MOUSE
130                             | SWM_D_PROP
131                             | SWM_D_CLASS
132                             | SWM_D_KEY
133                             | SWM_D_QUIRK
134                             | SWM_D_SPAWN
135                             | SWM_D_EVENTQ
136                             | SWM_D_CONF
137                             ;
138 #else
139 #define DPRINTF(x...)
140 #define DNPRINTF(n,x...)
141 #endif
142
143 #define LENGTH(x)               (sizeof x / sizeof x[0])
144 #define MODKEY                  Mod1Mask
145 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
146 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
147 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
148 #define SWM_PROPLEN             (16)
149 #define SWM_FUNCNAME_LEN        (32)
150 #define SWM_KEYS_LEN            (255)
151 #define SWM_QUIRK_LEN           (64)
152 #define X(r)                    (r)->g.x
153 #define Y(r)                    (r)->g.y
154 #define WIDTH(r)                (r)->g.w
155 #define HEIGHT(r)               (r)->g.h
156 #define SWM_MAX_FONT_STEPS      (3)
157 #define WINID(w)                (w ? w->id : 0)
158
159 #define SWM_FOCUS_DEFAULT       (0)
160 #define SWM_FOCUS_SYNERGY       (1)
161 #define SWM_FOCUS_FOLLOW        (2)
162
163 #ifndef SWM_LIB
164 #define SWM_LIB                 "/usr/local/lib/libswmhack.so"
165 #endif
166
167 char                    **start_argv;
168 Atom                    astate;
169 Atom                    aprot;
170 Atom                    adelete;
171 Atom                    takefocus;
172 Atom                    a_wmname;
173 Atom                    a_utf8_string;
174 Atom                    a_string;
175 Atom                    a_swm_iconic;
176 volatile sig_atomic_t   running = 1;
177 volatile sig_atomic_t   restart_wm = 0;
178 int                     outputs = 0;
179 int                     last_focus_event = FocusOut;
180 int                     (*xerrorxlib)(Display *, XErrorEvent *);
181 int                     other_wm;
182 int                     ss_enabled = 0;
183 int                     xrandr_support;
184 int                     xrandr_eventbase;
185 unsigned int            numlockmask = 0;
186 Display                 *display;
187
188 int                     cycle_empty = 0;
189 int                     cycle_visible = 0;
190 int                     term_width = 0;
191 int                     font_adjusted = 0;
192 unsigned int            mod_key = MODKEY;
193
194 /* dmenu search */
195 struct swm_region       *search_r;
196 int                     select_list_pipe[2];
197 int                     select_resp_pipe[2];
198 pid_t                   searchpid;
199 volatile sig_atomic_t   search_resp;
200
201 /* dialog windows */
202 double                  dialog_ratio = .6;
203 /* status bar */
204 #define SWM_BAR_MAX     (256)
205 char                    *bar_argv[] = { NULL, NULL };
206 int                     bar_pipe[2];
207 char                    bar_ext[SWM_BAR_MAX];
208 char                    bar_vertext[SWM_BAR_MAX];
209 int                     bar_version = 0;
210 sig_atomic_t            bar_alarm = 0;
211 int                     bar_delay = 30;
212 int                     bar_enabled = 1;
213 int                     bar_border_width = 1;
214 int                     bar_at_bottom = 0;
215 int                     bar_extra = 1;
216 int                     bar_extra_running = 0;
217 int                     bar_verbose = 1;
218 int                     bar_height = 0;
219 int                     stack_enabled = 1;
220 int                     clock_enabled = 1;
221 char                    *clock_format = NULL;
222 int                     title_name_enabled = 0;
223 int                     title_class_enabled = 0;
224 int                     window_name_enabled = 0;
225 int                     focus_mode = SWM_FOCUS_DEFAULT;
226 int                     disable_border = 0;
227 int                     border_width = 1;
228 pid_t                   bar_pid;
229 GC                      bar_gc;
230 XGCValues               bar_gcv;
231 int                     bar_fidx = 0;
232 XFontStruct             *bar_fs;
233 char                    *bar_fonts[] = { NULL, NULL, NULL, NULL };/* XXX Make fully dynamic */
234 char                    *spawn_term[] = { NULL, NULL };         /* XXX Make fully dynamic */
235
236 #define SWM_MENU_FN     (2)
237 #define SWM_MENU_NB     (4)
238 #define SWM_MENU_NF     (6)
239 #define SWM_MENU_SB     (8)
240 #define SWM_MENU_SF     (10)
241
242 /* layout manager data */
243 struct swm_geometry {
244         int                     x;
245         int                     y;
246         int                     w;
247         int                     h;
248 };
249
250 struct swm_screen;
251 struct workspace;
252
253 /* virtual "screens" */
254 struct swm_region {
255         TAILQ_ENTRY(swm_region) entry;
256         struct swm_geometry     g;
257         struct workspace        *ws;    /* current workspace on this region */
258         struct workspace        *ws_prior; /* prior workspace on this region */
259         struct swm_screen       *s;     /* screen idx */
260         Window                  bar_window;
261 };
262 TAILQ_HEAD(swm_region_list, swm_region);
263
264 struct ws_win {
265         TAILQ_ENTRY(ws_win)     entry;
266         Window                  id;
267         Window                  transient;
268         struct ws_win           *child_trans;   /* transient child window */
269         struct swm_geometry     g;              /* current geometry */
270         struct swm_geometry     g_float;        /* geometry when floating */
271         struct swm_geometry     rg_float;       /* region geom when floating */
272         int                     g_floatvalid;   /* flag: geometry in g_float is valid */
273         int                     floatmaxed;     /* flag: floater was maxed in max_stack */
274         int                     floating;
275         int                     manual;
276         int                     iconic;
277         unsigned int            ewmh_flags;
278         int                     font_size_boundary[SWM_MAX_FONT_STEPS];
279         int                     font_steps;
280         int                     last_inc;
281         int                     can_delete;
282         int                     take_focus;
283         int                     java;
284         unsigned long           quirks;
285         struct workspace        *ws;    /* always valid */
286         struct swm_screen       *s;     /* always valid, never changes */
287         XWindowAttributes       wa;
288         XSizeHints              sh;
289         XClassHint              ch;
290         XWMHints                *hints;
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 drain_enter_notify(void)
1386 {
1387         int                     i = 0;
1388         XEvent                  cne;
1389
1390         while (XCheckMaskEvent(display, EnterWindowMask, &cne))
1391                 i++;
1392
1393         DNPRINTF(SWM_D_MISC, "drain_enter_notify: drained %d\n", i);
1394 }
1395
1396 void
1397 set_win_state(struct ws_win *win, long state)
1398 {
1399         long                    data[] = {state, None};
1400
1401         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1402
1403         if (win == NULL)
1404                 return;
1405
1406         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1407             (unsigned char *)data, 2);
1408 }
1409
1410 long
1411 getstate(Window w)
1412 {
1413         long                    result = -1;
1414         unsigned char           *p = NULL;
1415         unsigned long           n;
1416
1417         if (!get_property(w, astate, 2L, astate, &n, &p))
1418                 return (-1);
1419         if (n != 0)
1420                 result = *((long *)p);
1421         XFree(p);
1422         return (result);
1423 }
1424
1425 void
1426 version(struct swm_region *r, union arg *args)
1427 {
1428         bar_version = !bar_version;
1429         if (bar_version)
1430                 snprintf(bar_vertext, sizeof bar_vertext, "Version: %s CVS: %s",
1431                     SWM_VERSION, cvstag);
1432         else
1433                 strlcpy(bar_vertext, "", sizeof bar_vertext);
1434         bar_update();
1435 }
1436
1437 void
1438 client_msg(struct ws_win *win, Atom a)
1439 {
1440         XClientMessageEvent     cm;
1441
1442         if (win == NULL)
1443                 return;
1444
1445         bzero(&cm, sizeof cm);
1446         cm.type = ClientMessage;
1447         cm.window = win->id;
1448         cm.message_type = aprot;
1449         cm.format = 32;
1450         cm.data.l[0] = a;
1451         cm.data.l[1] = CurrentTime;
1452         XSendEvent(display, win->id, False, 0L, (XEvent *)&cm);
1453 }
1454
1455 void
1456 config_win(struct ws_win *win, XConfigureRequestEvent  *ev)
1457 {
1458         XConfigureEvent         ce;
1459
1460         if (win == NULL)
1461                 return;
1462
1463         if (ev == NULL) {
1464                 DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
1465                     win->id, win->g.x, win->g.y, win->g.w, win->g.h);
1466
1467                 ce.type = ConfigureNotify;
1468                 ce.display = display;
1469                 ce.event = win->id;
1470                 ce.window = win->id;
1471                 ce.x = win->g.x;
1472                 ce.y = win->g.y;
1473                 ce.width = win->g.w;
1474                 ce.height = win->g.h;
1475                 ce.border_width = border_width;
1476                 ce.above = None;
1477                 ce.override_redirect = False;
1478         } else {
1479                 DNPRINTF(SWM_D_MISC, "config_win: ev win %lu x %d y %d w %d h %d\n",
1480                     ev->window, ev->x, ev->y, ev->width, ev->height);
1481                 ce.type = ConfigureNotify;
1482                 ce.display = ev->display;
1483                 ce.event = ev->window;
1484                 ce.window = ev->window;
1485                 ce.x = ev->x;
1486                 ce.y = ev->y;
1487                 ce.width = ev->width;
1488                 ce.height = ev->height;
1489                 ce.border_width = ev->border_width;
1490                 ce.above = ev->above;
1491                 ce.override_redirect = False;
1492         }
1493
1494         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
1495 }
1496
1497 int
1498 count_win(struct workspace *ws, int count_transient)
1499 {
1500         struct ws_win           *win;
1501         int                     count = 0;
1502
1503         TAILQ_FOREACH(win, &ws->winlist, entry) {
1504                 if (count_transient == 0 && win->floating)
1505                         continue;
1506                 if (count_transient == 0 && win->transient)
1507                         continue;
1508                 if (win->iconic)
1509                         continue;
1510                 count++;
1511         }
1512         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
1513
1514         return (count);
1515 }
1516
1517 void
1518 quit(struct swm_region *r, union arg *args)
1519 {
1520         DNPRINTF(SWM_D_MISC, "quit\n");
1521         running = 0;
1522 }
1523
1524 void
1525 unmap_window(struct ws_win *win)
1526 {
1527         if (win == NULL)
1528                 return;
1529
1530         /* don't unmap again */
1531         if (getstate(win->id) == IconicState)
1532                 return;
1533
1534         set_win_state(win, IconicState);
1535
1536         XUnmapWindow(display, win->id);
1537         XSetWindowBorder(display, win->id,
1538             win->s->c[SWM_S_COLOR_UNFOCUS].color);
1539 }
1540
1541 void
1542 unmap_all(void)
1543 {
1544         struct ws_win           *win;
1545         int                     i, j;
1546
1547         for (i = 0; i < ScreenCount(display); i++)
1548                 for (j = 0; j < SWM_WS_MAX; j++)
1549                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1550                                 unmap_window(win);
1551 }
1552
1553 void
1554 fake_keypress(struct ws_win *win, int keysym, int modifiers)
1555 {
1556         XKeyEvent event;
1557
1558         if (win == NULL)
1559                 return;
1560
1561         event.display = display;        /* Ignored, but what the hell */
1562         event.window = win->id;
1563         event.root = win->s->root;
1564         event.subwindow = None;
1565         event.time = CurrentTime;
1566         event.x = win->g.x;
1567         event.y = win->g.y;
1568         event.x_root = 1;
1569         event.y_root = 1;
1570         event.same_screen = True;
1571         event.keycode = XKeysymToKeycode(display, keysym);
1572         event.state = modifiers;
1573
1574         event.type = KeyPress;
1575         XSendEvent(event.display, event.window, True,
1576             KeyPressMask, (XEvent *)&event);
1577
1578         event.type = KeyRelease;
1579         XSendEvent(event.display, event.window, True,
1580             KeyPressMask, (XEvent *)&event);
1581
1582 }
1583
1584 void
1585 restart(struct swm_region *r, union arg *args)
1586 {
1587         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
1588
1589         /* disable alarm because the following code may not be interrupted */
1590         alarm(0);
1591         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
1592                 errx(1, "can't disable alarm");
1593
1594         bar_extra_stop();
1595         bar_extra = 1;
1596         unmap_all();
1597         XCloseDisplay(display);
1598         execvp(start_argv[0], start_argv);
1599         fprintf(stderr, "execvp failed\n");
1600         perror(" failed");
1601         quit(NULL, NULL);
1602 }
1603
1604 struct swm_region *
1605 root_to_region(Window root)
1606 {
1607         struct swm_region       *r = NULL;
1608         Window                  rr, cr;
1609         int                     i, x, y, wx, wy;
1610         unsigned int            mask;
1611
1612         for (i = 0; i < ScreenCount(display); i++)
1613                 if (screens[i].root == root)
1614                         break;
1615
1616         if (XQueryPointer(display, screens[i].root,
1617             &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
1618                 /* choose a region based on pointer location */
1619                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1620                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
1621                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
1622                                 break;
1623         }
1624
1625         if (r == NULL)
1626                 r = TAILQ_FIRST(&screens[i].rl);
1627
1628         return (r);
1629 }
1630
1631 struct ws_win *
1632 find_unmanaged_window(Window id)
1633 {
1634         struct ws_win           *win;
1635         int                     i, j;
1636
1637         for (i = 0; i < ScreenCount(display); i++)
1638                 for (j = 0; j < SWM_WS_MAX; j++)
1639                         TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
1640                             entry)
1641                                 if (id == win->id)
1642                                         return (win);
1643         return (NULL);
1644 }
1645
1646 struct ws_win *
1647 find_window(Window id)
1648 {
1649         struct ws_win           *win;
1650         Window                  wrr, wpr, *wcr = NULL;
1651         int                     i, j;
1652         unsigned int            nc;
1653
1654         for (i = 0; i < ScreenCount(display); i++)
1655                 for (j = 0; j < SWM_WS_MAX; j++)
1656                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1657                                 if (id == win->id)
1658                                         return (win);
1659
1660         /* if we were looking for the parent return that window instead */
1661         if (XQueryTree(display, id, &wrr, &wpr, &wcr, &nc) == 0)
1662                 return (NULL);
1663         if (wcr)
1664                 XFree(wcr);
1665
1666         /* ignore not found and root */
1667         if (wpr == 0 || wrr == wpr)
1668                 return (NULL);
1669
1670         /* look for parent */
1671         for (i = 0; i < ScreenCount(display); i++)
1672                 for (j = 0; j < SWM_WS_MAX; j++)
1673                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1674                                 if (wpr == win->id)
1675                                         return (win);
1676
1677         return (NULL);
1678 }
1679
1680 void
1681 spawn(struct swm_region *r, union arg *args, int close_fd)
1682 {
1683         int                     fd;
1684         char                    *ret = NULL;
1685
1686         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
1687
1688         if (display)
1689                 close(ConnectionNumber(display));
1690
1691         setenv("LD_PRELOAD", SWM_LIB, 1);
1692
1693         if (asprintf(&ret, "%d", r->ws->idx) == -1) {
1694                 perror("_SWM_WS");
1695                 _exit(1);
1696         }
1697         setenv("_SWM_WS", ret, 1);
1698         free(ret);
1699         ret = NULL;
1700
1701         if (asprintf(&ret, "%d", getpid()) == -1) {
1702                 perror("_SWM_PID");
1703                 _exit(1);
1704         }
1705         setenv("_SWM_PID", ret, 1);
1706         free(ret);
1707         ret = NULL;
1708
1709         if (setsid() == -1) {
1710                 perror("setsid");
1711                 _exit(1);
1712         }
1713
1714         if (close_fd) {
1715                 /*
1716                  * close stdin and stdout to prevent interaction between apps
1717                  * and the baraction script
1718                  * leave stderr open to record errors
1719                 */
1720                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
1721                         perror("open");
1722                         _exit(1);
1723                 }
1724                 dup2(fd, STDIN_FILENO);
1725                 dup2(fd, STDOUT_FILENO);
1726                 if (fd > 2)
1727                         close(fd);
1728         }
1729
1730         execvp(args->argv[0], args->argv);
1731
1732         perror("execvp");
1733         _exit(1);
1734 }
1735
1736 void
1737 spawnterm(struct swm_region *r, union arg *args)
1738 {
1739         DNPRINTF(SWM_D_MISC, "spawnterm\n");
1740
1741         if (term_width)
1742                 setenv("_SWM_XTERM_FONTADJ", "", 1);
1743         if (fork() == 0)
1744                 spawn(r, args, 1);
1745 }
1746
1747 void
1748 kill_refs(struct ws_win *win)
1749 {
1750         int                     i, x;
1751         struct swm_region       *r;
1752         struct workspace        *ws;
1753
1754         if (win == NULL)
1755                 return;
1756
1757         for (i = 0; i < ScreenCount(display); i++)
1758                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1759                         for (x = 0; x < SWM_WS_MAX; x++) {
1760                                 ws = &r->s->ws[x];
1761                                 if (win == ws->focus)
1762                                         ws->focus = NULL;
1763                                 if (win == ws->focus_prev)
1764                                         ws->focus_prev = NULL;
1765                         }
1766 }
1767
1768 int
1769 validate_win(struct ws_win *testwin)
1770 {
1771         struct ws_win           *win;
1772         struct workspace        *ws;
1773         struct swm_region       *r;
1774         int                     i, x, foundit = 0;
1775
1776         if (testwin == NULL)
1777                 return(0);
1778
1779         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1780                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1781                         for (x = 0; x < SWM_WS_MAX; x++) {
1782                                 ws = &r->s->ws[x];
1783                                 TAILQ_FOREACH(win, &ws->winlist, entry)
1784                                         if (win == testwin)
1785                                                 return (0);
1786                         }
1787         return (1);
1788 }
1789
1790 int
1791 validate_ws(struct workspace *testws)
1792 {
1793         struct swm_region       *r;
1794         struct workspace        *ws;
1795         int                     foundit, i, x;
1796
1797         /* validate all ws */
1798         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1799                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1800                         for (x = 0; x < SWM_WS_MAX; x++) {
1801                                 ws = &r->s->ws[x];
1802                                 if (ws == testws)
1803                                         return (0);
1804                         }
1805         return (1);
1806 }
1807
1808 void
1809 unfocus_win(struct ws_win *win)
1810 {
1811         XEvent                  cne;
1812         Window                  none = None;
1813
1814         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", WINID(win));
1815
1816         if (win == NULL)
1817                 return;
1818         if (win->ws == NULL)
1819                 return;
1820
1821         if (validate_ws(win->ws))
1822                 return; /* XXX this gets hit with thunderbird, needs fixing */
1823
1824         if (win->ws->r == NULL)
1825                 return;
1826
1827         if (validate_win(win)) {
1828                 kill_refs(win);
1829                 return;
1830         }
1831
1832         if (win->ws->focus == win) {
1833                 win->ws->focus = NULL;
1834                 win->ws->focus_prev = win;
1835         }
1836
1837         if (validate_win(win->ws->focus)) {
1838                 kill_refs(win->ws->focus);
1839                 win->ws->focus = NULL;
1840         }
1841         if (validate_win(win->ws->focus_prev)) {
1842                 kill_refs(win->ws->focus_prev);
1843                 win->ws->focus_prev = NULL;
1844         }
1845
1846         /* drain all previous unfocus events */
1847         while (XCheckTypedEvent(display, FocusOut, &cne) == True)
1848                 ;
1849
1850         grabbuttons(win, 0);
1851         XSetWindowBorder(display, win->id,
1852             win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1853
1854         XChangeProperty(display, win->s->root,
1855             ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1856             PropModeReplace, (unsigned char *)&none,1);
1857 }
1858
1859 void
1860 unfocus_all(void)
1861 {
1862         struct ws_win           *win;
1863         int                     i, j;
1864
1865         DNPRINTF(SWM_D_FOCUS, "unfocus_all\n");
1866
1867         for (i = 0; i < ScreenCount(display); i++)
1868                 for (j = 0; j < SWM_WS_MAX; j++)
1869                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1870                                 unfocus_win(win);
1871 }
1872
1873 void
1874 focus_win(struct ws_win *win)
1875 {
1876         XEvent                  cne;
1877         Window                  cur_focus;
1878         int                     rr;
1879         struct ws_win           *cfw = NULL;
1880
1881
1882         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
1883
1884         if (win == NULL)
1885                 return;
1886         if (win->ws == NULL)
1887                 return;
1888
1889         if (validate_ws(win->ws))
1890                 return; /* XXX this gets hit with thunderbird, needs fixing */
1891
1892         if (validate_win(win)) {
1893                 kill_refs(win);
1894                 return;
1895         }
1896
1897         if (validate_win(win)) {
1898                 kill_refs(win);
1899                 return;
1900         }
1901
1902         XGetInputFocus(display, &cur_focus, &rr);
1903         if ((cfw = find_window(cur_focus)) != NULL)
1904                 unfocus_win(cfw);
1905
1906         win->ws->focus = win;
1907
1908         if (win->ws->r != NULL) {
1909                 /* drain all previous focus events */
1910                 while (XCheckTypedEvent(display, FocusIn, &cne) == True)
1911                         ;
1912
1913                 if (win->java == 0)
1914                         XSetInputFocus(display, win->id,
1915                             RevertToParent, CurrentTime);
1916                 XMapRaised(display, win->id);
1917                 grabbuttons(win, 1);
1918                 XSetWindowBorder(display, win->id,
1919                     win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
1920                 if (win->ws->cur_layout->flags & SWM_L_MAPONFOCUS)
1921                         XMapRaised(display, win->id);
1922
1923                 XChangeProperty(display, win->s->root,
1924                     ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1925                     PropModeReplace, (unsigned char *)&win->id,1);
1926         }
1927
1928         if (window_name_enabled)
1929                 bar_update();
1930 }
1931
1932 void
1933 switchws(struct swm_region *r, union arg *args)
1934 {
1935         int                     wsid = args->id, unmap_old = 0;
1936         struct swm_region       *this_r, *other_r;
1937         struct ws_win           *win;
1938         struct workspace        *new_ws, *old_ws;
1939         union arg               a;
1940
1941         if (!(r && r->s))
1942                 return;
1943
1944         this_r = r;
1945         old_ws = this_r->ws;
1946         new_ws = &this_r->s->ws[wsid];
1947
1948         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
1949             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
1950             old_ws->idx, wsid);
1951
1952         if (new_ws == NULL || old_ws == NULL)
1953                 return;
1954         if (new_ws == old_ws)
1955                 return;
1956
1957         other_r = new_ws->r;
1958         if (other_r == NULL) {
1959                 /* the other workspace is hidden, hide this one */
1960                 old_ws->r = NULL;
1961                 unmap_old = 1;
1962         } else {
1963                 /* the other ws is visible in another region, exchange them */
1964                 other_r->ws_prior = new_ws;
1965                 other_r->ws = old_ws;
1966                 old_ws->r = other_r;
1967         }
1968         this_r->ws_prior = old_ws;
1969         this_r->ws = new_ws;
1970         new_ws->r = this_r;
1971
1972         stack();
1973         a.id = SWM_ARG_ID_FOCUSCUR;
1974         focus(new_ws->r, &a);
1975
1976         bar_update();
1977
1978         /* unmap old windows */
1979         if (unmap_old)
1980                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
1981                         unmap_window(win);
1982
1983         if (focus_mode == SWM_FOCUS_DEFAULT)
1984                 drain_enter_notify();
1985 }
1986
1987 void
1988 cyclews(struct swm_region *r, union arg *args)
1989 {
1990         union                   arg a;
1991         struct swm_screen       *s = r->s;
1992
1993         DNPRINTF(SWM_D_WS, "cyclews id %d "
1994             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
1995             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1996
1997         a.id = r->ws->idx;
1998         do {
1999                 switch (args->id) {
2000                 case SWM_ARG_ID_CYCLEWS_UP:
2001                         if (a.id < SWM_WS_MAX - 1)
2002                                 a.id++;
2003                         else
2004                                 a.id = 0;
2005                         break;
2006                 case SWM_ARG_ID_CYCLEWS_DOWN:
2007                         if (a.id > 0)
2008                                 a.id--;
2009                         else
2010                                 a.id = SWM_WS_MAX - 1;
2011                         break;
2012                 default:
2013                         return;
2014                 };
2015
2016                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
2017                         continue;
2018                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
2019                         continue;
2020
2021                 switchws(r, &a);
2022         } while (a.id != r->ws->idx);
2023 }
2024
2025 void
2026 priorws(struct swm_region *r, union arg *args)
2027 {
2028         union arg               a;
2029
2030         DNPRINTF(SWM_D_WS, "priorws id %d "
2031             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
2032             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2033
2034         if (r->ws_prior == NULL)
2035                 return;
2036
2037         a.id = r->ws_prior->idx;
2038         switchws(r, &a);
2039 }
2040
2041 void
2042 cyclescr(struct swm_region *r, union arg *args)
2043 {
2044         struct swm_region       *rr = NULL;
2045         union arg               a;
2046         int                     i, x, y;
2047
2048         /* do nothing if we don't have more than one screen */
2049         if (!(ScreenCount(display) > 1 || outputs > 1))
2050                 return;
2051
2052         i = r->s->idx;
2053         switch (args->id) {
2054         case SWM_ARG_ID_CYCLESC_UP:
2055                 rr = TAILQ_NEXT(r, entry);
2056                 if (rr == NULL)
2057                         rr = TAILQ_FIRST(&screens[i].rl);
2058                 break;
2059         case SWM_ARG_ID_CYCLESC_DOWN:
2060                 rr = TAILQ_PREV(r, swm_region_list, entry);
2061                 if (rr == NULL)
2062                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2063                 break;
2064         default:
2065                 return;
2066         };
2067         if (rr == NULL)
2068                 return;
2069
2070         /* move mouse to region */
2071         x = rr->g.x + 1;
2072         y = rr->g.y + 1 + (bar_enabled ? bar_height : 0);
2073         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2074
2075         a.id = SWM_ARG_ID_FOCUSCUR;
2076         focus(rr, &a);
2077
2078         if (rr->ws->focus) {
2079                 /* move to focus window */
2080                 x = rr->ws->focus->g.x + 1;
2081                 y = rr->ws->focus->g.y + 1;
2082                 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2083         }
2084 }
2085
2086 void
2087 sort_windows(struct ws_win_list *wl)
2088 {
2089         struct ws_win           *win, *parent, *nxt;
2090
2091         if (wl == NULL)
2092                 return;
2093
2094         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
2095                 nxt = TAILQ_NEXT(win, entry);
2096                 if (win->transient) {
2097                         parent = find_window(win->transient);
2098                         if (parent == NULL) {
2099                                 fprintf(stderr, "not possible bug\n");
2100                                 continue;
2101                         }
2102                         TAILQ_REMOVE(wl, win, entry);
2103                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
2104                 }
2105         }
2106
2107 }
2108
2109 void
2110 swapwin(struct swm_region *r, union arg *args)
2111 {
2112         struct ws_win           *target, *source;
2113         struct ws_win           *cur_focus;
2114         struct ws_win_list      *wl;
2115
2116
2117         DNPRINTF(SWM_D_WS, "swapwin id %d "
2118             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
2119             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2120
2121         cur_focus = r->ws->focus;
2122         if (cur_focus == NULL)
2123                 return;
2124
2125         source = cur_focus;
2126         wl = &source->ws->winlist;
2127
2128         switch (args->id) {
2129         case SWM_ARG_ID_SWAPPREV:
2130                 if (source->transient)
2131                         source = find_window(source->transient);
2132                 target = TAILQ_PREV(source, ws_win_list, entry);
2133                 if (target && target->transient)
2134                         target = find_window(target->transient);
2135                 TAILQ_REMOVE(wl, source, entry);
2136                 if (target == NULL)
2137                         TAILQ_INSERT_TAIL(wl, source, entry);
2138                 else
2139                         TAILQ_INSERT_BEFORE(target, source, entry);
2140                 break;
2141         case SWM_ARG_ID_SWAPNEXT:
2142                 target = TAILQ_NEXT(source, entry);
2143                 /* move the parent and let the sort handle the move */
2144                 if (source->transient)
2145                         source = find_window(source->transient);
2146                 TAILQ_REMOVE(wl, source, entry);
2147                 if (target == NULL)
2148                         TAILQ_INSERT_HEAD(wl, source, entry);
2149                 else
2150                         TAILQ_INSERT_AFTER(wl, target, source, entry);
2151                 break;
2152         case SWM_ARG_ID_SWAPMAIN:
2153                 target = TAILQ_FIRST(wl);
2154                 if (target == source) {
2155                         if (source->ws->focus_prev != NULL &&
2156                             source->ws->focus_prev != target)
2157
2158                                 source = source->ws->focus_prev;
2159                         else
2160                                 return;
2161                 }
2162                 if (target == NULL || source == NULL)
2163                         return;
2164                 source->ws->focus_prev = target;
2165                 TAILQ_REMOVE(wl, target, entry);
2166                 TAILQ_INSERT_BEFORE(source, target, entry);
2167                 TAILQ_REMOVE(wl, source, entry);
2168                 TAILQ_INSERT_HEAD(wl, source, entry);
2169                 break;
2170         case SWM_ARG_ID_MOVELAST:
2171                 TAILQ_REMOVE(wl, source, entry);
2172                 TAILQ_INSERT_TAIL(wl, source, entry);
2173                 break;
2174         default:
2175                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
2176                 return;
2177         }
2178
2179         sort_windows(wl);
2180
2181         stack();
2182 }
2183
2184 void
2185 focus_prev(struct ws_win *win)
2186 {
2187         struct ws_win           *winfocus = NULL, *winlostfocus = NULL;
2188         struct ws_win           *cur_focus = NULL;
2189         struct ws_win_list      *wl = NULL;
2190         struct workspace        *ws = NULL;
2191
2192         DNPRINTF(SWM_D_FOCUS, "focus_prev: id %lu\n", WINID(win));
2193
2194         if (!(win && win->ws))
2195                 return;
2196
2197         ws = win->ws;
2198         wl = &ws->winlist;
2199         cur_focus = ws->focus;
2200         winlostfocus = cur_focus;
2201
2202         /* pickle, just focus on whatever */
2203         if (cur_focus == NULL) {
2204                 /* use prev_focus if valid */
2205                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
2206                     find_window(WINID(ws->focus_prev)))
2207                         winfocus = ws->focus_prev;
2208                 if (winfocus == NULL)
2209                         winfocus = TAILQ_FIRST(wl);
2210                 goto done;
2211         }
2212
2213         /* if transient focus on parent */
2214         if (cur_focus->transient) {
2215                 winfocus = find_window(cur_focus->transient);
2216                 goto done;
2217         }
2218
2219         /* if in max_stack try harder */
2220         if (ws->cur_layout->flags & SWM_L_FOCUSPREV) {
2221                 if (cur_focus != ws->focus_prev)
2222                         winfocus = ws->focus_prev;
2223                 else if (cur_focus != ws->focus)
2224                         winfocus = ws->focus;
2225                 else
2226                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
2227                 if (winfocus)
2228                         goto done;
2229         }
2230
2231         if (cur_focus == win)
2232                 winfocus = TAILQ_PREV(win, ws_win_list, entry);
2233         if (winfocus == NULL)
2234                 winfocus = TAILQ_LAST(wl, ws_win_list);
2235         if (winfocus == NULL || winfocus == win)
2236                 winfocus = TAILQ_NEXT(cur_focus, entry);
2237 done:
2238         if (winfocus == winlostfocus || winfocus == NULL)
2239                 return;
2240
2241         focus_magic(winfocus);
2242 }
2243
2244 void
2245 focus(struct swm_region *r, union arg *args)
2246 {
2247         struct ws_win           *winfocus = NULL, *winlostfocus = NULL, *head;
2248         struct ws_win           *cur_focus = NULL;
2249         struct ws_win_list      *wl = NULL;
2250         struct workspace        *ws = NULL;
2251
2252         if (!(r && r->ws))
2253                 return;
2254
2255         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
2256
2257         /* treat FOCUS_CUR special */
2258         if (args->id == SWM_ARG_ID_FOCUSCUR) {
2259                 if (r->ws->focus && r->ws->focus->iconic == 0)
2260                         winfocus = r->ws->focus;
2261                 else if (r->ws->focus_prev && r->ws->focus_prev->iconic == 0)
2262                         winfocus = r->ws->focus_prev;
2263                 else
2264                         TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
2265                                 if (winfocus->iconic == 0)
2266                                         break;
2267
2268                 focus_magic(winfocus);
2269                 return;
2270         }
2271
2272         if ((cur_focus = r->ws->focus) == NULL)
2273                 return;
2274         ws = r->ws;
2275         wl = &ws->winlist;
2276
2277         winlostfocus = cur_focus;
2278
2279         switch (args->id) {
2280         case SWM_ARG_ID_FOCUSPREV:
2281                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
2282                 if (head == NULL)
2283                         head = TAILQ_LAST(wl, ws_win_list);
2284                 winfocus = head;
2285                 if (WINID(winfocus) == cur_focus->transient) {
2286                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
2287                         if (head == NULL)
2288                                 head = TAILQ_LAST(wl, ws_win_list);
2289                         winfocus = head;
2290                 }
2291
2292                 /* skip iconics */
2293                 if (winfocus && winfocus->iconic) {
2294                         TAILQ_FOREACH_REVERSE(winfocus, wl, ws_win_list, entry)
2295                                 if (winfocus->iconic == 0)
2296                                         break;
2297                 }
2298                 break;
2299
2300         case SWM_ARG_ID_FOCUSNEXT:
2301                 head = TAILQ_NEXT(cur_focus, entry);
2302                 if (head == NULL)
2303                         head = TAILQ_FIRST(wl);
2304                 winfocus = head;
2305
2306                 /* skip iconics */
2307                 if (winfocus && winfocus->iconic) {
2308                         TAILQ_FOREACH(winfocus, wl, entry)
2309                                 if (winfocus->iconic == 0)
2310                                         break;
2311                 }
2312                 break;
2313
2314         case SWM_ARG_ID_FOCUSMAIN:
2315                 winfocus = TAILQ_FIRST(wl);
2316                 if (winfocus == cur_focus)
2317                         winfocus = cur_focus->ws->focus_prev;
2318                 break;
2319
2320         default:
2321                 return;
2322         }
2323         if (winfocus == winlostfocus || winfocus == NULL)
2324                 return;
2325
2326         focus_magic(winfocus);
2327 }
2328
2329 void
2330 cycle_layout(struct swm_region *r, union arg *args)
2331 {
2332         struct workspace        *ws = r->ws;
2333         struct ws_win           *winfocus;
2334         union arg               a;
2335
2336         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
2337
2338         winfocus = ws->focus;
2339
2340         ws->cur_layout++;
2341         if (ws->cur_layout->l_stack == NULL)
2342                 ws->cur_layout = &layouts[0];
2343
2344         stack();
2345         a.id = SWM_ARG_ID_FOCUSCUR;
2346         focus(r, &a);
2347         bar_update();
2348 }
2349
2350 void
2351 stack_config(struct swm_region *r, union arg *args)
2352 {
2353         struct workspace        *ws = r->ws;
2354
2355         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
2356             args->id, ws->idx);
2357
2358         if (ws->cur_layout->l_config != NULL)
2359                 ws->cur_layout->l_config(ws, args->id);
2360
2361         if (args->id != SWM_ARG_ID_STACKINIT);
2362                 stack();
2363 }
2364
2365 void
2366 stack(void) {
2367         struct swm_geometry     g;
2368         struct swm_region       *r;
2369         int                     i, j;
2370
2371         DNPRINTF(SWM_D_STACK, "stack\n");
2372
2373         for (i = 0; i < ScreenCount(display); i++) {
2374                 j = 0;
2375                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2376                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
2377                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
2378
2379                         /* start with screen geometry, adjust for bar */
2380                         g = r->g;
2381                         g.w -= 2 * border_width;
2382                         g.h -= 2 * border_width;
2383                         if (bar_enabled) {
2384                                 if (!bar_at_bottom)
2385                                         g.y += bar_height;
2386                                 g.h -= bar_height;
2387                         }
2388                         r->ws->cur_layout->l_stack(r->ws, &g);
2389                         /* save r so we can track region changes */
2390                         r->ws->old_r = r;
2391                 }
2392         }
2393         if (font_adjusted)
2394                 font_adjusted--;
2395
2396         if (focus_mode == SWM_FOCUS_DEFAULT)
2397                 drain_enter_notify();
2398 }
2399
2400 void
2401 store_float_geom(struct ws_win *win, struct swm_region *r)
2402 {
2403         /* retain window geom and region geom */
2404         win->g_float.x = win->g.x;
2405         win->g_float.y = win->g.y;
2406         win->g_float.w = win->g.w;
2407         win->g_float.h = win->g.h;
2408         win->rg_float.x = r->g.x;
2409         win->rg_float.y = r->g.y;
2410         win->rg_float.w = r->g.w;
2411         win->rg_float.h = r->g.h;
2412         win->g_floatvalid = 1;
2413 }
2414
2415 void
2416 stack_floater(struct ws_win *win, struct swm_region *r)
2417 {
2418         unsigned int            mask;
2419         XWindowChanges          wc;
2420
2421         if (win == NULL)
2422                 return;
2423
2424         bzero(&wc, sizeof wc);
2425         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
2426
2427         /*
2428          * to allow windows to change their size (e.g. mplayer fs) only retrieve
2429          * geom on ws switches or return from max mode
2430          */
2431
2432         if (win->floatmaxed || (r != r->ws->old_r && win->g_floatvalid
2433             && !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
2434                 /*
2435                  * use stored g and rg to set relative position and size
2436                  * as in old region or before max stack mode
2437                  */
2438                 win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
2439                 win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
2440                 win->g.w = win->g_float.w;
2441                 win->g.h = win->g_float.h;
2442                 win->g_floatvalid = 0;
2443         }
2444
2445         win->floatmaxed = 0;
2446
2447         if ((win->quirks & SWM_Q_FULLSCREEN) && (win->g.w >= WIDTH(r)) &&
2448             (win->g.h >= HEIGHT(r)))
2449                 wc.border_width = 0;
2450         else
2451                 wc.border_width = border_width;
2452         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
2453                 win->g.w = (double)WIDTH(r) * dialog_ratio;
2454                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
2455         }
2456
2457         if (!win->manual) {
2458                 /*
2459                  * floaters and transients are auto-centred unless moved
2460                  * or resized
2461                  */
2462                 win->g.x = r->g.x + (WIDTH(r) - win->g.w) / 2 - wc.border_width;
2463                 win->g.y = r->g.y + (HEIGHT(r) - win->g.h) / 2 - wc.border_width;
2464         }
2465
2466         /* win can be outside r if new r smaller than old r */
2467         /* Ensure top left corner inside r (move probs otherwise) */
2468         if (win->g.x < r->g.x - wc.border_width)
2469                 win->g.x = r->g.x - wc.border_width;
2470         if (win->g.x > r->g.x + r->g.w - 1)
2471                 win->g.x = (win->g.w > r->g.w) ? r->g.x :
2472                     (r->g.x + r->g.w - win->g.w - 2 * wc.border_width);
2473         if (win->g.y < r->g.y - wc.border_width)
2474                 win->g.y = r->g.y - wc.border_width;
2475         if (win->g.y > r->g.y + r->g.h - 1)
2476                 win->g.y = (win->g.h > r->g.h) ? r->g.y :
2477                     (r->g.y + r->g.h - win->g.h - 2 * wc.border_width);
2478
2479         wc.x = win->g.x;
2480         wc.y = win->g.y;
2481         wc.width = win->g.w;
2482         wc.height = win->g.h;
2483
2484         /*
2485          * Retain floater and transient geometry for correct positioning
2486          * when ws changes region
2487          */
2488         if (!(win->ewmh_flags & EWMH_F_FULLSCREEN))
2489                 store_float_geom(win, r);
2490
2491         DNPRINTF(SWM_D_MISC, "stack_floater: win %lu x %d y %d w %d h %d\n",
2492             win->id, wc.x, wc.y, wc.width, wc.height);
2493
2494         XConfigureWindow(display, win->id, mask, &wc);
2495 }
2496
2497 /*
2498  * Send keystrokes to terminal to decrease/increase the font size as the
2499  * window size changes.
2500  */
2501 void
2502 adjust_font(struct ws_win *win)
2503 {
2504         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
2505             win->floating || win->transient)
2506                 return;
2507
2508         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
2509             win->g.w / win->sh.width_inc < term_width &&
2510             win->font_steps < SWM_MAX_FONT_STEPS) {
2511                 win->font_size_boundary[win->font_steps] =
2512                     (win->sh.width_inc * term_width) + win->sh.base_width;
2513                 win->font_steps++;
2514                 font_adjusted++;
2515                 win->last_inc = win->sh.width_inc;
2516                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
2517         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
2518             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
2519                 win->font_steps--;
2520                 font_adjusted++;
2521                 win->last_inc = win->sh.width_inc;
2522                 fake_keypress(win, XK_KP_Add, ShiftMask);
2523         }
2524 }
2525
2526 #define SWAPXY(g)       do {                            \
2527         int tmp;                                        \
2528         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
2529         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
2530 } while (0)
2531 void
2532 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
2533 {
2534         XWindowChanges          wc;
2535         XWindowAttributes       wa;
2536         struct swm_geometry     win_g, r_g = *g;
2537         struct ws_win           *win, *fs_win = 0;
2538         int                     i, j, s, stacks;
2539         int                     w_inc = 1, h_inc, w_base = 1, h_base;
2540         int                     hrh, extra = 0, h_slice, last_h = 0;
2541         int                     split, colno, winno, mwin, msize, mscale;
2542         int                     remain, missing, v_slice, reconfigure;
2543         unsigned int            mask;
2544
2545         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
2546             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
2547
2548         winno = count_win(ws, 0);
2549         if (winno == 0 && count_win(ws, 1) == 0)
2550                 return;
2551
2552         TAILQ_FOREACH(win, &ws->winlist, entry)
2553                 if (win->transient == 0 && win->floating == 0 && win->iconic == 0)
2554                         break;
2555
2556         if (win == NULL)
2557                 goto notiles;
2558
2559         if (rot) {
2560                 w_inc = win->sh.width_inc;
2561                 w_base = win->sh.base_width;
2562                 mwin = ws->l_state.horizontal_mwin;
2563                 mscale = ws->l_state.horizontal_msize;
2564                 stacks = ws->l_state.horizontal_stacks;
2565                 SWAPXY(&r_g);
2566         } else {
2567                 w_inc = win->sh.height_inc;
2568                 w_base = win->sh.base_height;
2569                 mwin = ws->l_state.vertical_mwin;
2570                 mscale = ws->l_state.vertical_msize;
2571                 stacks = ws->l_state.vertical_stacks;
2572         }
2573         win_g = r_g;
2574
2575         if (stacks > winno - mwin)
2576                 stacks = winno - mwin;
2577         if (stacks < 1)
2578                 stacks = 1;
2579
2580         h_slice = r_g.h / SWM_H_SLICE;
2581         if (mwin && winno > mwin) {
2582                 v_slice = r_g.w / SWM_V_SLICE;
2583
2584                 split = mwin;
2585                 colno = split;
2586                 win_g.w = v_slice * mscale;
2587
2588                 if (w_inc > 1 && w_inc < v_slice) {
2589                         /* adjust for window's requested size increment */
2590                         remain = (win_g.w - w_base) % w_inc;
2591                         missing = w_inc - remain;
2592                         win_g.w -= remain;
2593                         extra += remain;
2594                 }
2595
2596                 msize = win_g.w;
2597                 if (flip)
2598                         win_g.x += r_g.w - msize;
2599         } else {
2600                 msize = -2;
2601                 colno = split = winno / stacks;
2602                 win_g.w = ((r_g.w - (stacks * 2 * border_width) + 2 * border_width) / stacks);
2603         }
2604         hrh = r_g.h / colno;
2605         extra = r_g.h - (colno * hrh);
2606         win_g.h = hrh - 2 * border_width;
2607
2608         /*  stack all the tiled windows */
2609         i = j = 0, s = stacks;
2610         TAILQ_FOREACH(win, &ws->winlist, entry) {
2611                 if (win->transient != 0 || win->floating != 0)
2612                         continue;
2613                 if (win->iconic != 0)
2614                         continue;
2615
2616                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2617                         fs_win = win;
2618                         continue;
2619                 }
2620
2621                 if (split && i == split) {
2622                         colno = (winno - mwin) / stacks;
2623                         if (s <= (winno - mwin) % stacks)
2624                                 colno++;
2625                         split = split + colno;
2626                         hrh = (r_g.h / colno);
2627                         extra = r_g.h - (colno * hrh);
2628                         if (flip)
2629                                 win_g.x = r_g.x;
2630                         else
2631                                 win_g.x += win_g.w + 2 * border_width;
2632                         win_g.w = (r_g.w - msize - (stacks * 2 * border_width)) / stacks;
2633                         if (s == 1)
2634                                 win_g.w += (r_g.w - msize - (stacks * 2 * border_width)) %
2635                                     stacks;
2636                         s--;
2637                         j = 0;
2638                 }
2639                 win_g.h = hrh - 2 * border_width;
2640                 if (rot) {
2641                         h_inc = win->sh.width_inc;
2642                         h_base = win->sh.base_width;
2643                 } else {
2644                         h_inc = win->sh.height_inc;
2645                         h_base = win->sh.base_height;
2646                 }
2647                 if (j == colno - 1) {
2648                         win_g.h = hrh + extra;
2649                 } else if (h_inc > 1 && h_inc < h_slice) {
2650                         /* adjust for window's requested size increment */
2651                         remain = (win_g.h - h_base) % h_inc;
2652                         missing = h_inc - remain;
2653
2654                         if (missing <= extra || j == 0) {
2655                                 extra -= missing;
2656                                 win_g.h += missing;
2657                         } else {
2658                                 win_g.h -= remain;
2659                                 extra += remain;
2660                         }
2661                 }
2662
2663                 if (j == 0)
2664                         win_g.y = r_g.y;
2665                 else
2666                         win_g.y += last_h + 2 * border_width;
2667
2668                 bzero(&wc, sizeof wc);
2669                 if (disable_border && bar_enabled == 0 && winno == 1){
2670                         wc.border_width = 0;
2671                         win_g.w += 2 * border_width;
2672                         win_g.h += 2 * border_width;
2673                 } else
2674                         wc.border_width = border_width;
2675                 reconfigure = 0;
2676                 if (rot) {
2677                         if (win->g.x != win_g.y || win->g.y != win_g.x ||
2678                             win->g.w != win_g.h || win->g.h != win_g.w) {
2679                                 reconfigure = 1;
2680                                 win->g.x = wc.x = win_g.y;
2681                                 win->g.y = wc.y = win_g.x;
2682                                 win->g.w = wc.width = win_g.h;
2683                                 win->g.h = wc.height = win_g.w;
2684                         }
2685                 } else {
2686                         if (win->g.x != win_g.x || win->g.y != win_g.y ||
2687                             win->g.w != win_g.w || win->g.h != win_g.h) {
2688                                 reconfigure = 1;
2689                                 win->g.x = wc.x = win_g.x;
2690                                 win->g.y = wc.y = win_g.y;
2691                                 win->g.w = wc.width = win_g.w;
2692                                 win->g.h = wc.height = win_g.h;
2693                         }
2694                 }
2695                 if (reconfigure) {
2696                         adjust_font(win);
2697                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2698                         XConfigureWindow(display, win->id, mask, &wc);
2699                 }
2700
2701                 if (XGetWindowAttributes(display, win->id, &wa))
2702                         if (wa.map_state == IsUnmapped)
2703                                 XMapRaised(display, win->id);
2704
2705                 last_h = win_g.h;
2706                 i++;
2707                 j++;
2708         }
2709
2710 notiles:
2711         /* now, stack all the floaters and transients */
2712         TAILQ_FOREACH(win, &ws->winlist, entry) {
2713                 if (win->transient == 0 && win->floating == 0)
2714                         continue;
2715                 if (win->iconic == 1)
2716                         continue;
2717                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2718                         fs_win = win;
2719                         continue;
2720                 }
2721
2722                 stack_floater(win, ws->r);
2723                 XMapRaised(display, win->id);
2724         }
2725
2726         if (fs_win) {
2727                 stack_floater(fs_win, ws->r);
2728                 XMapRaised(display, fs_win->id);
2729         }
2730 }
2731
2732 void
2733 vertical_config(struct workspace *ws, int id)
2734 {
2735         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
2736
2737         switch (id) {
2738         case SWM_ARG_ID_STACKRESET:
2739         case SWM_ARG_ID_STACKINIT:
2740                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
2741                 ws->l_state.vertical_mwin = 1;
2742                 ws->l_state.vertical_stacks = 1;
2743                 break;
2744         case SWM_ARG_ID_MASTERSHRINK:
2745                 if (ws->l_state.vertical_msize > 1)
2746                         ws->l_state.vertical_msize--;
2747                 break;
2748         case SWM_ARG_ID_MASTERGROW:
2749                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
2750                         ws->l_state.vertical_msize++;
2751                 break;
2752         case SWM_ARG_ID_MASTERADD:
2753                 ws->l_state.vertical_mwin++;
2754                 break;
2755         case SWM_ARG_ID_MASTERDEL:
2756                 if (ws->l_state.vertical_mwin > 0)
2757                         ws->l_state.vertical_mwin--;
2758                 break;
2759         case SWM_ARG_ID_STACKINC:
2760                 ws->l_state.vertical_stacks++;
2761                 break;
2762         case SWM_ARG_ID_STACKDEC:
2763                 if (ws->l_state.vertical_stacks > 1)
2764                         ws->l_state.vertical_stacks--;
2765                 break;
2766         default:
2767                 return;
2768         }
2769 }
2770
2771 void
2772 vertical_stack(struct workspace *ws, struct swm_geometry *g)
2773 {
2774         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
2775
2776         stack_master(ws, g, 0, 0);
2777 }
2778
2779 void
2780 horizontal_config(struct workspace *ws, int id)
2781 {
2782         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
2783
2784         switch (id) {
2785         case SWM_ARG_ID_STACKRESET:
2786         case SWM_ARG_ID_STACKINIT:
2787                 ws->l_state.horizontal_mwin = 1;
2788                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
2789                 ws->l_state.horizontal_stacks = 1;
2790                 break;
2791         case SWM_ARG_ID_MASTERSHRINK:
2792                 if (ws->l_state.horizontal_msize > 1)
2793                         ws->l_state.horizontal_msize--;
2794                 break;
2795         case SWM_ARG_ID_MASTERGROW:
2796                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
2797                         ws->l_state.horizontal_msize++;
2798                 break;
2799         case SWM_ARG_ID_MASTERADD:
2800                 ws->l_state.horizontal_mwin++;
2801                 break;
2802         case SWM_ARG_ID_MASTERDEL:
2803                 if (ws->l_state.horizontal_mwin > 0)
2804                         ws->l_state.horizontal_mwin--;
2805                 break;
2806         case SWM_ARG_ID_STACKINC:
2807                 ws->l_state.horizontal_stacks++;
2808                 break;
2809         case SWM_ARG_ID_STACKDEC:
2810                 if (ws->l_state.horizontal_stacks > 1)
2811                         ws->l_state.horizontal_stacks--;
2812                 break;
2813         default:
2814                 return;
2815         }
2816 }
2817
2818 void
2819 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
2820 {
2821         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
2822
2823         stack_master(ws, g, 1, 0);
2824 }
2825
2826 /* fullscreen view */
2827 void
2828 max_stack(struct workspace *ws, struct swm_geometry *g)
2829 {
2830         XWindowChanges          wc;
2831         struct swm_geometry     gg = *g;
2832         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
2833         unsigned int            mask;
2834         int                     winno;
2835
2836         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
2837
2838         if (ws == NULL)
2839                 return;
2840
2841         winno = count_win(ws, 0);
2842         if (winno == 0 && count_win(ws, 1) == 0)
2843                 return;
2844
2845         TAILQ_FOREACH(win, &ws->winlist, entry) {
2846                 if (win->transient) {
2847                         wintrans = win;
2848                         parent = find_window(win->transient);
2849                         continue;
2850                 }
2851
2852                 if (win->floating && win->floatmaxed == 0 ) {
2853                         /*
2854                          * retain geometry for retrieval on exit from
2855                          * max_stack mode
2856                          */
2857                         store_float_geom(win, ws->r);
2858                         win->floatmaxed = 1;
2859                 }
2860
2861                 /* only reconfigure if necessary */
2862                 if (win->g.x != gg.x || win->g.y != gg.y || win->g.w != gg.w ||
2863                     win->g.h != gg.h) {
2864                         bzero(&wc, sizeof wc);
2865                         win->g.x = wc.x = gg.x;
2866                         win->g.y = wc.y = gg.y;
2867                         if (bar_enabled){
2868                                 wc.border_width = border_width;
2869                                 win->g.w = wc.width = gg.w;
2870                                 win->g.h = wc.height = gg.h;
2871                         } else {
2872                                 wc.border_width = 0;
2873                                 win->g.w = wc.width = gg.w + 2 * border_width;
2874                                 win->g.h = wc.height = gg.h + 2 * border_width;
2875                         }
2876                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2877                         XConfigureWindow(display, win->id, mask, &wc);
2878                 }
2879                 /* unmap only if we don't have multi screen */
2880                 if (win != ws->focus)
2881                         if (!(ScreenCount(display) > 1 || outputs > 1))
2882                                 unmap_window(win);
2883         }
2884
2885         /* put the last transient on top */
2886         if (wintrans) {
2887                 if (parent)
2888                         XMapRaised(display, parent->id);
2889                 stack_floater(wintrans, ws->r);
2890                 focus_magic(wintrans);
2891         }
2892 }
2893
2894 void
2895 send_to_ws(struct swm_region *r, union arg *args)
2896 {
2897         int                     wsid = args->id;
2898         struct ws_win           *win = NULL, *parent;
2899         struct workspace        *ws, *nws;
2900         Atom                    ws_idx_atom = 0;
2901         unsigned char           ws_idx_str[SWM_PROPLEN];
2902         union arg               a;
2903
2904         if (r && r->ws)
2905                 win = r->ws->focus;
2906         else
2907                 return;
2908         if (win == NULL)
2909                 return;
2910         if (win->ws->idx == wsid)
2911                 return;
2912
2913         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
2914
2915         ws = win->ws;
2916         nws = &win->s->ws[wsid];
2917
2918         a.id = SWM_ARG_ID_FOCUSPREV;
2919         focus(r, &a);
2920         if (win->transient) {
2921                 parent = find_window(win->transient);
2922                 if (parent) {
2923                         unmap_window(parent);
2924                         TAILQ_REMOVE(&ws->winlist, parent, entry);
2925                         TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
2926                         parent->ws = nws;
2927                 }
2928         }
2929         unmap_window(win);
2930         TAILQ_REMOVE(&ws->winlist, win, entry);
2931         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
2932         win->ws = nws;
2933
2934         /* Try to update the window's workspace property */
2935         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2936         if (ws_idx_atom &&
2937             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
2938                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2939                     ws_idx_str);
2940                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2941                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2942         }
2943
2944         stack();
2945 }
2946
2947 void
2948 iconify(struct swm_region *r, union arg *args)
2949 {
2950         union arg a;
2951
2952         if (r->ws->focus == NULL)
2953                 return;
2954         unmap_window(r->ws->focus);
2955         update_iconic(r->ws->focus, 1);
2956         stack();
2957         r->ws->focus = NULL;
2958         a.id = SWM_ARG_ID_FOCUSCUR;
2959         focus(r, &a);
2960 }
2961
2962 unsigned char *
2963 get_win_name(Display *dpy, Window win, Atom wname, Atom stype,
2964     unsigned long *slen)
2965 {
2966         int                     status, retfmt;
2967         unsigned long           nitems, nbytes, nextra;
2968         unsigned char           *prop = NULL;
2969         Atom                    rettype;
2970
2971         status = XGetWindowProperty(dpy, win, wname, 0L, 0L, False, stype,
2972             &rettype, &retfmt,  &nitems, &nbytes, &prop);
2973         if (status != Success)
2974                 return (NULL);
2975         XFree(prop);
2976
2977         status = XGetWindowProperty(dpy, win, wname, 0L, nbytes, False,
2978             stype, &rettype, &retfmt, &nitems, &nextra, &prop);
2979         if (status != Success) {
2980                 XFree(prop);
2981                 return (NULL);
2982         }
2983         if (rettype != stype) {
2984                 XFree(prop);
2985                 return (NULL);
2986         }
2987         *slen = nitems;
2988         return (prop);
2989 }
2990
2991 void
2992 uniconify(struct swm_region *r, union arg *args)
2993 {
2994         struct ws_win           *win;
2995         FILE                    *lfile;
2996         char                    *name;
2997         int                     count = 0;
2998         unsigned long           len;
2999
3000         DNPRINTF(SWM_D_MISC, "uniconify\n");
3001
3002         if (r && r->ws == NULL)
3003                 return;
3004
3005         /* make sure we have anything to uniconify */
3006         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3007                 if (win->ws == NULL)
3008                         continue; /* should never happen */
3009                 if (win->iconic == 0)
3010                         continue;
3011                 count++;
3012         }
3013         if (count == 0)
3014                 return;
3015
3016         search_r = r;
3017
3018         spawn_select(r, args, "uniconify", &searchpid);
3019
3020         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3021                 return;
3022
3023         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3024                 if (win->ws == NULL)
3025                         continue; /* should never happen */
3026                 if (win->iconic == 0)
3027                         continue;
3028
3029                 name = get_win_name(display, win->id, a_wmname, a_string,
3030                     &len);
3031                 if (name == NULL)
3032                         continue;
3033                 fprintf(lfile, "%s.%lu\n", name, win->id);
3034                 XFree(name);
3035         }
3036
3037         fclose(lfile);
3038 }
3039
3040 #define MAX_RESP_LEN    1024
3041
3042 void
3043 search_do_resp(void)
3044 {
3045         ssize_t                 rbytes;
3046         struct ws_win           *win;
3047         char                    *name, *resp, *s;
3048         unsigned long           len;
3049
3050         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
3051
3052         search_resp = 0;
3053         searchpid = 0;
3054
3055         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
3056                 fprintf(stderr, "search: calloc\n");
3057                 return;
3058         }
3059
3060         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
3061         if (rbytes <= 0) {
3062                 fprintf(stderr, "search: read error: %s\n", strerror(errno));
3063                 goto done;
3064         }
3065         resp[rbytes] = '\0';
3066         len = strlen(resp);
3067
3068         DNPRINTF(SWM_D_MISC, "search_do_resp: resp %s\n", resp);
3069         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
3070                 if (win->iconic == 0)
3071                         continue;
3072                 name = get_win_name(display, win->id, a_wmname, a_string, &len);
3073                 if (name == NULL)
3074                         continue;
3075                 if (asprintf(&s, "%s.%lu", name, win->id) == -1) {
3076                         XFree(name);
3077                         continue;
3078                 }
3079                 XFree(name);
3080                 if (strncmp(s, resp, len) == 0) {
3081                         /* XXX this should be a callback to generalize */
3082                         update_iconic(win, 0);
3083                         free(s);
3084                         break;
3085                 }
3086                 free(s);
3087         }
3088 done:
3089         free(resp);
3090 }
3091
3092 void
3093 wkill(struct swm_region *r, union arg *args)
3094 {
3095         DNPRINTF(SWM_D_MISC, "wkill %d\n", args->id);
3096
3097         if (r->ws->focus == NULL)
3098                 return;
3099
3100         if (args->id == SWM_ARG_ID_KILLWINDOW)
3101                 XKillClient(display, r->ws->focus->id);
3102         else
3103                 if (r->ws->focus->can_delete)
3104                         client_msg(r->ws->focus, adelete);
3105 }
3106
3107
3108 int
3109 floating_toggle_win(struct ws_win *win)
3110 {
3111         struct swm_region       *r;
3112
3113         if (win == NULL)
3114                 return 0;
3115
3116         if (!win->ws->r)
3117                 return 0;
3118
3119         r = win->ws->r;
3120
3121         /* reject floating toggles in max stack mode */
3122         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
3123                 return 0;
3124
3125         if (win->floating) {
3126                 if (!win->floatmaxed) {
3127                         /* retain position for refloat */
3128                         store_float_geom(win, r);
3129                 }
3130                 win->floating = 0;
3131         } else {
3132                 if (win->g_floatvalid) {
3133                         /* refloat at last floating relative position */
3134                         win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
3135                         win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
3136                         win->g.w = win->g_float.w;
3137                         win->g.h = win->g_float.h;
3138                 }
3139                 win->floating = 1;
3140         }
3141
3142         ewmh_update_actions(win);
3143
3144         return 1;
3145 }
3146
3147 void
3148 floating_toggle(struct swm_region *r, union arg *args)
3149 {
3150         struct ws_win           *win = r->ws->focus;
3151         union arg               a;
3152
3153         if (win == NULL)
3154                 return;
3155
3156         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3157             _NET_WM_STATE_TOGGLE);
3158
3159         stack();
3160
3161         if (win == win->ws->focus) {
3162                 a.id = SWM_ARG_ID_FOCUSCUR;
3163                 focus(win->ws->r, &a);
3164         }
3165 }
3166
3167 void
3168 resize_window(struct ws_win *win, int center)
3169 {
3170         unsigned int            mask;
3171         XWindowChanges          wc;
3172         struct swm_region       *r;
3173
3174         r = root_to_region(win->wa.root);
3175         bzero(&wc, sizeof wc);
3176         mask = CWBorderWidth | CWWidth | CWHeight;
3177         wc.border_width = border_width;
3178         wc.width = win->g.w;
3179         wc.height = win->g.h;
3180         if (center == SWM_ARG_ID_CENTER) {
3181                 wc.x = (WIDTH(r) - win->g.w) / 2 - border_width;
3182                 wc.y = (HEIGHT(r) - win->g.h) / 2 - border_width;
3183                 mask |= CWX | CWY;
3184         }
3185
3186         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
3187             win->id, wc.x, wc.y, wc.width, wc.height);
3188
3189         XConfigureWindow(display, win->id, mask, &wc);
3190 }
3191
3192 void
3193 resize(struct ws_win *win, union arg *args)
3194 {
3195         XEvent                  ev;
3196         Time                    time = 0;
3197         struct swm_region       *r = win->ws->r;
3198         int                     relx, rely;
3199         union arg               a;
3200
3201
3202         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %lu\n",
3203             win->id, win->floating, win->transient);
3204
3205         if (!(win->transient != 0 || win->floating != 0))
3206                 return;
3207
3208         /* reject resizes in max mode for floaters (transient ok) */
3209         if (win->floatmaxed)
3210                 return;
3211
3212         win->manual = 1;
3213         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3214             _NET_WM_STATE_ADD);
3215         /* raise the window = move to last in window list */
3216         a.id = SWM_ARG_ID_MOVELAST;
3217         swapwin(r, &a);
3218         stack();
3219
3220         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3221             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3222                 return;
3223
3224         /* place pointer at bottom left corner or nearest point inside r */
3225         if ( win->g.x + win->g.w < r->g.x + r->g.w - 1)
3226                 relx = win->g.w - 1;
3227         else
3228                 relx = r->g.x + r->g.w - win->g.x - 1;
3229
3230         if ( win->g.y + win->g.h < r->g.y + r->g.h - 1)
3231                 rely = win->g.h - 1;
3232         else
3233                 rely = r->g.y + r->g.h - win->g.y - 1;
3234
3235         XWarpPointer(display, None, win->id, 0, 0, 0, 0, relx, rely);
3236         do {
3237                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3238                     SubstructureRedirectMask, &ev);
3239                 switch(ev.type) {
3240                 case ConfigureRequest:
3241                 case Expose:
3242                 case MapRequest:
3243                         handler[ev.type](&ev);
3244                         break;
3245                 case MotionNotify:
3246                         /* do not allow resize outside of region */
3247                         if (    ev.xmotion.x_root < r->g.x ||
3248                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3249                                 ev.xmotion.y_root < r->g.y ||
3250                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3251                                 continue;
3252
3253                         if (ev.xmotion.x <= 1)
3254                                 ev.xmotion.x = 1;
3255                         if (ev.xmotion.y <= 1)
3256                                 ev.xmotion.y = 1;
3257                         win->g.w = ev.xmotion.x + 1;
3258                         win->g.h = ev.xmotion.y + 1;
3259
3260                         /* not free, don't sync more than 120 times / second */
3261                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3262                                 time = ev.xmotion.time;
3263                                 XSync(display, False);
3264                                 resize_window(win, args->id);
3265                         }
3266                         break;
3267                 }
3268         } while (ev.type != ButtonRelease);
3269         if (time) {
3270                 XSync(display, False);
3271                 resize_window(win, args->id);
3272         }
3273         store_float_geom(win,r);
3274
3275         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
3276             win->g.h - 1);
3277         XUngrabPointer(display, CurrentTime);
3278
3279         /* drain events */
3280         drain_enter_notify();
3281 }
3282
3283 void
3284 move_window(struct ws_win *win)
3285 {
3286         unsigned int            mask;
3287         XWindowChanges          wc;
3288         struct swm_region       *r;
3289
3290         r = root_to_region(win->wa.root);
3291         bzero(&wc, sizeof wc);
3292         mask = CWX | CWY;
3293         wc.x = win->g.x;
3294         wc.y = win->g.y;
3295         wc.border_width = border_width;
3296
3297         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
3298             win->id, wc.x, wc.y, wc.width, wc.height);
3299
3300         XConfigureWindow(display, win->id, mask, &wc);
3301 }
3302
3303 void
3304 move(struct ws_win *win, union arg *args)
3305 {
3306         XEvent                  ev;
3307         Time                    time = 0;
3308         struct swm_region       *r = win->ws->r;
3309         union arg               a;
3310
3311         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %lu\n",
3312             win->id, win->floating, win->transient);
3313
3314         /* in max_stack mode should only move transients */
3315         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
3316                 return;
3317
3318         win->manual = 1;
3319         if (win->floating == 0 && !win->transient) {
3320                 win->floating = 1;
3321                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3322                     _NET_WM_STATE_ADD);
3323         }
3324         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3325             _NET_WM_STATE_ADD);
3326
3327         /* raise the window = move to last in window list */
3328         a.id = SWM_ARG_ID_MOVELAST;
3329         swapwin(r, &a);
3330         stack();
3331
3332         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3333             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3334                 return;
3335         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3336         do {
3337                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3338                     SubstructureRedirectMask, &ev);
3339                 switch(ev.type) {
3340                 case ConfigureRequest:
3341                 case Expose:
3342                 case MapRequest:
3343                         handler[ev.type](&ev);
3344                         break;
3345                 case MotionNotify:
3346                         /* don't allow to move window origin out of region */
3347                         if (    ev.xmotion.x_root < r->g.x ||
3348                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3349                                 ev.xmotion.y_root < r->g.y ||
3350                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3351                                 continue;
3352
3353                         win->g.x = ev.xmotion.x_root - border_width;
3354                         win->g.y = ev.xmotion.y_root - border_width;
3355
3356                         /* not free, don't sync more than 120 times / second */
3357                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3358                                 time = ev.xmotion.time;
3359                                 XSync(display, False);
3360                                 move_window(win);
3361                         }
3362                         break;
3363                 }
3364         } while (ev.type != ButtonRelease);
3365         if (time) {
3366                 XSync(display, False);
3367                 move_window(win);
3368         }
3369         store_float_geom(win,r);
3370         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3371         XUngrabPointer(display, CurrentTime);
3372
3373         /* drain events */
3374         drain_enter_notify();
3375 }
3376
3377 /* user/key callable function IDs */
3378 enum keyfuncid {
3379         kf_cycle_layout,
3380         kf_stack_reset,
3381         kf_master_shrink,
3382         kf_master_grow,
3383         kf_master_add,
3384         kf_master_del,
3385         kf_stack_inc,
3386         kf_stack_dec,
3387         kf_swap_main,
3388         kf_focus_next,
3389         kf_focus_prev,
3390         kf_swap_next,
3391         kf_swap_prev,
3392         kf_spawn_term,
3393         kf_spawn_menu,
3394         kf_quit,
3395         kf_restart,
3396         kf_focus_main,
3397         kf_ws_1,
3398         kf_ws_2,
3399         kf_ws_3,
3400         kf_ws_4,
3401         kf_ws_5,
3402         kf_ws_6,
3403         kf_ws_7,
3404         kf_ws_8,
3405         kf_ws_9,
3406         kf_ws_10,
3407         kf_ws_next,
3408         kf_ws_prev,
3409         kf_ws_prior,
3410         kf_screen_next,
3411         kf_screen_prev,
3412         kf_mvws_1,
3413         kf_mvws_2,
3414         kf_mvws_3,
3415         kf_mvws_4,
3416         kf_mvws_5,
3417         kf_mvws_6,
3418         kf_mvws_7,
3419         kf_mvws_8,
3420         kf_mvws_9,
3421         kf_mvws_10,
3422         kf_bar_toggle,
3423         kf_wind_kill,
3424         kf_wind_del,
3425         kf_screenshot_all,
3426         kf_screenshot_wind,
3427         kf_float_toggle,
3428         kf_version,
3429         kf_spawn_lock,
3430         kf_spawn_initscr,
3431         kf_spawn_custom,
3432         kf_iconify,
3433         kf_uniconify,
3434         kf_dumpwins, /* MUST BE LAST */
3435         kf_invalid
3436 };
3437
3438 /* key definitions */
3439 void
3440 dummykeyfunc(struct swm_region *r, union arg *args)
3441 {
3442 };
3443
3444 void
3445 legacyfunc(struct swm_region *r, union arg *args)
3446 {
3447 };
3448
3449 struct keyfunc {
3450         char                    name[SWM_FUNCNAME_LEN];
3451         void                    (*func)(struct swm_region *r, union arg *);
3452         union arg               args;
3453 } keyfuncs[kf_invalid + 1] = {
3454         /* name                 function        argument */
3455         { "cycle_layout",       cycle_layout,   {0} },
3456         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
3457         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
3458         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
3459         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
3460         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
3461         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
3462         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
3463         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
3464         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
3465         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
3466         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
3467         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
3468         { "spawn_term",         spawnterm,      {.argv = spawn_term} },
3469         { "spawn_menu",         legacyfunc,     {0} },
3470         { "quit",               quit,           {0} },
3471         { "restart",            restart,        {0} },
3472         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
3473         { "ws_1",               switchws,       {.id = 0} },
3474         { "ws_2",               switchws,       {.id = 1} },
3475         { "ws_3",               switchws,       {.id = 2} },
3476         { "ws_4",               switchws,       {.id = 3} },
3477         { "ws_5",               switchws,       {.id = 4} },
3478         { "ws_6",               switchws,       {.id = 5} },
3479         { "ws_7",               switchws,       {.id = 6} },
3480         { "ws_8",               switchws,       {.id = 7} },
3481         { "ws_9",               switchws,       {.id = 8} },
3482         { "ws_10",              switchws,       {.id = 9} },
3483         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
3484         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
3485         { "ws_prior",           priorws,        {0} },
3486         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
3487         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
3488         { "mvws_1",             send_to_ws,     {.id = 0} },
3489         { "mvws_2",             send_to_ws,     {.id = 1} },
3490         { "mvws_3",             send_to_ws,     {.id = 2} },
3491         { "mvws_4",             send_to_ws,     {.id = 3} },
3492         { "mvws_5",             send_to_ws,     {.id = 4} },
3493         { "mvws_6",             send_to_ws,     {.id = 5} },
3494         { "mvws_7",             send_to_ws,     {.id = 6} },
3495         { "mvws_8",             send_to_ws,     {.id = 7} },
3496         { "mvws_9",             send_to_ws,     {.id = 8} },
3497         { "mvws_10",            send_to_ws,     {.id = 9} },
3498         { "bar_toggle",         bar_toggle,     {0} },
3499         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
3500         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
3501         { "screenshot_all",     legacyfunc,     {0} },
3502         { "screenshot_wind",    legacyfunc,     {0} },
3503         { "float_toggle",       floating_toggle,{0} },
3504         { "version",            version,        {0} },
3505         { "spawn_lock",         legacyfunc,     {0} },
3506         { "spawn_initscr",      legacyfunc,     {0} },
3507         { "spawn_custom",       dummykeyfunc,   {0} },
3508         { "iconify",            iconify,        {0} },
3509         { "uniconify",          uniconify,      {0} },
3510         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
3511         { "invalid key func",   NULL,           {0} },
3512 };
3513 struct key {
3514         unsigned int            mod;
3515         KeySym                  keysym;
3516         enum keyfuncid          funcid;
3517         char                    *spawn_name;
3518 };
3519 int                             keys_size = 0, keys_length = 0;
3520 struct key                      *keys = NULL;
3521
3522 /* mouse */
3523 enum { client_click, root_click };
3524 struct button {
3525         unsigned int            action;
3526         unsigned int            mask;
3527         unsigned int            button;
3528         void                    (*func)(struct ws_win *, union arg *);
3529         union arg               args;
3530 } buttons[] = {
3531           /* action     key             mouse button    func    args */
3532         { client_click, MODKEY,         Button3,        resize, {.id = SWM_ARG_ID_DONTCENTER} },
3533         { client_click, MODKEY | ShiftMask, Button3,    resize, {.id = SWM_ARG_ID_CENTER} },
3534         { client_click, MODKEY,         Button1,        move,   {0} },
3535 };
3536
3537 void
3538 update_modkey(unsigned int mod)
3539 {
3540         int                     i;
3541
3542         mod_key = mod;
3543         for (i = 0; i < keys_length; i++)
3544                 if (keys[i].mod & ShiftMask)
3545                         keys[i].mod = mod | ShiftMask;
3546                 else
3547                         keys[i].mod = mod;
3548
3549         for (i = 0; i < LENGTH(buttons); i++)
3550                 if (buttons[i].mask & ShiftMask)
3551                         buttons[i].mask = mod | ShiftMask;
3552                 else
3553                         buttons[i].mask = mod;
3554 }
3555
3556 /* spawn */
3557 struct spawn_prog {
3558         char                    *name;
3559         int                     argc;
3560         char                    **argv;
3561 };
3562
3563 int                             spawns_size = 0, spawns_length = 0;
3564 struct spawn_prog               *spawns = NULL;
3565
3566 int
3567 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
3568     char ***ret_args)
3569 {
3570         struct spawn_prog       *prog = NULL;
3571         int                     i;
3572         char                    *ap, **real_args;
3573
3574         DNPRINTF(SWM_D_SPAWN, "spawn_expand %s\n", spawn_name);
3575
3576         /* find program */
3577         for (i = 0; i < spawns_length; i++) {
3578                 if (!strcasecmp(spawn_name, spawns[i].name))
3579                         prog = &spawns[i];
3580         }
3581         if (prog == NULL) {
3582                 fprintf(stderr, "spawn_custom: program %s not found\n",
3583                     spawn_name);
3584                 return (-1);
3585         }
3586
3587         /* make room for expanded args */
3588         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
3589                 err(1, "spawn_custom: calloc real_args");
3590
3591         /* expand spawn_args into real_args */
3592         for (i = 0; i < prog->argc; i++) {
3593                 ap = prog->argv[i];
3594                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg = %s\n", ap);
3595                 if (!strcasecmp(ap, "$bar_border")) {
3596                         if ((real_args[i] =
3597                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
3598                             == NULL)
3599                                 err(1,  "spawn_custom border color");
3600                 } else if (!strcasecmp(ap, "$bar_color")) {
3601                         if ((real_args[i] =
3602                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
3603                             == NULL)
3604                                 err(1, "spawn_custom bar color");
3605                 } else if (!strcasecmp(ap, "$bar_font")) {
3606                         if ((real_args[i] = strdup(bar_fonts[bar_fidx]))
3607                             == NULL)
3608                                 err(1, "spawn_custom bar fonts");
3609                 } else if (!strcasecmp(ap, "$bar_font_color")) {
3610                         if ((real_args[i] =
3611                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
3612                             == NULL)
3613                                 err(1, "spawn_custom color font");
3614                 } else if (!strcasecmp(ap, "$color_focus")) {
3615                         if ((real_args[i] =
3616                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
3617                             == NULL)
3618                                 err(1, "spawn_custom color focus");
3619                 } else if (!strcasecmp(ap, "$color_unfocus")) {
3620                         if ((real_args[i] =
3621                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
3622                             == NULL)
3623                                 err(1, "spawn_custom color unfocus");
3624                 } else {
3625                         /* no match --> copy as is */
3626                         if ((real_args[i] = strdup(ap)) == NULL)
3627                                 err(1, "spawn_custom strdup(ap)");
3628                 }
3629                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg = %s\n",
3630                     real_args[i]);
3631         }
3632
3633 #ifdef SWM_DEBUG
3634         if ((swm_debug & SWM_D_SPAWN) != 0) {
3635                 fprintf(stderr, "spawn_custom: result = ");
3636                 for (i = 0; i < prog->argc; i++)
3637                         fprintf(stderr, "\"%s\" ", real_args[i]);
3638                 fprintf(stderr, "\n");
3639         }
3640 #endif
3641         *ret_args = real_args;
3642         return (prog->argc);
3643 }
3644
3645 void
3646 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
3647 {
3648         union arg               a;
3649         char                    **real_args;
3650         int                     spawn_argc, i;
3651
3652         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3653                 return;
3654         a.argv = real_args;
3655         if (fork() == 0)
3656                 spawn(r, &a, 1);
3657
3658         for (i = 0; i < spawn_argc; i++)
3659                 free(real_args[i]);
3660         free(real_args);
3661 }
3662
3663 void
3664 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
3665 {
3666         union arg               a;
3667         char                    **real_args;
3668         int                     i, spawn_argc;
3669
3670         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3671                 return;
3672         a.argv = real_args;
3673
3674         if (pipe(select_list_pipe) == -1)
3675                 err(1, "pipe error");
3676         if (pipe(select_resp_pipe) == -1)
3677                 err(1, "pipe error");
3678
3679         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3680                 err(1, "could not disable SIGPIPE");
3681         switch (*pid = fork()) {
3682         case -1:
3683                 err(1, "cannot fork");
3684                 break;
3685         case 0: /* child */
3686                 if (dup2(select_list_pipe[0], 0) == -1)
3687                         errx(1, "dup2");
3688                 if (dup2(select_resp_pipe[1], 1) == -1)
3689                         errx(1, "dup2");
3690                 close(select_list_pipe[1]);
3691                 close(select_resp_pipe[0]);
3692                 spawn(r, &a, 0);
3693                 break;
3694         default: /* parent */
3695                 close(select_list_pipe[0]);
3696                 close(select_resp_pipe[1]);
3697                 break;
3698         }
3699
3700         for (i = 0; i < spawn_argc; i++)
3701                 free(real_args[i]);
3702         free(real_args);
3703 }
3704
3705 void
3706 setspawn(struct spawn_prog *prog)
3707 {
3708         int                     i, j;
3709
3710         if (prog == NULL || prog->name == NULL)
3711                 return;
3712
3713         /* find existing */
3714         for (i = 0; i < spawns_length; i++) {
3715                 if (!strcmp(spawns[i].name, prog->name)) {
3716                         /* found */
3717                         if (prog->argv == NULL) {
3718                                 /* delete */
3719                                 DNPRINTF(SWM_D_SPAWN,
3720                                     "setspawn: delete #%d %s\n",
3721                                     i, spawns[i].name);
3722                                 free(spawns[i].name);
3723                                 for (j = 0; j < spawns[i].argc; j++)
3724                                         free(spawns[i].argv[j]);
3725                                 free(spawns[i].argv);
3726                                 j = spawns_length - 1;
3727                                 if (i < j)
3728                                         spawns[i] = spawns[j];
3729                                 spawns_length--;
3730                                 free(prog->name);
3731                         } else {
3732                                 /* replace */
3733                                 DNPRINTF(SWM_D_SPAWN,
3734                                     "setspawn: replace #%d %s\n",
3735                                     i, spawns[i].name);
3736                                 free(spawns[i].name);
3737                                 for (j = 0; j < spawns[i].argc; j++)
3738                                         free(spawns[i].argv[j]);
3739                                 free(spawns[i].argv);
3740                                 spawns[i] = *prog;
3741                         }
3742                         /* found case handled */
3743                         free(prog);
3744                         return;
3745                 }
3746         }
3747
3748         if (prog->argv == NULL) {
3749                 fprintf(stderr,
3750                     "error: setspawn: cannot find program %s", prog->name);
3751                 free(prog);
3752                 return;
3753         }
3754
3755         /* not found: add */
3756         if (spawns_size == 0 || spawns == NULL) {
3757                 spawns_size = 4;
3758                 DNPRINTF(SWM_D_SPAWN, "setspawn: init list %d\n", spawns_size);
3759                 spawns = malloc((size_t)spawns_size *
3760                     sizeof(struct spawn_prog));
3761                 if (spawns == NULL) {
3762                         fprintf(stderr, "setspawn: malloc failed\n");
3763                         perror(" failed");
3764                         quit(NULL, NULL);
3765                 }
3766         } else if (spawns_length == spawns_size) {
3767                 spawns_size *= 2;
3768                 DNPRINTF(SWM_D_SPAWN, "setspawn: grow list %d\n", spawns_size);
3769                 spawns = realloc(spawns, (size_t)spawns_size *
3770                     sizeof(struct spawn_prog));
3771                 if (spawns == NULL) {
3772                         fprintf(stderr, "setspawn: realloc failed\n");
3773                         perror(" failed");
3774                         quit(NULL, NULL);
3775                 }
3776         }
3777
3778         if (spawns_length < spawns_size) {
3779                 DNPRINTF(SWM_D_SPAWN, "setspawn: add #%d %s\n",
3780                     spawns_length, prog->name);
3781                 i = spawns_length++;
3782                 spawns[i] = *prog;
3783         } else {
3784                 fprintf(stderr, "spawns array problem?\n");
3785                 if (spawns == NULL) {
3786                         fprintf(stderr, "spawns array is NULL!\n");
3787                         quit(NULL, NULL);
3788                 }
3789         }
3790         free(prog);
3791 }
3792
3793 int
3794 setconfspawn(char *selector, char *value, int flags)
3795 {
3796         struct spawn_prog       *prog;
3797         char                    *vp, *cp, *word;
3798
3799         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
3800         if ((prog = calloc(1, sizeof *prog)) == NULL)
3801                 err(1, "setconfspawn: calloc prog");
3802         prog->name = strdup(selector);
3803         if (prog->name == NULL)
3804                 err(1, "setconfspawn prog->name");
3805         if ((cp = vp = strdup(value)) == NULL)
3806                 err(1, "setconfspawn: strdup(value) ");
3807         while ((word = strsep(&cp, " \t")) != NULL) {
3808                 DNPRINTF(SWM_D_SPAWN, "setconfspawn: arg [%s]\n", word);
3809                 if (cp)
3810                         cp += (long)strspn(cp, " \t");
3811                 if (strlen(word) > 0) {
3812                         prog->argc++;
3813                         prog->argv = realloc(prog->argv,
3814                             prog->argc * sizeof(char *));
3815                         if ((prog->argv[prog->argc - 1] = strdup(word)) == NULL)
3816                                 err(1, "setconfspawn: strdup");
3817                 }
3818         }
3819         free(vp);
3820
3821         setspawn(prog);
3822
3823         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
3824         return (0);
3825 }
3826
3827 void
3828 setup_spawn(void)
3829 {
3830         setconfspawn("term",            "xterm",                0);
3831         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
3832         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
3833         setconfspawn("lock",            "xlock",                0);
3834         setconfspawn("initscr",         "initscreen.sh",        0);
3835         setconfspawn("menu",            "dmenu_run"
3836                                         " -fn $bar_font"
3837                                         " -nb $bar_color"
3838                                         " -nf $bar_font_color"
3839                                         " -sb $bar_border"
3840                                         " -sf $bar_color",      0);
3841         setconfspawn("uniconify",       "dmenu"
3842                                         " -i"
3843                                         " -fn $bar_font"
3844                                         " -nb $bar_color"
3845                                         " -nf $bar_font_color"
3846                                         " -sb $bar_border"
3847                                         " -sf $bar_color",      0);
3848 }
3849
3850 /* key bindings */
3851 #define SWM_MODNAME_SIZE        32
3852 #define SWM_KEY_WS              "\n+ \t"
3853 int
3854 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
3855 {
3856         char                    *cp, *name;
3857         KeySym                  uks;
3858         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
3859         if (mod == NULL || ks == NULL) {
3860                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
3861                 return (1);
3862         }
3863         if (keystr == NULL || strlen(keystr) == 0) {
3864                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
3865                 return (1);
3866         }
3867         cp = keystr;
3868         *ks = NoSymbol;
3869         *mod = 0;
3870         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
3871                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
3872                 if (cp)
3873                         cp += (long)strspn(cp, SWM_KEY_WS);
3874                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
3875                         *mod |= currmod;
3876                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
3877                         *mod |= Mod1Mask;
3878                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
3879                         *mod += Mod2Mask;
3880                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
3881                         *mod |= Mod3Mask;
3882                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
3883                         *mod |= Mod4Mask;
3884                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
3885                         *mod |= ShiftMask;
3886                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
3887                         *mod |= ControlMask;
3888                 else {
3889                         *ks = XStringToKeysym(name);
3890                         XConvertCase(*ks, ks, &uks);
3891                         if (ks == NoSymbol) {
3892                                 DNPRINTF(SWM_D_KEY,
3893                                     "parsekeys: invalid key %s\n",
3894                                     name);
3895                                 return (1);
3896                         }
3897                 }
3898         }
3899         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
3900         return (0);
3901 }
3902
3903 char *
3904 strdupsafe(char *str)
3905 {
3906         if (str == NULL)
3907                 return (NULL);
3908         else
3909                 return (strdup(str));
3910 }
3911
3912 void
3913 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid, char *spawn_name)
3914 {
3915         int                     i, j;
3916         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
3917             keyfuncs[kfid].name, spawn_name);
3918         /* find existing */
3919         for (i = 0; i < keys_length; i++) {
3920                 if (keys[i].mod == mod && keys[i].keysym == ks) {
3921                         if (kfid == kf_invalid) {
3922                                 /* found: delete */
3923                                 DNPRINTF(SWM_D_KEY,
3924                                     "setkeybinding: delete #%d %s\n",
3925                                     i, keyfuncs[keys[i].funcid].name);
3926                                 free(keys[i].spawn_name);
3927                                 j = keys_length - 1;
3928                                 if (i < j)
3929                                         keys[i] = keys[j];
3930                                 keys_length--;
3931                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3932                                 return;
3933                         } else {
3934                                 /* found: replace */
3935                                 DNPRINTF(SWM_D_KEY,
3936                                     "setkeybinding: replace #%d %s %s\n",
3937                                     i, keyfuncs[keys[i].funcid].name,
3938                                     spawn_name);
3939                                 free(keys[i].spawn_name);
3940                                 keys[i].mod = mod;
3941                                 keys[i].keysym = ks;
3942                                 keys[i].funcid = kfid;
3943                                 keys[i].spawn_name = strdupsafe(spawn_name);
3944                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3945                                 return;
3946                         }
3947                 }
3948         }
3949         if (kfid == kf_invalid) {
3950                 fprintf(stderr,
3951                     "error: setkeybinding: cannot find mod/key combination");
3952                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3953                 return;
3954         }
3955         /* not found: add */
3956         if (keys_size == 0 || keys == NULL) {
3957                 keys_size = 4;
3958                 DNPRINTF(SWM_D_KEY, "setkeybinding: init list %d\n", keys_size);
3959                 keys = malloc((size_t)keys_size * sizeof(struct key));
3960                 if (!keys) {
3961                         fprintf(stderr, "malloc failed\n");
3962                         perror(" failed");
3963                         quit(NULL, NULL);
3964                 }
3965         } else if (keys_length == keys_size) {
3966                 keys_size *= 2;
3967                 DNPRINTF(SWM_D_KEY, "setkeybinding: grow list %d\n", keys_size);
3968                 keys = realloc(keys, (size_t)keys_size * sizeof(struct key));
3969                 if (!keys) {
3970                         fprintf(stderr, "realloc failed\n");
3971                         perror(" failed");
3972                         quit(NULL, NULL);
3973                 }
3974         }
3975         if (keys_length < keys_size) {
3976                 j = keys_length++;
3977                 DNPRINTF(SWM_D_KEY, "setkeybinding: add #%d %s %s\n",
3978                     j, keyfuncs[kfid].name, spawn_name);
3979                 keys[j].mod = mod;
3980                 keys[j].keysym = ks;
3981                 keys[j].funcid = kfid;
3982                 keys[j].spawn_name = strdupsafe(spawn_name);
3983         } else {
3984                 fprintf(stderr, "keys array problem?\n");
3985                 if (!keys) {
3986                         fprintf(stderr, "keys array problem\n");
3987                         quit(NULL, NULL);
3988                 }
3989         }
3990         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3991 }
3992
3993 int
3994 setconfbinding(char *selector, char *value, int flags)
3995 {
3996         enum keyfuncid          kfid;
3997         unsigned int            mod;
3998         KeySym                  ks;
3999         int                     i;
4000         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
4001         if (selector == NULL) {
4002                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
4003                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4004                         kfid = kf_invalid;
4005                         setkeybinding(mod, ks, kfid, NULL);
4006                         return (0);
4007                 } else
4008                         return (1);
4009         }
4010         /* search by key function name */
4011         for (kfid = 0; kfid < kf_invalid; (kfid)++) {
4012                 if (strncasecmp(selector, keyfuncs[kfid].name,
4013                     SWM_FUNCNAME_LEN) == 0) {
4014                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4015                             selector);
4016                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4017                                 setkeybinding(mod, ks, kfid, NULL);
4018                                 return (0);
4019                         } else
4020                                 return (1);
4021                 }
4022         }
4023         /* search by custom spawn name */
4024         for (i = 0; i < spawns_length; i++) {
4025                 if (strcasecmp(selector, spawns[i].name) == 0) {
4026                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4027                             selector);
4028                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4029                                 setkeybinding(mod, ks, kf_spawn_custom,
4030                                     spawns[i].name);
4031                                 return (0);
4032                         } else
4033                                 return (1);
4034                 }
4035         }
4036         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
4037         return (1);
4038 }
4039
4040 void
4041 setup_keys(void)
4042 {
4043         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout,NULL);
4044         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset, NULL);
4045         setkeybinding(MODKEY,           XK_h,           kf_master_shrink,NULL);
4046         setkeybinding(MODKEY,           XK_l,           kf_master_grow, NULL);
4047         setkeybinding(MODKEY,           XK_comma,       kf_master_add,  NULL);
4048         setkeybinding(MODKEY,           XK_period,      kf_master_del,  NULL);
4049         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc,   NULL);
4050         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec,   NULL);
4051         setkeybinding(MODKEY,           XK_Return,      kf_swap_main,   NULL);
4052         setkeybinding(MODKEY,           XK_j,           kf_focus_next,  NULL);
4053         setkeybinding(MODKEY,           XK_k,           kf_focus_prev,  NULL);
4054         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next,   NULL);
4055         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev,   NULL);
4056         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_term,  NULL);
4057         setkeybinding(MODKEY,           XK_p,           kf_spawn_custom,        "menu");
4058         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit,        NULL);
4059         setkeybinding(MODKEY,           XK_q,           kf_restart,     NULL);
4060         setkeybinding(MODKEY,           XK_m,           kf_focus_main,  NULL);
4061         setkeybinding(MODKEY,           XK_1,           kf_ws_1,        NULL);
4062         setkeybinding(MODKEY,           XK_2,           kf_ws_2,        NULL);
4063         setkeybinding(MODKEY,           XK_3,           kf_ws_3,        NULL);
4064         setkeybinding(MODKEY,           XK_4,           kf_ws_4,        NULL);
4065         setkeybinding(MODKEY,           XK_5,           kf_ws_5,        NULL);
4066         setkeybinding(MODKEY,           XK_6,           kf_ws_6,        NULL);
4067         setkeybinding(MODKEY,           XK_7,           kf_ws_7,        NULL);
4068         setkeybinding(MODKEY,           XK_8,           kf_ws_8,        NULL);
4069         setkeybinding(MODKEY,           XK_9,           kf_ws_9,        NULL);
4070         setkeybinding(MODKEY,           XK_0,           kf_ws_10,       NULL);
4071         setkeybinding(MODKEY,           XK_Right,       kf_ws_next,     NULL);
4072         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev,     NULL);
4073         setkeybinding(MODKEY,           XK_a,           kf_ws_prior,    NULL);
4074         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next, NULL);
4075         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev, NULL);
4076         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1,      NULL);
4077         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2,      NULL);
4078         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3,      NULL);
4079         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4,      NULL);
4080         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5,      NULL);
4081         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6,      NULL);
4082         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7,      NULL);
4083         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8,      NULL);
4084         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9,      NULL);
4085         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10,     NULL);
4086         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle,  NULL);
4087         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next,  NULL);
4088         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev,  NULL);
4089         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill,   NULL);
4090         setkeybinding(MODKEY,           XK_x,           kf_wind_del,    NULL);
4091         setkeybinding(MODKEY,           XK_s,           kf_spawn_custom,        "screenshot_all");
4092         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_spawn_custom,        "screenshot_wind");
4093         setkeybinding(MODKEY,           XK_t,           kf_float_toggle,NULL);
4094         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version,     NULL);
4095         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_custom,        "lock");
4096         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_custom,        "initscr");
4097         setkeybinding(MODKEY,           XK_w,           kf_iconify,     NULL);
4098         setkeybinding(MODKEY|ShiftMask, XK_w,           kf_uniconify,   NULL);
4099 #ifdef SWM_DEBUG
4100         setkeybinding(MODKEY|ShiftMask, XK_d,           kf_dumpwins,    NULL);
4101 #endif
4102 }
4103
4104 void
4105 updatenumlockmask(void)
4106 {
4107         unsigned int            i, j;
4108         XModifierKeymap         *modmap;
4109
4110         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
4111         numlockmask = 0;
4112         modmap = XGetModifierMapping(display);
4113         for (i = 0; i < 8; i++)
4114                 for (j = 0; j < modmap->max_keypermod; j++)
4115                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
4116                           == XKeysymToKeycode(display, XK_Num_Lock))
4117                                 numlockmask = (1 << i);
4118
4119         XFreeModifiermap(modmap);
4120 }
4121
4122 void
4123 grabkeys(void)
4124 {
4125         unsigned int            i, j, k;
4126         KeyCode                 code;
4127         unsigned int            modifiers[] =
4128             { 0, LockMask, numlockmask, numlockmask | LockMask };
4129
4130         DNPRINTF(SWM_D_MISC, "grabkeys\n");
4131         updatenumlockmask();
4132
4133         for (k = 0; k < ScreenCount(display); k++) {
4134                 if (TAILQ_EMPTY(&screens[k].rl))
4135                         continue;
4136                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
4137                 for (i = 0; i < keys_length; i++) {
4138                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
4139                                 for (j = 0; j < LENGTH(modifiers); j++)
4140                                         XGrabKey(display, code,
4141                                             keys[i].mod | modifiers[j],
4142                                             screens[k].root, True,
4143                                             GrabModeAsync, GrabModeAsync);
4144                 }
4145         }
4146 }
4147
4148 void
4149 grabbuttons(struct ws_win *win, int focused)
4150 {
4151         unsigned int            i, j;
4152         unsigned int            modifiers[] =
4153             { 0, LockMask, numlockmask, numlockmask|LockMask };
4154
4155         updatenumlockmask();
4156         XUngrabButton(display, AnyButton, AnyModifier, win->id);
4157         if (focused) {
4158                 for (i = 0; i < LENGTH(buttons); i++)
4159                         if (buttons[i].action == client_click)
4160                                 for (j = 0; j < LENGTH(modifiers); j++)
4161                                         XGrabButton(display, buttons[i].button,
4162                                             buttons[i].mask | modifiers[j],
4163                                             win->id, False, BUTTONMASK,
4164                                             GrabModeAsync, GrabModeSync, None,
4165                                             None);
4166         } else
4167                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
4168                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
4169 }
4170
4171 const char *quirkname[] = {
4172         "NONE",         /* config string for "no value" */
4173         "FLOAT",
4174         "TRANSSZ",
4175         "ANYWHERE",
4176         "XTERM_FONTADJ",
4177         "FULLSCREEN",
4178 };
4179
4180 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
4181 #define SWM_Q_WS                "\n|+ \t"
4182 int
4183 parsequirks(char *qstr, unsigned long *quirk)
4184 {
4185         char                    *cp, *name;
4186         int                     i;
4187
4188         if (quirk == NULL)
4189                 return (1);
4190
4191         cp = qstr;
4192         *quirk = 0;
4193         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
4194                 if (cp)
4195                         cp += (long)strspn(cp, SWM_Q_WS);
4196                 for (i = 0; i < LENGTH(quirkname); i++) {
4197                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
4198                                 DNPRINTF(SWM_D_QUIRK, "parsequirks: %s\n", name);
4199                                 if (i == 0) {
4200                                         *quirk = 0;
4201                                         return (0);
4202                                 }
4203                                 *quirk |= 1 << (i-1);
4204                                 break;
4205                         }
4206                 }
4207                 if (i >= LENGTH(quirkname)) {
4208                         DNPRINTF(SWM_D_QUIRK,
4209                             "parsequirks: invalid quirk [%s]\n", name);
4210                         return (1);
4211                 }
4212         }
4213         return (0);
4214 }
4215
4216 void
4217 setquirk(const char *class, const char *name, const int quirk)
4218 {
4219         int                     i, j;
4220
4221         /* find existing */
4222         for (i = 0; i < quirks_length; i++) {
4223                 if (!strcmp(quirks[i].class, class) &&
4224                     !strcmp(quirks[i].name, name)) {
4225                         if (!quirk) {
4226                                 /* found: delete */
4227                                 DNPRINTF(SWM_D_QUIRK,
4228                                     "setquirk: delete #%d %s:%s\n",
4229                                     i, quirks[i].class, quirks[i].name);
4230                                 free(quirks[i].class);
4231                                 free(quirks[i].name);
4232                                 j = quirks_length - 1;
4233                                 if (i < j)
4234                                         quirks[i] = quirks[j];
4235                                 quirks_length--;
4236                                 return;
4237                         } else {
4238                                 /* found: replace */
4239                                 DNPRINTF(SWM_D_QUIRK,
4240                                     "setquirk: replace #%d %s:%s\n",
4241                                     i, quirks[i].class, quirks[i].name);
4242                                 free(quirks[i].class);
4243                                 free(quirks[i].name);
4244                                 quirks[i].class = strdup(class);
4245                                 quirks[i].name = strdup(name);
4246                                 quirks[i].quirk = quirk;
4247                                 return;
4248                         }
4249                 }
4250         }
4251         if (!quirk) {
4252                 fprintf(stderr,
4253                     "error: setquirk: cannot find class/name combination");
4254                 return;
4255         }
4256         /* not found: add */
4257         if (quirks_size == 0 || quirks == NULL) {
4258                 quirks_size = 4;
4259                 DNPRINTF(SWM_D_QUIRK, "setquirk: init list %d\n", quirks_size);
4260                 quirks = malloc((size_t)quirks_size * sizeof(struct quirk));
4261                 if (!quirks) {
4262                         fprintf(stderr, "setquirk: malloc failed\n");
4263                         perror(" failed");
4264                         quit(NULL, NULL);
4265                 }
4266         } else if (quirks_length == quirks_size) {
4267                 quirks_size *= 2;
4268                 DNPRINTF(SWM_D_QUIRK, "setquirk: grow list %d\n", quirks_size);
4269                 quirks = realloc(quirks, (size_t)quirks_size * sizeof(struct quirk));
4270                 if (!quirks) {
4271                         fprintf(stderr, "setquirk: realloc failed\n");
4272                         perror(" failed");
4273                         quit(NULL, NULL);
4274                 }
4275         }
4276         if (quirks_length < quirks_size) {
4277                 DNPRINTF(SWM_D_QUIRK, "setquirk: add %d\n", quirks_length);
4278                 j = quirks_length++;
4279                 quirks[j].class = strdup(class);
4280                 quirks[j].name = strdup(name);
4281                 quirks[j].quirk = quirk;
4282         } else {
4283                 fprintf(stderr, "quirks array problem?\n");
4284                 if (!quirks) {
4285                         fprintf(stderr, "quirks array problem!\n");
4286                         quit(NULL, NULL);
4287                 }
4288         }
4289 }
4290
4291 int
4292 setconfquirk(char *selector, char *value, int flags)
4293 {
4294         char                    *cp, *class, *name;
4295         int                     retval;
4296         unsigned long           quirks;
4297         if (selector == NULL)
4298                 return (0);
4299         if ((cp = strchr(selector, ':')) == NULL)
4300                 return (0);
4301         *cp = '\0';
4302         class = selector;
4303         name = cp + 1;
4304         if ((retval = parsequirks(value, &quirks)) == 0)
4305                 setquirk(class, name, quirks);
4306         return (retval);
4307 }
4308
4309 void
4310 setup_quirks(void)
4311 {
4312         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
4313         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
4314         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
4315         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
4316         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4317         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
4318         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4319         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4320         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4321         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4322         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
4323         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
4324         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
4325 }
4326
4327 /* conf file stuff */
4328 #define SWM_CONF_FILE   "scrotwm.conf"
4329
4330 enum    { SWM_S_BAR_DELAY, SWM_S_BAR_ENABLED, SWM_S_BAR_BORDER_WIDTH, SWM_S_STACK_ENABLED,
4331           SWM_S_CLOCK_ENABLED, SWM_S_CLOCK_FORMAT, SWM_S_CYCLE_EMPTY,
4332           SWM_S_CYCLE_VISIBLE, SWM_S_SS_ENABLED, SWM_S_TERM_WIDTH,
4333           SWM_S_TITLE_CLASS_ENABLED, SWM_S_TITLE_NAME_ENABLED, SWM_S_WINDOW_NAME_ENABLED,
4334           SWM_S_FOCUS_MODE, SWM_S_DISABLE_BORDER, SWM_S_BORDER_WIDTH, SWM_S_BAR_FONT,
4335           SWM_S_BAR_ACTION, SWM_S_SPAWN_TERM, SWM_S_SS_APP, SWM_S_DIALOG_RATIO,
4336           SWM_S_BAR_AT_BOTTOM
4337         };
4338
4339 int
4340 setconfvalue(char *selector, char *value, int flags)
4341 {
4342         switch (flags) {
4343         case SWM_S_BAR_DELAY:
4344                 bar_delay = atoi(value);
4345                 break;
4346         case SWM_S_BAR_ENABLED:
4347                 bar_enabled = atoi(value);
4348                 break;
4349         case SWM_S_BAR_BORDER_WIDTH:
4350                 bar_border_width = atoi(value);
4351                 break;
4352         case SWM_S_BAR_AT_BOTTOM:
4353                 bar_at_bottom = atoi(value);
4354                 break;
4355         case SWM_S_STACK_ENABLED:
4356                 stack_enabled = atoi(value);
4357                 break;
4358         case SWM_S_CLOCK_ENABLED:
4359                 clock_enabled = atoi(value);
4360                 break;
4361         case SWM_S_CLOCK_FORMAT:
4362 #ifndef SWM_DENY_CLOCK_FORMAT
4363                 free(clock_format);
4364                 if ((clock_format = strdup(value)) == NULL)
4365                         err(1, "setconfvalue: clock_format");
4366 #endif
4367                 break;
4368         case SWM_S_CYCLE_EMPTY:
4369                 cycle_empty = atoi(value);
4370                 break;
4371         case SWM_S_CYCLE_VISIBLE:
4372                 cycle_visible = atoi(value);
4373                 break;
4374         case SWM_S_SS_ENABLED:
4375                 ss_enabled = atoi(value);
4376                 break;
4377         case SWM_S_TERM_WIDTH:
4378                 term_width = atoi(value);
4379                 break;
4380         case SWM_S_TITLE_CLASS_ENABLED:
4381                 title_class_enabled = atoi(value);
4382                 break;
4383         case SWM_S_WINDOW_NAME_ENABLED:
4384                 window_name_enabled = atoi(value);
4385                 break;
4386         case SWM_S_TITLE_NAME_ENABLED:
4387                 title_name_enabled = atoi(value);
4388                 break;
4389         case SWM_S_FOCUS_MODE:
4390                 if (!strcmp(value, "default"))
4391                         focus_mode = SWM_FOCUS_DEFAULT;
4392                 else if (!strcmp(value, "follow_cursor"))
4393                         focus_mode = SWM_FOCUS_FOLLOW;
4394                 else if (!strcmp(value, "synergy"))
4395                         focus_mode = SWM_FOCUS_SYNERGY;
4396                 else
4397                         err(1, "focus_mode");
4398                 break;
4399         case SWM_S_DISABLE_BORDER:
4400                 disable_border = atoi(value);
4401                 break;
4402         case SWM_S_BORDER_WIDTH:
4403                 border_width = atoi(value);
4404                 break;
4405         case SWM_S_BAR_FONT:
4406                 free(bar_fonts[0]);
4407                 if ((bar_fonts[0] = strdup(value)) == NULL)
4408                         err(1, "setconfvalue: bar_font");
4409                 break;
4410         case SWM_S_BAR_ACTION:
4411                 free(bar_argv[0]);
4412                 if ((bar_argv[0] = strdup(value)) == NULL)
4413                         err(1, "setconfvalue: bar_action");
4414                 break;
4415         case SWM_S_SPAWN_TERM:
4416                 free(spawn_term[0]);
4417                 if ((spawn_term[0] = strdup(value)) == NULL)
4418                         err(1, "setconfvalue: spawn_term");
4419                 break;
4420         case SWM_S_SS_APP:
4421                 break;
4422         case SWM_S_DIALOG_RATIO:
4423                 dialog_ratio = atof(value);
4424                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
4425                         dialog_ratio = .6;
4426                 break;
4427         default:
4428                 return (1);
4429         }
4430         return (0);
4431 }
4432
4433 int
4434 setconfmodkey(char *selector, char *value, int flags)
4435 {
4436         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
4437                 update_modkey(Mod1Mask);
4438         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
4439                 update_modkey(Mod2Mask);
4440         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
4441                 update_modkey(Mod3Mask);
4442         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
4443                 update_modkey(Mod4Mask);
4444         else
4445                 return (1);
4446         return (0);
4447 }
4448
4449 int
4450 setconfcolor(char *selector, char *value, int flags)
4451 {
4452         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
4453         return (0);
4454 }
4455
4456 int
4457 setconfregion(char *selector, char *value, int flags)
4458 {
4459         custom_region(value);
4460         return (0);
4461 }
4462
4463 /* config options */
4464 struct config_option {
4465         char                    *optname;
4466         int (*func)(char*, char*, int);
4467         int funcflags;
4468 };
4469 struct config_option configopt[] = {
4470         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
4471         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
4472         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
4473         { "bar_border_width",                   setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
4474         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
4475         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
4476         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
4477         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
4478         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
4479         { "bind",                       setconfbinding, 0 },
4480         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
4481         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
4482         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
4483         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
4484         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
4485         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
4486         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
4487         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
4488         { "modkey",                     setconfmodkey,  0 },
4489         { "program",                    setconfspawn,   0 },
4490         { "quirk",                      setconfquirk,   0 },
4491         { "region",                     setconfregion,  0 },
4492         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
4493         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
4494         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
4495         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
4496         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
4497         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
4498         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
4499         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
4500         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
4501         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
4502 };
4503
4504
4505 int
4506 conf_load(char *filename)
4507 {
4508         FILE                    *config;
4509         char                    *line, *cp, *optsub, *optval;
4510         size_t                  linelen, lineno = 0;
4511         int                     wordlen, i, optind;
4512         struct config_option    *opt;
4513
4514         DNPRINTF(SWM_D_CONF, "conf_load begin\n");
4515
4516         if (filename == NULL) {
4517                 fprintf(stderr, "conf_load: no filename\n");
4518                 return (1);
4519         }
4520         if ((config = fopen(filename, "r")) == NULL) {
4521                 warn("conf_load: fopen");
4522                 return (1);
4523         }
4524
4525         while (!feof(config)) {
4526                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
4527                     == NULL) {
4528                         if (ferror(config))
4529                                 err(1, "%s", filename);
4530                         else
4531                                 continue;
4532                 }
4533                 cp = line;
4534                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4535                 if (cp[0] == '\0') {
4536                         /* empty line */
4537                         free(line);
4538                         continue;
4539                 }
4540                 /* get config option */
4541                 wordlen = strcspn(cp, "=[ \t\n");
4542                 if (wordlen == 0) {
4543                         warnx("%s: line %zd: no option found",
4544                             filename, lineno);
4545                         return (1);
4546                 }
4547                 optind = -1;
4548                 for (i = 0; i < LENGTH(configopt); i++) {
4549                         opt = &configopt[i];
4550                         if (!strncasecmp(cp, opt->optname, wordlen) &&
4551                             strlen(opt->optname) == wordlen) {
4552                                 optind = i;
4553                                 break;
4554                         }
4555                 }
4556                 if (optind == -1) {
4557                         warnx("%s: line %zd: unknown option %.*s",
4558                             filename, lineno, wordlen, cp);
4559                         return (1);
4560                 }
4561                 cp += wordlen;
4562                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4563                 /* get [selector] if any */
4564                 optsub = NULL;
4565                 if (*cp == '[') {
4566                         cp++;
4567                         wordlen = strcspn(cp, "]");
4568                         if (*cp != ']') {
4569                                 if (wordlen == 0) {
4570                                         warnx("%s: line %zd: syntax error",
4571                                             filename, lineno);
4572                                         return (1);
4573                                 }
4574                                 asprintf(&optsub, "%.*s", wordlen, cp);
4575                         }
4576                         cp += wordlen;
4577                         cp += strspn(cp, "] \t\n"); /* eat trailing */
4578                 }
4579                 cp += strspn(cp, "= \t\n"); /* eat trailing */
4580                 /* get RHS value */
4581                 optval = strdup(cp);
4582                 /* call function to deal with it all */
4583                 if (configopt[optind].func(optsub, optval,
4584                     configopt[optind].funcflags) != 0) {
4585                         fprintf(stderr, "%s line %zd: %s\n",
4586                             filename, lineno, line);
4587                         errx(1, "%s: line %zd: invalid data for %s",
4588                             filename, lineno, configopt[optind].optname);
4589                 }
4590                 free(optval);
4591                 free(optsub);
4592                 free(line);
4593         }
4594
4595         fclose(config);
4596         DNPRINTF(SWM_D_CONF, "conf_load end\n");
4597
4598         return (0);
4599 }
4600
4601 void
4602 set_child_transient(struct ws_win *win, Window *trans)
4603 {
4604         struct ws_win           *parent, *w;
4605         XWMHints                *wmh = NULL;
4606         struct swm_region       *r;
4607         struct workspace        *ws;
4608
4609         parent = find_window(win->transient);
4610         if (parent)
4611                 parent->child_trans = win;
4612         else {
4613                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
4614                     " for %lu trans %lu\n", win->id, win->transient);
4615
4616                 if (win->hints == NULL) {
4617                         fprintf(stderr, "no hints for %lu\n", win->id);
4618                         return;
4619                 }
4620
4621                 r = root_to_region(win->wa.root);
4622                 ws = r->ws;
4623                 /* parent doen't exist in our window list */
4624                 TAILQ_FOREACH(w, &ws->winlist, entry) {
4625                         if (wmh)
4626                                 XFree(wmh);
4627
4628                         if ((wmh = XGetWMHints(display, w->id)) == NULL) {
4629                                 fprintf(stderr, "can't get hints for %lu\n",
4630                                     w->id);
4631                                 continue;
4632                         }
4633
4634                         if (win->hints->window_group != wmh->window_group)
4635                                 continue;
4636
4637                         w->child_trans = win;
4638                         win->transient = w->id;
4639                         *trans = w->id;
4640                         DNPRINTF(SWM_D_MISC, "set_child_transient: asjusting "
4641                             "transient to %lu\n", win->transient);
4642                         break;
4643                 }
4644         }
4645
4646         if (wmh)
4647                 XFree(wmh);
4648 }
4649
4650 struct ws_win *
4651 manage_window(Window id)
4652 {
4653         Window                  trans = 0;
4654         struct workspace        *ws;
4655         struct ws_win           *win, *ww;
4656         int                     format, i, ws_idx, n, border_me = 0;
4657         unsigned long           nitems, bytes;
4658         Atom                    ws_idx_atom = 0, type;
4659         Atom                    *prot = NULL, *pp;
4660         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
4661         struct swm_region       *r;
4662         long                    mask;
4663         const char              *errstr;
4664         XWindowChanges          wc;
4665
4666         if ((win = find_window(id)) != NULL)
4667                 return (win);   /* already being managed */
4668
4669         /* see if we are on the unmanaged list */
4670         if ((win = find_unmanaged_window(id)) != NULL) {
4671                 DNPRINTF(SWM_D_MISC, "manage previously unmanaged window "
4672                     "%lu\n", win->id);
4673                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4674                 if (win->transient) {
4675                         set_child_transient(win, &trans);
4676                 } if (trans && (ww = find_window(trans)))
4677                         TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
4678                 else
4679                         TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
4680                 ewmh_update_actions(win);
4681                 return (win);
4682         }
4683
4684         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
4685                 errx(1, "calloc: failed to allocate memory for new window");
4686
4687         win->id = id;
4688
4689         /* Get all the window data in one shot */
4690         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
4691         if (ws_idx_atom)
4692                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
4693                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
4694         XGetWindowAttributes(display, id, &win->wa);
4695         XGetWMNormalHints(display, id, &win->sh, &mask);
4696         win->hints = XGetWMHints(display, id);
4697         XGetTransientForHint(display, id, &trans);
4698         if (trans) {
4699                 win->transient = trans;
4700                 set_child_transient(win, &trans);
4701                 DNPRINTF(SWM_D_MISC, "manage_window: win %lu transient %lu\n",
4702                     win->id, win->transient);
4703         }
4704
4705         /* get supported protocols */
4706         if (XGetWMProtocols(display, id, &prot, &n)) {
4707                 for (i = 0, pp = prot; i < n; i++, pp++) {
4708                         if (*pp == takefocus)
4709                                 win->take_focus = 1;
4710                         if (*pp == adelete)
4711                                 win->can_delete = 1;
4712                 }
4713                 if (prot)
4714                         XFree(prot);
4715         }
4716
4717         win->iconic = get_iconic(win);
4718
4719         /*
4720          * Figure out where to put the window. If it was previously assigned to
4721          * a workspace (either by spawn() or manually moving), and isn't
4722          * transient, * put it in the same workspace
4723          */
4724         r = root_to_region(win->wa.root);
4725         if (prop && win->transient == 0) {
4726                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
4727                 ws_idx = strtonum(prop, 0, 9, &errstr);
4728                 if (errstr) {
4729                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
4730                             errstr, prop);
4731                 }
4732                 ws = &r->s->ws[ws_idx];
4733         } else {
4734                 ws = r->ws;
4735                 /* this should launch transients in the same ws as parent */
4736                 if (id && trans)
4737                         if ((ww = find_window(trans)) != NULL)
4738                                 if (ws->r) {
4739                                         ws = ww->ws;
4740                                         if (ww->ws->r)
4741                                                 r = ww->ws->r;
4742                                         else
4743                                                 fprintf(stderr,
4744                                                     "fix this bug mcbride\n");
4745                                         border_me = 1;
4746                                 }
4747         }
4748
4749         /* set up the window layout */
4750         win->id = id;
4751         win->ws = ws;
4752         win->s = r->s;  /* this never changes */
4753         if (trans && (ww = find_window(trans)))
4754                 TAILQ_INSERT_AFTER(&ws->winlist, ww, win, entry);
4755         else
4756                 TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
4757
4758         win->g.w = win->wa.width;
4759         win->g.h = win->wa.height;
4760         win->g.x = win->wa.x;
4761         win->g.y = win->wa.y;
4762         win->g_floatvalid = 0;
4763         win->floatmaxed = 0;
4764         win->ewmh_flags = 0;
4765
4766         /* Set window properties so we can remember this after reincarnation */
4767         if (ws_idx_atom && prop == NULL &&
4768             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
4769                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
4770                     ws_idx_str);
4771                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
4772                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
4773         }
4774         if (prop)
4775                 XFree(prop);
4776
4777         ewmh_autoquirk(win);
4778
4779         if (XGetClassHint(display, win->id, &win->ch)) {
4780                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
4781                     win->ch.res_class, win->ch.res_name);
4782
4783                 /* java is retarded so treat it special */
4784                 if (strstr(win->ch.res_name, "sun-awt")) {
4785                         win->java = 1;
4786                         border_me = 1;
4787                 }
4788
4789                 for (i = 0; i < quirks_length; i++){
4790                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
4791                             !strcmp(win->ch.res_name, quirks[i].name)) {
4792                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
4793                                     win->ch.res_class, win->ch.res_name);
4794                                 if (quirks[i].quirk & SWM_Q_FLOAT) {
4795                                         win->floating = 1;
4796                                         border_me = 1;
4797                                 }
4798                                 win->quirks = quirks[i].quirk;
4799                         }
4800                 }
4801         }
4802
4803         /* alter window position if quirky */
4804         if (win->quirks & SWM_Q_ANYWHERE) {
4805                 win->manual = 1; /* don't center the quirky windows */
4806                 bzero(&wc, sizeof wc);
4807                 mask = 0;
4808                 if (bar_enabled && win->g.y < bar_height) {
4809                         win->g.y = wc.y = bar_height;
4810                         mask |= CWY;
4811                 }
4812                 if (win->g.w + win->g.x > WIDTH(r)) {
4813                         win->g.x = wc.x = WIDTH(r) - win->g.w - 2;
4814                         mask |= CWX;
4815                 }
4816                 border_me = 1;
4817         }
4818
4819         /* Reset font sizes (the bruteforce way; no default keybinding). */
4820         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
4821                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4822                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
4823                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4824                         fake_keypress(win, XK_KP_Add, ShiftMask);
4825         }
4826
4827         ewmh_get_win_state(win);
4828         ewmh_update_actions(win);
4829         ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
4830
4831         /* border me */
4832         if (border_me) {
4833                 bzero(&wc, sizeof wc);
4834                 wc.border_width = border_width;
4835                 mask = CWBorderWidth;
4836                 XConfigureWindow(display, win->id, mask, &wc);
4837         }
4838
4839         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
4840             PropertyChangeMask | StructureNotifyMask);
4841
4842         /* floaters need to be mapped if they are in the current workspace */
4843         if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
4844                 XMapRaised(display, win->id);
4845
4846         return (win);
4847 }
4848
4849 void
4850 free_window(struct ws_win *win)
4851 {
4852         DNPRINTF(SWM_D_MISC, "free_window:  %lu\n", win->id);
4853
4854         if (win == NULL)
4855                 return;
4856
4857         /* needed for restart wm */
4858         set_win_state(win, WithdrawnState);
4859
4860         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4861
4862         if (win->ch.res_class)
4863                 XFree(win->ch.res_class);
4864         if (win->ch.res_name)
4865                 XFree(win->ch.res_name);
4866
4867         kill_refs(win);
4868
4869         /* paint memory */
4870         memset(win, 0xff, sizeof *win); /* XXX kill later */
4871
4872         free(win);
4873 }
4874
4875 void
4876 unmanage_window(struct ws_win *win)
4877 {
4878         struct ws_win           *parent;
4879
4880         if (win == NULL)
4881                 return;
4882
4883         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
4884
4885         if (win->transient) {
4886                 parent = find_window(win->transient);
4887                 if (parent)
4888                         parent->child_trans = NULL;
4889         }
4890
4891         /* focus on root just in case */
4892         XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
4893
4894         focus_prev(win);
4895
4896         TAILQ_REMOVE(&win->ws->winlist, win, entry);
4897         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
4898
4899         kill_refs(win);
4900 }
4901
4902 void
4903 focus_magic(struct ws_win *win)
4904 {
4905         DNPRINTF(SWM_D_FOCUS, "focus_magic: %lu\n", WINID(win));
4906
4907         if (win == NULL)
4908                 return;
4909
4910         if (win->child_trans) {
4911                 /* win = parent & has a transient so focus on that */
4912                 if (win->java) {
4913                         focus_win(win->child_trans);
4914                         if (win->child_trans->take_focus)
4915                                 client_msg(win, takefocus);
4916                 } else {
4917                         /* make sure transient hasn't dissapeared */
4918                         if (validate_win(win->child_trans) == 0) {
4919                                 focus_win(win->child_trans);
4920                                 if (win->child_trans->take_focus)
4921                                         client_msg(win->child_trans, takefocus);
4922                         } else {
4923                                 win->child_trans = NULL;
4924                                 focus_win(win);
4925                                 if (win->take_focus)
4926                                         client_msg(win, takefocus);
4927                         }
4928                 }
4929         } else {
4930                 /* regular focus */
4931                 focus_win(win);
4932                 if (win->take_focus)
4933                         client_msg(win, takefocus);
4934         }
4935 }
4936
4937 void
4938 expose(XEvent *e)
4939 {
4940         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
4941 }
4942
4943 void
4944 keypress(XEvent *e)
4945 {
4946         unsigned int            i;
4947         KeySym                  keysym;
4948         XKeyEvent               *ev = &e->xkey;
4949
4950         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
4951
4952         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
4953         for (i = 0; i < keys_length; i++)
4954                 if (keysym == keys[i].keysym
4955                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
4956                    && keyfuncs[keys[i].funcid].func) {
4957                         if (keys[i].funcid == kf_spawn_custom)
4958                                 spawn_custom(
4959                                     root_to_region(ev->root),
4960                                     &(keyfuncs[keys[i].funcid].args),
4961                                     keys[i].spawn_name
4962                                     );
4963                         else
4964                                 keyfuncs[keys[i].funcid].func(
4965                                     root_to_region(ev->root),
4966                                     &(keyfuncs[keys[i].funcid].args)
4967                                     );
4968                 }
4969 }
4970
4971 void
4972 buttonpress(XEvent *e)
4973 {
4974         struct ws_win           *win;
4975         int                     i, action;
4976         XButtonPressedEvent     *ev = &e->xbutton;
4977
4978         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
4979
4980         action = root_click;
4981         if ((win = find_window(ev->window)) == NULL)
4982                 return;
4983
4984         focus_magic(win);
4985         action = client_click;
4986
4987         for (i = 0; i < LENGTH(buttons); i++)
4988                 if (action == buttons[i].action && buttons[i].func &&
4989                     buttons[i].button == ev->button &&
4990                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
4991                         buttons[i].func(win, &buttons[i].args);
4992 }
4993
4994 void
4995 configurerequest(XEvent *e)
4996 {
4997         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
4998         struct ws_win           *win;
4999         int                     new = 0;
5000         XWindowChanges          wc;
5001
5002         if ((win = find_window(ev->window)) == NULL)
5003                 if ((win = find_unmanaged_window(ev->window)) == NULL)
5004                         new = 1;
5005
5006         if (new) {
5007                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
5008                     ev->window);
5009                 bzero(&wc, sizeof wc);
5010                 wc.x = ev->x;
5011                 wc.y = ev->y;
5012                 wc.width = ev->width;
5013                 wc.height = ev->height;
5014                 wc.border_width = ev->border_width;
5015                 wc.sibling = ev->above;
5016                 wc.stack_mode = ev->detail;
5017                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
5018         } else {
5019                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
5020                     ev->window);
5021                 config_win(win, ev);
5022         }
5023 }
5024
5025 void
5026 configurenotify(XEvent *e)
5027 {
5028         struct ws_win           *win;
5029         long                    mask;
5030
5031         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
5032             e->xconfigure.window);
5033
5034         win = find_window(e->xconfigure.window);
5035         if (win) {
5036                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5037                 adjust_font(win);
5038                 if (font_adjusted)
5039                         stack();
5040         }
5041 }
5042
5043 void
5044 destroynotify(XEvent *e)
5045 {
5046         struct ws_win           *win;
5047         XDestroyWindowEvent     *ev = &e->xdestroywindow;
5048
5049         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
5050
5051         if ((win = find_window(ev->window)) == NULL) {
5052                 if ((win = find_unmanaged_window(ev->window)) == NULL)
5053                         return;
5054                 free_window(win);
5055                 return;
5056         }
5057
5058         /* make sure we focus on something */
5059         win->floating = 0;
5060
5061         unmanage_window(win);
5062         stack();
5063         free_window(win);
5064 }
5065
5066 void
5067 enternotify(XEvent *e)
5068 {
5069         XCrossingEvent          *ev = &e->xcrossing;
5070         XEvent                  cne;
5071         struct ws_win           *win;
5072 #if 0
5073         struct ws_win           *w;
5074         Window                  focus_return;
5075         int                     revert_to_return;
5076 #endif
5077         DNPRINTF(SWM_D_FOCUS, "enternotify: window: %lu mode %d detail %d root "
5078             "%lu subwindow %lu same_screen %d focus %d state %d\n",
5079             ev->window, ev->mode, ev->detail, ev->root, ev->subwindow,
5080             ev->same_screen, ev->focus, ev->state);
5081
5082         switch (focus_mode) {
5083         case SWM_FOCUS_DEFAULT:
5084                 break;
5085         case SWM_FOCUS_FOLLOW:
5086                 break;
5087         case SWM_FOCUS_SYNERGY:
5088 #if 0
5089         /*
5090          * all these checks need to be in this order because the
5091          * XCheckTypedWindowEvent relies on weeding out the previous events
5092          *
5093          * making this code an option would enable a follow mouse for focus
5094          * feature
5095          */
5096
5097         /*
5098          * state is set when we are switching workspaces and focus is set when
5099          * the window or a subwindow already has focus (occurs during restart).
5100          *
5101          * Only honor the focus flag if last_focus_event is not FocusOut,
5102          * this allows scrotwm to continue to control focus when another
5103          * program is also playing with it.
5104          */
5105         if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
5106                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
5107                 return;
5108         }
5109
5110         /*
5111          * happens when a window is created or destroyed and the border
5112          * crosses the mouse pointer and when switching ws
5113          *
5114          * we need the subwindow test to see if we came from root in order
5115          * to give focus to floaters
5116          */
5117         if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
5118             ev->subwindow == 0) {
5119                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
5120                 return;
5121         }
5122
5123         /* this window already has focus */
5124         if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
5125                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
5126                 return;
5127         }
5128
5129         /* this window is being deleted or moved to another ws */
5130         if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
5131             &cne) == True) {
5132                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
5133                 XPutBackEvent(display, &cne);
5134                 return;
5135         }
5136
5137         if ((win = find_window(ev->window)) == NULL) {
5138                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5139                 return;
5140         }
5141
5142         /*
5143          * In fullstack kill all enters unless they come from a different ws
5144          * (i.e. another region) or focus has been grabbed externally.
5145          */
5146         if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
5147             last_focus_event != FocusOut) {
5148                 XGetInputFocus(display, &focus_return, &revert_to_return);
5149                 if ((w = find_window(focus_return)) == NULL ||
5150                     w->ws == win->ws) {
5151                         DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
5152                         return;
5153                 }
5154         }
5155 #endif
5156                 break;
5157         }
5158
5159         if ((win = find_window(ev->window)) == NULL) {
5160                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5161                 return;
5162         }
5163
5164         /*
5165          * if we have more enternotifies let them handle it in due time
5166          */
5167         if (XCheckTypedEvent(display, EnterNotify, &cne) == True) {
5168                 DNPRINTF(SWM_D_EVENT,
5169                     "ignoring enternotify: got more enternotify\n");
5170                 XPutBackEvent(display, &cne);
5171                 return;
5172         }
5173
5174         focus_magic(win);
5175 }
5176
5177 /* lets us use one switch statement for arbitrary mode/detail combinations */
5178 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
5179
5180 void
5181 focusevent(XEvent *e)
5182 {
5183 #if 0
5184         struct ws_win           *win;
5185         u_int32_t               mode_detail;
5186         XFocusChangeEvent       *ev = &e->xfocus;
5187
5188         DNPRINTF(SWM_D_EVENT, "focusevent: %s window: %lu mode %d detail %d\n",
5189             ev->type == FocusIn ? "entering" : "leaving",
5190             ev->window, ev->mode, ev->detail);
5191
5192         if (last_focus_event == ev->type) {
5193                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent: bad ordering\n");
5194                 return;
5195         }
5196
5197         last_focus_event = ev->type;
5198         mode_detail = MERGE_MEMBERS(ev->mode, ev->detail);
5199
5200         switch (mode_detail) {
5201         /* synergy client focus operations */
5202         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinear):
5203         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinearVirtual):
5204
5205         /* synergy server focus operations */
5206         case MERGE_MEMBERS(NotifyWhileGrabbed, NotifyNonlinear):
5207
5208         /* Entering applications like rdesktop that mangle the pointer */
5209         case MERGE_MEMBERS(NotifyNormal, NotifyPointer):
5210
5211                 if ((win = find_window(e->xfocus.window)) != NULL && win->ws->r)
5212                         XSetWindowBorder(display, win->id,
5213                             win->ws->r->s->c[ev->type == FocusIn ?
5214                             SWM_S_COLOR_FOCUS : SWM_S_COLOR_UNFOCUS].color);
5215                 break;
5216         default:
5217                 fprintf(stderr, "ignoring focusevent\n");
5218                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent\n");
5219                 break;
5220         }
5221 #endif
5222 }
5223
5224 void
5225 mapnotify(XEvent *e)
5226 {
5227         struct ws_win           *win;
5228         XMapEvent               *ev = &e->xmap;
5229
5230         DNPRINTF(SWM_D_EVENT, "mapnotify: window: %lu\n", ev->window);
5231
5232         win = manage_window(ev->window);
5233         if (win)
5234                 set_win_state(win, NormalState);
5235 }
5236
5237 void
5238 mappingnotify(XEvent *e)
5239 {
5240         XMappingEvent           *ev = &e->xmapping;
5241
5242         XRefreshKeyboardMapping(ev);
5243         if (ev->request == MappingKeyboard)
5244                 grabkeys();
5245 }
5246
5247 void
5248 maprequest(XEvent *e)
5249 {
5250         struct ws_win           *win;
5251         struct swm_region       *r;
5252         XWindowAttributes       wa;
5253         XMapRequestEvent        *ev = &e->xmaprequest;
5254
5255         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
5256             e->xmaprequest.window);
5257
5258         if (!XGetWindowAttributes(display, ev->window, &wa))
5259                 return;
5260         if (wa.override_redirect)
5261                 return;
5262
5263         win = manage_window(e->xmaprequest.window);
5264         if (win == NULL)
5265                 return; /* can't happen */
5266
5267         stack();
5268
5269         /* make new win focused */
5270         r = root_to_region(win->wa.root);
5271         if (win->ws == r->ws)
5272                 focus_magic(win);
5273 }
5274
5275 void
5276 propertynotify(XEvent *e)
5277 {
5278         struct ws_win           *win;
5279         XPropertyEvent          *ev = &e->xproperty;
5280
5281         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
5282             ev->window);
5283
5284         win = find_window(ev->window);
5285         if (win == NULL)
5286                 return;
5287
5288         if (ev->state == PropertyDelete && ev->atom == a_swm_iconic) {
5289                 update_iconic(win, 0);
5290                 XMapRaised(display, win->id);
5291                 stack();
5292                 focus_win(win);
5293                 return;
5294         }
5295
5296         switch (ev->atom) {
5297         case XA_WM_NORMAL_HINTS:
5298 #if 0
5299                 long            mask;
5300                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5301                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
5302                 if (win->sh.flags & PMinSize) {
5303                         win->g.w = win->sh.min_width;
5304                         win->g.h = win->sh.min_height;
5305                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
5306                 }
5307                 XMoveResizeWindow(display, win->id,
5308                     win->g.x, win->g.y, win->g.w, win->g.h);
5309 #endif
5310                 if (window_name_enabled)
5311                         bar_update();
5312                 break;
5313         default:
5314                 break;
5315         }
5316 }
5317
5318 void
5319 unmapnotify(XEvent *e)
5320 {
5321         struct ws_win           *win;
5322
5323         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
5324
5325         /* determine if we need to help unmanage this window */
5326         win = find_window(e->xunmap.window);
5327         if (win == NULL)
5328                 return;
5329
5330         if (getstate(e->xunmap.window) == NormalState) {
5331                 unmanage_window(win);
5332                 stack();
5333
5334                 /* giant hack for apps that don't destroy transient windows */
5335                 /* eat a bunch of events to prevent remanaging the window */
5336                 XEvent                  cne;
5337                 while (XCheckWindowEvent(display, e->xunmap.window,
5338                     EnterWindowMask, &cne))
5339                         ;
5340                 while (XCheckWindowEvent(display, e->xunmap.window,
5341                     StructureNotifyMask, &cne))
5342                         ;
5343                 while (XCheckWindowEvent(display, e->xunmap.window,
5344                     SubstructureNotifyMask, &cne))
5345                         ;
5346                 /* resend unmap because we ated it */
5347                 XUnmapWindow(display, e->xunmap.window);
5348         }
5349 }
5350
5351 void
5352 visibilitynotify(XEvent *e)
5353 {
5354         int                     i;
5355         struct swm_region       *r;
5356
5357         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
5358             e->xvisibility.window);
5359         if (e->xvisibility.state == VisibilityUnobscured)
5360                 for (i = 0; i < ScreenCount(display); i++)
5361                         TAILQ_FOREACH(r, &screens[i].rl, entry)
5362                                 if (e->xvisibility.window == r->bar_window)
5363                                         bar_update();
5364 }
5365
5366 void
5367 clientmessage(XEvent *e)
5368 {
5369         XClientMessageEvent *ev;
5370         struct ws_win *win;
5371
5372         ev = &e->xclient;
5373
5374         win = find_window(ev->window);
5375         if (win == NULL)
5376                 return;
5377
5378         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%lx type: %ld \n",
5379             ev->window, ev->message_type);
5380
5381         if (ev->message_type == ewmh[_NET_ACTIVE_WINDOW].atom) {
5382                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW \n");
5383                 focus_win(win);
5384         }
5385         if (ev->message_type == ewmh[_NET_CLOSE_WINDOW].atom) {
5386                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW \n");
5387                 if (win->can_delete)
5388                         client_msg(win, adelete);
5389                 else
5390                         XKillClient(display, win->id);
5391         }
5392         if (ev->message_type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
5393                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_MOVERESIZE_WINDOW \n");
5394                 if (win->floating) {
5395                         if (ev->data.l[0] & (1<<8)) /* x */
5396                                 win->g.x = ev->data.l[1];
5397                         if (ev->data.l[0] & (1<<9)) /* y */
5398                                 win->g.y = ev->data.l[2];
5399                         if (ev->data.l[0] & (1<<10)) /* width */
5400                                 win->g.w = ev->data.l[3];
5401                         if (ev->data.l[0] & (1<<11)) /* height */
5402                                 win->g.h = ev->data.l[4];
5403                 }
5404                 else {
5405                         /* TODO: Change stack sizes */
5406                 }
5407                 config_win(win, NULL);
5408         }
5409         if (ev->message_type == ewmh[_NET_WM_STATE].atom) {
5410                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE \n");
5411                 ewmh_update_win_state(win, ev->data.l[1], ev->data.l[0]);
5412                 if (ev->data.l[2])
5413                         ewmh_update_win_state(win, ev->data.l[2], ev->data.l[0]);
5414
5415                 stack();
5416         }
5417 }
5418
5419 int
5420 xerror_start(Display *d, XErrorEvent *ee)
5421 {
5422         other_wm = 1;
5423         return (-1);
5424 }
5425
5426 int
5427 xerror(Display *d, XErrorEvent *ee)
5428 {
5429         /* fprintf(stderr, "error: %p %p\n", display, ee); */
5430         return (-1);
5431 }
5432
5433 int
5434 active_wm(void)
5435 {
5436         other_wm = 0;
5437         xerrorxlib = XSetErrorHandler(xerror_start);
5438
5439         /* this causes an error if some other window manager is running */
5440         XSelectInput(display, DefaultRootWindow(display),
5441             SubstructureRedirectMask);
5442         XSync(display, False);
5443         if (other_wm)
5444                 return (1);
5445
5446         XSetErrorHandler(xerror);
5447         XSync(display, False);
5448         return (0);
5449 }
5450
5451 void
5452 new_region(struct swm_screen *s, int x, int y, int w, int h)
5453 {
5454         struct swm_region       *r, *n;
5455         struct workspace        *ws = NULL;
5456         int                     i;
5457
5458         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
5459              s->idx, w, h, x, y);
5460
5461         /* remove any conflicting regions */
5462         n = TAILQ_FIRST(&s->rl);
5463         while (n) {
5464                 r = n;
5465                 n = TAILQ_NEXT(r, entry);
5466                 if (X(r) < (x + w) &&
5467                     (X(r) + WIDTH(r)) > x &&
5468                     Y(r) < (y + h) &&
5469                     (Y(r) + HEIGHT(r)) > y) {
5470                         if (r->ws->r != NULL)
5471                                 r->ws->old_r = r->ws->r;
5472                         r->ws->r = NULL;
5473                         XDestroyWindow(display, r->bar_window);
5474                         TAILQ_REMOVE(&s->rl, r, entry);
5475                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
5476                 }
5477         }
5478
5479         /* search old regions for one to reuse */
5480
5481         /* size + location match */
5482         TAILQ_FOREACH(r, &s->orl, entry)
5483                 if (X(r) == x && Y(r) == y &&
5484                     HEIGHT(r) == h && WIDTH(r) == w)
5485                         break;
5486
5487         /* size match */
5488         TAILQ_FOREACH(r, &s->orl, entry)
5489                 if (HEIGHT(r) == h && WIDTH(r) == w)
5490                         break;
5491
5492         if (r != NULL) {
5493                 TAILQ_REMOVE(&s->orl, r, entry);
5494                 /* try to use old region's workspace */
5495                 if (r->ws->r == NULL)
5496                         ws = r->ws;
5497         } else
5498                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
5499                         errx(1, "calloc: failed to allocate memory for screen");
5500
5501         /* if we don't have a workspace already, find one */
5502         if (ws == NULL) {
5503                 for (i = 0; i < SWM_WS_MAX; i++)
5504                         if (s->ws[i].r == NULL) {
5505                                 ws = &s->ws[i];
5506                                 break;
5507                         }
5508         }
5509
5510         if (ws == NULL)
5511                 errx(1, "no free workspaces\n");
5512
5513         X(r) = x;
5514         Y(r) = y;
5515         WIDTH(r) = w;
5516         HEIGHT(r) = h;
5517         r->s = s;
5518         r->ws = ws;
5519         r->ws_prior = NULL;
5520         ws->r = r;
5521         outputs++;
5522         TAILQ_INSERT_TAIL(&s->rl, r, entry);
5523 }
5524
5525 void
5526 scan_xrandr(int i)
5527 {
5528 #ifdef SWM_XRR_HAS_CRTC
5529         XRRCrtcInfo             *ci;
5530         XRRScreenResources      *sr;
5531         int                     c;
5532         int                     ncrtc = 0;
5533 #endif /* SWM_XRR_HAS_CRTC */
5534         struct swm_region       *r;
5535
5536
5537         if (i >= ScreenCount(display))
5538                 errx(1, "invalid screen");
5539
5540         /* remove any old regions */
5541         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
5542                 r->ws->old_r = r->ws->r = NULL;
5543                 XDestroyWindow(display, r->bar_window);
5544                 TAILQ_REMOVE(&screens[i].rl, r, entry);
5545                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
5546         }
5547         outputs = 0;
5548
5549         /* map virtual screens onto physical screens */
5550 #ifdef SWM_XRR_HAS_CRTC
5551         if (xrandr_support) {
5552                 sr = XRRGetScreenResources(display, screens[i].root);
5553                 if (sr == NULL)
5554                         new_region(&screens[i], 0, 0,
5555                             DisplayWidth(display, i),
5556                             DisplayHeight(display, i));
5557                 else
5558                         ncrtc = sr->ncrtc;
5559
5560                 for (c = 0, ci = NULL; c < ncrtc; c++) {
5561                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
5562                         if (ci->noutput == 0)
5563                                 continue;
5564
5565                         if (ci != NULL && ci->mode == None)
5566                                 new_region(&screens[i], 0, 0,
5567                                     DisplayWidth(display, i),
5568                                     DisplayHeight(display, i));
5569                         else
5570                                 new_region(&screens[i],
5571                                     ci->x, ci->y, ci->width, ci->height);
5572                 }
5573                 if (ci)
5574                         XRRFreeCrtcInfo(ci);
5575                 XRRFreeScreenResources(sr);
5576         } else
5577 #endif /* SWM_XRR_HAS_CRTC */
5578         {
5579                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
5580                     DisplayHeight(display, i));
5581         }
5582 }
5583
5584 void
5585 screenchange(XEvent *e) {
5586         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
5587         struct swm_region               *r;
5588         int                             i;
5589
5590         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
5591
5592         if (!XRRUpdateConfiguration(e))
5593                 return;
5594
5595         /* silly event doesn't include the screen index */
5596         for (i = 0; i < ScreenCount(display); i++)
5597                 if (screens[i].root == xe->root)
5598                         break;
5599         if (i >= ScreenCount(display))
5600                 errx(1, "screenchange: screen not found\n");
5601
5602         /* brute force for now, just re-enumerate the regions */
5603         scan_xrandr(i);
5604
5605         /* add bars to all regions */
5606         for (i = 0; i < ScreenCount(display); i++)
5607                 TAILQ_FOREACH(r, &screens[i].rl, entry)
5608                         bar_setup(r);
5609         stack();
5610 }
5611
5612 void
5613 grab_windows(void)
5614 {
5615         Window                  d1, d2, *wins = NULL;
5616         XWindowAttributes       wa;
5617         unsigned int            no;
5618         int                     i, j;
5619         long                    state, manage;
5620
5621         for (i = 0; i < ScreenCount(display); i++) {
5622                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
5623                         continue;
5624
5625                 /* attach windows to a region */
5626                 /* normal windows */
5627                 for (j = 0; j < no; j++) {
5628                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5629                             wa.override_redirect ||
5630                             XGetTransientForHint(display, wins[j], &d1))
5631                                 continue;
5632
5633                         state = getstate(wins[j]);
5634                         manage = state == IconicState;
5635                         if (wa.map_state == IsViewable || manage)
5636                                 manage_window(wins[j]);
5637                 }
5638                 /* transient windows */
5639                 for (j = 0; j < no; j++) {
5640                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5641                             wa.override_redirect)
5642                                 continue;
5643
5644                         state = getstate(wins[j]);
5645                         manage = state == IconicState;
5646                         if (XGetTransientForHint(display, wins[j], &d1) &&
5647                             manage)
5648                                 manage_window(wins[j]);
5649                 }
5650                 if (wins) {
5651                         XFree(wins);
5652                         wins = NULL;
5653                 }
5654         }
5655 }
5656
5657 void
5658 setup_screens(void)
5659 {
5660         int                     i, j, k;
5661         int                     errorbase, major, minor;
5662         struct workspace        *ws;
5663         int                     ws_idx_atom;
5664
5665         if ((screens = calloc(ScreenCount(display),
5666              sizeof(struct swm_screen))) == NULL)
5667                 errx(1, "calloc: screens");
5668
5669         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
5670
5671         /* initial Xrandr setup */
5672         xrandr_support = XRRQueryExtension(display,
5673             &xrandr_eventbase, &errorbase);
5674         if (xrandr_support)
5675                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
5676                         xrandr_support = 0;
5677
5678         /* map physical screens */
5679         for (i = 0; i < ScreenCount(display); i++) {
5680                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
5681                 screens[i].idx = i;
5682                 TAILQ_INIT(&screens[i].rl);
5683                 TAILQ_INIT(&screens[i].orl);
5684                 screens[i].root = RootWindow(display, i);
5685
5686                 /* set default colors */
5687                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
5688                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
5689                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
5690                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
5691                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
5692
5693                 /* set default cursor */
5694                 XDefineCursor(display, screens[i].root,
5695                     XCreateFontCursor(display, XC_left_ptr));
5696
5697                 /* init all workspaces */
5698                 /* XXX these should be dynamically allocated too */
5699                 for (j = 0; j < SWM_WS_MAX; j++) {
5700                         ws = &screens[i].ws[j];
5701                         ws->idx = j;
5702                         ws->focus = NULL;
5703                         ws->r = NULL;
5704                         ws->old_r = NULL;
5705                         TAILQ_INIT(&ws->winlist);
5706                         TAILQ_INIT(&ws->unmanagedlist);
5707
5708                         for (k = 0; layouts[k].l_stack != NULL; k++)
5709                                 if (layouts[k].l_config != NULL)
5710                                         layouts[k].l_config(ws,
5711                                             SWM_ARG_ID_STACKINIT);
5712                         ws->cur_layout = &layouts[0];
5713                 }
5714
5715                 scan_xrandr(i);
5716
5717                 if (xrandr_support)
5718                         XRRSelectInput(display, screens[i].root,
5719                             RRScreenChangeNotifyMask);
5720         }
5721 }
5722
5723 void
5724 setup_globals(void)
5725 {
5726         if ((bar_fonts[0] = strdup("-*-terminus-medium-*-*-*-*-*-*-*-*-*-*-*"))
5727             == NULL)
5728                 err(1, "setup_globals: strdup");
5729         if ((bar_fonts[1] = strdup("-*-times-medium-r-*-*-*-*-*-*-*-*-*-*"))
5730             == NULL)
5731                 err(1, "setup_globals: strdup");
5732         if ((bar_fonts[2] = strdup("-misc-fixed-medium-r-*-*-*-*-*-*-*-*-*-*"))
5733             == NULL)
5734                 err(1, "setup_globals: strdup");
5735         if ((spawn_term[0] = strdup("xterm")) == NULL)
5736                 err(1, "setup_globals: strdup");
5737         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
5738                 errx(1, "strdup");
5739 }
5740
5741 void
5742 workaround(void)
5743 {
5744         int                     i;
5745         Atom                    netwmcheck, netwmname, utf8_string;
5746         Window                  root, win;
5747
5748         /* work around sun jdk bugs, code from wmname */
5749         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
5750         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
5751         utf8_string = XInternAtom(display, "UTF8_STRING", False);
5752         for (i = 0; i < ScreenCount(display); i++) {
5753                 root = screens[i].root;
5754                 win = XCreateSimpleWindow(display,root, 0, 0, 1, 1, 0,
5755                     screens[i].c[SWM_S_COLOR_UNFOCUS].color,
5756                     screens[i].c[SWM_S_COLOR_UNFOCUS].color);
5757
5758                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
5759                     PropModeReplace, (unsigned char *)&win,1);
5760                 XChangeProperty(display, win, netwmcheck, XA_WINDOW, 32,
5761                     PropModeReplace, (unsigned char *)&win,1);
5762                 XChangeProperty(display, win, netwmname, utf8_string, 8,
5763                     PropModeReplace, (unsigned char*)"LG3D", strlen("LG3D"));
5764         }
5765 }
5766
5767 int
5768 main(int argc, char *argv[])
5769 {
5770         struct passwd           *pwd;
5771         struct swm_region       *r, *rr;
5772         struct ws_win           *winfocus = NULL;
5773         struct timeval          tv;
5774         union arg               a;
5775         char                    conf[PATH_MAX], *cfile = NULL;
5776         struct stat             sb;
5777         XEvent                  e;
5778         int                     xfd, i;
5779         fd_set                  rd;
5780         struct sigaction        sact;
5781
5782         start_argv = argv;
5783         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
5784             SWM_VERSION, cvstag);
5785         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
5786                 warnx("no locale support");
5787
5788         if (!(display = XOpenDisplay(0)))
5789                 errx(1, "can not open display");
5790
5791         if (active_wm())
5792                 errx(1, "other wm running");
5793
5794         /* handle some signals */
5795         bzero(&sact, sizeof(sact));
5796         sigemptyset(&sact.sa_mask);
5797         sact.sa_flags = 0;
5798         sact.sa_handler = sighdlr;
5799         sigaction(SIGINT, &sact, NULL);
5800         sigaction(SIGQUIT, &sact, NULL);
5801         sigaction(SIGTERM, &sact, NULL);
5802         sigaction(SIGHUP, &sact, NULL);
5803
5804         sact.sa_handler = sighdlr;
5805         sact.sa_flags = SA_NOCLDSTOP;
5806         sigaction(SIGCHLD, &sact, NULL);
5807
5808         astate = XInternAtom(display, "WM_STATE", False);
5809         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
5810         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
5811         takefocus = XInternAtom(display, "WM_TAKE_FOCUS", False);
5812         a_wmname = XInternAtom(display, "WM_NAME", False);
5813         a_utf8_string = XInternAtom(display, "UTF8_STRING", False);
5814         a_string = XInternAtom(display, "STRING", False);
5815         a_swm_iconic = XInternAtom(display, "_SWM_ICONIC", False);
5816
5817         /* look for local and global conf file */
5818         pwd = getpwuid(getuid());
5819         if (pwd == NULL)
5820                 errx(1, "invalid user %d", getuid());
5821
5822         setup_screens();
5823         setup_globals();
5824         setup_keys();
5825         setup_quirks();
5826         setup_spawn();
5827
5828         /* load config */
5829         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
5830         if (stat(conf, &sb) != -1) {
5831                 if (S_ISREG(sb.st_mode))
5832                         cfile = conf;
5833         } else {
5834                 /* try global conf file */
5835                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
5836                 if (!stat(conf, &sb))
5837                         if (S_ISREG(sb.st_mode))
5838                                 cfile = conf;
5839         }
5840         if (cfile)
5841                 conf_load(cfile);
5842
5843         setup_ewmh();
5844         /* set some values to work around bad programs */
5845         workaround();
5846
5847         /* grab existing windows (before we build the bars) */
5848         grab_windows();
5849
5850         /* setup all bars */
5851         for (i = 0; i < ScreenCount(display); i++)
5852                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
5853                         if (winfocus == NULL)
5854                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
5855                         bar_setup(r);
5856                 }
5857
5858         unfocus_all();
5859
5860         grabkeys();
5861         stack();
5862
5863         xfd = ConnectionNumber(display);
5864         while (running) {
5865                 while (XPending(display)) {
5866                         XNextEvent(display, &e);
5867                         if (running == 0)
5868                                 goto done;
5869                         if (e.type < LASTEvent) {
5870                                 dumpevent(&e);
5871                                 if (handler[e.type])
5872                                         handler[e.type](&e);
5873                                 else
5874                                         DNPRINTF(SWM_D_EVENT,
5875                                             "win: %lu unknown event: %d\n",
5876                                             e.xany.window, e.type);
5877                         } else {
5878                                 switch (e.type - xrandr_eventbase) {
5879                                 case RRScreenChangeNotify:
5880                                         screenchange(&e);
5881                                         break;
5882                                 default:
5883                                         DNPRINTF(SWM_D_EVENT,
5884                                             "win: %lu unknown xrandr event: "
5885                                             "%d\n", e.xany.window, e.type);
5886                                         break;
5887                                 }
5888                         }
5889                 }
5890
5891                 /* if we are being restarted go focus on first window */
5892                 if (winfocus) {
5893                         rr = winfocus->ws->r;
5894                         if (rr == NULL) {
5895                                 /* not a visible window */
5896                                 winfocus = NULL;
5897                                 continue;
5898                         }
5899                         /* move pointer to first screen if multi screen */
5900                         if (ScreenCount(display) > 1 || outputs > 1)
5901                                 XWarpPointer(display, None, rr->s[0].root,
5902                                     0, 0, 0, 0, rr->g.x,
5903                                     rr->g.y + (bar_enabled ? bar_height : 0));
5904
5905                         a.id = SWM_ARG_ID_FOCUSCUR;
5906                         focus(rr, &a);
5907                         winfocus = NULL;
5908                         continue;
5909                 }
5910
5911                 FD_ZERO(&rd);
5912                 FD_SET(xfd, &rd);
5913                 tv.tv_sec = 1;
5914                 tv.tv_usec = 0;
5915                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
5916                         if (errno != EINTR)
5917                                 DNPRINTF(SWM_D_MISC, "select failed");
5918                 if (restart_wm == 1)
5919                         restart(NULL, NULL);
5920                 if (search_resp == 1)
5921                         search_do_resp();
5922                 if (running == 0)
5923                         goto done;
5924                 if (bar_alarm) {
5925                         bar_alarm = 0;
5926                         bar_update();
5927                 }
5928         }
5929 done:
5930         teardown_ewmh();
5931         bar_extra_stop();
5932         XFreeGC(display, bar_gc);
5933         XCloseDisplay(display);
5934
5935         return (0);
5936 }