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