JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
add majordomo
[spectrwm.git] / scrotwm.c
1 /* $scrotwm$ */
2 /*
3  * Copyright (c) 2009 Marco Peereboom <marco@peereboom.us>
4  * Copyright (c) 2009 Ryan McBride <mcbride@countersiege.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 /*
19  * Much code and ideas taken from dwm under the following license:
20  * MIT/X Consortium License
21  * 
22  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
23  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
24  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
25  * 2007 Premysl Hruby <dfenze at gmail dot com>
26  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
27  * 2007 Christof Musik <christof at sendfax dot de>
28  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
29  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
30  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
31  * 
32  * Permission is hereby granted, free of charge, to any person obtaining a
33  * copy of this software and associated documentation files (the "Software"),
34  * to deal in the Software without restriction, including without limitation
35  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
36  * and/or sell copies of the Software, and to permit persons to whom the
37  * Software is furnished to do so, subject to the following conditions:
38  * 
39  * The above copyright notice and this permission notice shall be included in
40  * all copies or substantial portions of the Software.
41  * 
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  */
50
51 static const char       *cvstag = "$scrotwm$";
52
53 #define SWM_VERSION     "0.9.1"
54
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <locale.h>
61 #include <unistd.h>
62 #include <time.h>
63 #include <signal.h>
64 #include <string.h>
65 #include <util.h>
66 #include <pwd.h>
67 #include <ctype.h>
68
69 #include <sys/types.h>
70 #include <sys/time.h>
71 #include <sys/stat.h>
72 #include <sys/wait.h>
73 #include <sys/queue.h>
74 #include <sys/param.h>
75 #include <sys/select.h>
76
77 #include <X11/cursorfont.h>
78 #include <X11/keysym.h>
79 #include <X11/Xatom.h>
80 #include <X11/Xlib.h>
81 #include <X11/Xproto.h>
82 #include <X11/Xutil.h>
83 #include <X11/extensions/Xrandr.h>
84
85 #if RANDR_MAJOR < 1
86 #  error XRandR versions less than 1.0 are not supported
87 #endif
88
89 #if RANDR_MAJOR >= 1
90 #if RANDR_MINOR >= 2
91 #define SWM_XRR_HAS_CRTC
92 #endif
93 #endif
94
95 /* #define SWM_DEBUG */
96 #ifdef SWM_DEBUG
97 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
98 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
99 #define SWM_D_MISC              0x0001
100 #define SWM_D_EVENT             0x0002
101 #define SWM_D_WS                0x0004
102 #define SWM_D_FOCUS             0x0008
103 #define SWM_D_MOVE              0x0010
104 #define SWM_D_STACK             0x0020
105 #define SWM_D_MOUSE             0x0040
106 #define SWM_D_PROP              0x0080
107 #define SWM_D_CLASS             0x0100
108
109 u_int32_t               swm_debug = 0
110                             | SWM_D_MISC
111                             | SWM_D_EVENT
112                             | SWM_D_WS
113                             | SWM_D_FOCUS
114                             | SWM_D_MOVE
115                             | SWM_D_STACK
116                             | SWM_D_MOUSE
117                             | SWM_D_PROP
118                             | SWM_D_CLASS
119                             ;
120 #else
121 #define DPRINTF(x...)
122 #define DNPRINTF(n,x...)
123 #endif
124
125 #define LENGTH(x)               (sizeof x / sizeof x[0])
126 #define MODKEY                  Mod1Mask
127 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
128 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
129 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
130 #define SWM_PROPLEN             (16)
131 #define X(r)                    (r)->g.x
132 #define Y(r)                    (r)->g.y
133 #define WIDTH(r)                (r)->g.w
134 #define HEIGHT(r)               (r)->g.h
135 #define SWM_MAX_FONT_STEPS      (3)
136
137 #ifndef SWM_LIB
138 #define SWM_LIB                 "/usr/X11R6/lib/swmhack.so"
139 #endif
140
141 char                    **start_argv;
142 Atom                    astate;
143 Atom                    aprot;
144 Atom                    adelete;
145 int                     (*xerrorxlib)(Display *, XErrorEvent *);
146 int                     other_wm;
147 int                     running = 1;
148 int                     ss_enabled = 0;
149 int                     xrandr_support;
150 int                     xrandr_eventbase;
151 int                     ignore_enter = 0;
152 unsigned int            numlockmask = 0;
153 Display                 *display;
154
155 int                     cycle_empty = 0;
156 int                     cycle_visible = 0;
157 int                     term_width = 0;
158 int                     font_adjusted = 0;
159
160 /* dialog windows */
161 double                  dialog_ratio = .6;
162 /* status bar */
163 #define SWM_BAR_MAX     (256)
164 char                    *bar_argv[] = { NULL, NULL };
165 int                     bar_pipe[2];
166 char                    bar_ext[SWM_BAR_MAX];
167 char                    bar_vertext[SWM_BAR_MAX];
168 int                     bar_version = 0;
169 sig_atomic_t            bar_alarm = 0;
170 int                     bar_delay = 30;
171 int                     bar_enabled = 1;
172 int                     bar_extra = 1;
173 int                     bar_extra_running = 0;
174 int                     bar_verbose = 1;
175 int                     bar_height = 0;
176 int                     clock_enabled = 1;
177 pid_t                   bar_pid;
178 GC                      bar_gc;
179 XGCValues               bar_gcv;
180 int                     bar_fidx = 0;
181 XFontStruct             *bar_fs;
182 char                    *bar_fonts[] = {
183                             "-*-terminus-medium-*-*-*-*-*-*-*-*-*-*-*",
184                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
185                             NULL
186 };
187
188 /* terminal + args */
189 char                    *spawn_term[] = { "xterm", NULL };
190 char                    *spawn_screenshot[] = { "screenshot.sh", NULL, NULL };
191 char                    *spawn_lock[] = { "xlock", NULL };
192 char                    *spawn_initscr[] = { "initscreen.sh", NULL };
193 char                    *spawn_menu[] = { "dmenu_run", "-fn", NULL, "-nb", NULL,
194                             "-nf", NULL, "-sb", NULL, "-sf", NULL, NULL };
195
196 #define SWM_MENU_FN     (2)
197 #define SWM_MENU_NB     (4)
198 #define SWM_MENU_NF     (6)
199 #define SWM_MENU_SB     (8)
200 #define SWM_MENU_SF     (10)
201
202 /* layout manager data */
203 struct swm_geometry {
204         int                     x;
205         int                     y;
206         int                     w;
207         int                     h;
208 };
209
210 struct swm_screen;
211 struct workspace;
212
213 /* virtual "screens" */
214 struct swm_region {
215         TAILQ_ENTRY(swm_region) entry;
216         struct swm_geometry     g;
217         struct workspace        *ws;    /* current workspace on this region */
218         struct swm_screen       *s;     /* screen idx */
219         Window                  bar_window;
220 }; 
221 TAILQ_HEAD(swm_region_list, swm_region);
222
223 struct ws_win {
224         TAILQ_ENTRY(ws_win)     entry;
225         Window                  id;
226         struct swm_geometry     g;
227         int                     got_focus;
228         int                     floating;
229         int                     transient;
230         int                     manual;
231         int                     font_size_boundary[SWM_MAX_FONT_STEPS];
232         int                     font_steps;
233         int                     last_inc;
234         int                     can_delete;
235         unsigned long           quirks;
236         struct workspace        *ws;    /* always valid */
237         struct swm_screen       *s;     /* always valid, never changes */
238         XWindowAttributes       wa;
239         XSizeHints              sh;
240         XClassHint              ch;
241 };
242 TAILQ_HEAD(ws_win_list, ws_win);
243
244 /* layout handlers */
245 void    stack(void);
246 void    vertical_config(struct workspace *, int);
247 void    vertical_stack(struct workspace *, struct swm_geometry *);
248 void    horizontal_config(struct workspace *, int);
249 void    horizontal_stack(struct workspace *, struct swm_geometry *);
250 void    max_stack(struct workspace *, struct swm_geometry *);
251
252 void    grabbuttons(struct ws_win *, int);
253 void    new_region(struct swm_screen *, int, int, int, int);
254 void    update_modkey(unsigned int);
255
256 struct layout {
257         void            (*l_stack)(struct workspace *, struct swm_geometry *);
258         void            (*l_config)(struct workspace *, int);
259 } layouts[] =  {
260         /* stack,               configure */
261         { vertical_stack,       vertical_config},
262         { horizontal_stack,     horizontal_config},
263         { max_stack,            NULL},
264         { NULL,                 NULL},
265 };
266
267 #define SWM_H_SLICE             (32)
268 #define SWM_V_SLICE             (32)
269
270 /* define work spaces */
271 struct workspace {
272         int                     idx;            /* workspace index */
273         int                     restack;        /* restack on switch */
274         struct layout           *cur_layout;    /* current layout handlers */
275         struct ws_win           *focus;         /* may be NULL */
276         struct ws_win           *focus_prev;    /* may be NULL */
277         struct swm_region       *r;             /* may be NULL */
278         struct ws_win_list      winlist;        /* list of windows in ws */
279
280         /* stacker state */
281         struct {
282                                 int horizontal_msize;
283                                 int horizontal_mwin;
284                                 int horizontal_stacks;
285                                 int vertical_msize;
286                                 int vertical_mwin;
287                                 int vertical_stacks;
288         } l_state;
289 };
290
291 enum    { SWM_S_COLOR_BAR, SWM_S_COLOR_BAR_BORDER, SWM_S_COLOR_BAR_FONT,
292           SWM_S_COLOR_FOCUS, SWM_S_COLOR_UNFOCUS, SWM_S_COLOR_MAX };
293
294 /* physical screen mapping */
295 #define SWM_WS_MAX              (10)            /* XXX Too small? */
296 struct swm_screen {
297         int                     idx;            /* screen index */
298         struct swm_region_list  rl;     /* list of regions on this screen */
299         struct swm_region_list  orl;    /* list of old regions */
300         Window                  root;
301         struct workspace        ws[SWM_WS_MAX];
302
303         /* colors */
304         struct {
305                 unsigned long   color;
306                 char            *name;
307         } c[SWM_S_COLOR_MAX];
308 };
309 struct swm_screen       *screens;
310 int                     num_screens;
311
312 struct ws_win           *cur_focus = NULL;
313
314 /* args to functions */
315 union arg {
316         int                     id;
317 #define SWM_ARG_ID_FOCUSNEXT    (0)
318 #define SWM_ARG_ID_FOCUSPREV    (1)
319 #define SWM_ARG_ID_FOCUSMAIN    (2)
320 #define SWM_ARG_ID_SWAPNEXT     (3)
321 #define SWM_ARG_ID_SWAPPREV     (4)
322 #define SWM_ARG_ID_SWAPMAIN     (5)
323 #define SWM_ARG_ID_MASTERSHRINK (6)
324 #define SWM_ARG_ID_MASTERGROW   (7)
325 #define SWM_ARG_ID_MASTERADD    (8)
326 #define SWM_ARG_ID_MASTERDEL    (9)
327 #define SWM_ARG_ID_STACKRESET   (10)
328 #define SWM_ARG_ID_STACKINIT    (11)
329 #define SWM_ARG_ID_CYCLEWS_UP   (12)
330 #define SWM_ARG_ID_CYCLEWS_DOWN (13)
331 #define SWM_ARG_ID_CYCLESC_UP   (14)
332 #define SWM_ARG_ID_CYCLESC_DOWN (15)
333 #define SWM_ARG_ID_STACKINC     (16)
334 #define SWM_ARG_ID_STACKDEC     (17)
335 #define SWM_ARG_ID_SS_ALL       (0)
336 #define SWM_ARG_ID_SS_WINDOW    (1)
337 #define SWM_ARG_ID_DONTCENTER   (0)
338 #define SWM_ARG_ID_CENTER       (1)
339 #define SWM_ARG_ID_KILLWINDOW   (0)
340 #define SWM_ARG_ID_DELETEWINDOW (1)
341         char                    **argv;
342 };
343
344 /* quirks */
345 struct quirk {
346         char                    *class;
347         char                    *name;
348         unsigned long           quirk;
349 #define SWM_Q_FLOAT             (1<<0)  /* float this window */
350 #define SWM_Q_TRANSSZ           (1<<1)  /* transiend window size too small */
351 #define SWM_Q_ANYWHERE          (1<<2)  /* don't position this window */
352 #define SWM_Q_XTERM_FONTADJ     (1<<3)  /* adjust xterm fonts when resizing */
353 #define SWM_Q_FULLSCREEN        (1<<4)  /* remove border */
354 } quirks[] = {
355         { "MPlayer",            "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN },
356         { "OpenOffice.org 2.4", "VCLSalFrame",  SWM_Q_FLOAT },
357         { "OpenOffice.org 3.0", "VCLSalFrame",  SWM_Q_FLOAT },
358         { "Firefox-bin",        "firefox-bin",  SWM_Q_TRANSSZ },
359         { "Firefox",            "Dialog",       SWM_Q_FLOAT },
360         { "Gimp",               "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE },
361         { "XTerm",              "xterm",        SWM_Q_XTERM_FONTADJ },
362         { "xine",               "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE },
363         { "Xitk",               "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE },
364         { "xine",               "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE },
365         { "Xitk",               "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE },
366         { "xine",               "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT },
367         { "pcb",                "pcb",          SWM_Q_FLOAT },
368         { NULL,                 NULL,           0},
369 };
370
371 /* events */
372 void                    expose(XEvent *);
373 void                    keypress(XEvent *);
374 void                    buttonpress(XEvent *);
375 void                    configurerequest(XEvent *);
376 void                    configurenotify(XEvent *);
377 void                    destroynotify(XEvent *);
378 void                    enternotify(XEvent *);
379 void                    focusin(XEvent *);
380 void                    focusout(XEvent *);
381 void                    mappingnotify(XEvent *);
382 void                    maprequest(XEvent *);
383 void                    propertynotify(XEvent *);
384 void                    unmapnotify(XEvent *);
385 void                    visibilitynotify(XEvent *);
386
387 void                    (*handler[LASTEvent])(XEvent *) = {
388                                 [Expose] = expose,
389                                 [KeyPress] = keypress,
390                                 [ButtonPress] = buttonpress,
391                                 [ConfigureRequest] = configurerequest,
392                                 [ConfigureNotify] = configurenotify,
393                                 [DestroyNotify] = destroynotify,
394                                 [EnterNotify] = enternotify,
395                                 [FocusIn] = focusin,
396                                 [FocusOut] = focusout,
397                                 [MappingNotify] = mappingnotify,
398                                 [MapRequest] = maprequest,
399                                 [PropertyNotify] = propertynotify,
400                                 [UnmapNotify] = unmapnotify,
401                                 [VisibilityNotify] = visibilitynotify,
402 };
403
404 unsigned long
405 name_to_color(char *colorname)
406 {
407         Colormap                cmap;
408         Status                  status;
409         XColor                  screen_def, exact_def;
410         unsigned long           result = 0;
411         char                    cname[32] = "#";
412
413         cmap = DefaultColormap(display, screens[0].idx);
414         status = XAllocNamedColor(display, cmap, colorname,
415             &screen_def, &exact_def);
416         if (!status) {
417                 strlcat(cname, colorname + 2, sizeof cname - 1);
418                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
419                     &exact_def);
420         }
421         if (status)
422                 result = screen_def.pixel;
423         else
424                 fprintf(stderr, "color '%s' not found.\n", colorname);
425
426         return (result);
427 }
428
429 void
430 setscreencolor(char *val, int i, int c)
431 {
432         if (i > 0 && i <= ScreenCount(display)) {
433                 screens[i - 1].c[c].color = name_to_color(val);
434                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
435                         errx(1, "strdup");
436         } else if (i == -1) {
437                 for (i = 0; i < ScreenCount(display); i++)
438                         screens[i].c[c].color = name_to_color(val);
439                         if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
440                                 errx(1, "strdup");
441         } else
442                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
443                     i, ScreenCount(display));
444 }
445
446 void
447 custom_region(char *val)
448 {
449         unsigned int                    sidx, x, y, w, h;
450
451         if (sscanf(val, "screen[%u]:%ux%u+%u+%u", &sidx, &w, &h, &x, &y) != 5)
452                 errx(1, "invalid custom region, "
453                     "should be 'screen[<n>]:<n>x<n>+<n>+<n>\n");
454         if (sidx < 1 || sidx > ScreenCount(display))
455                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
456                     sidx, ScreenCount(display));
457         sidx--;
458
459         if (w < 1 || h < 1)
460                 errx(1, "region %ux%u+%u+%u too small\n", w, h, x, y);
461
462         if (x  < 0 || x > DisplayWidth(display, sidx) ||
463             y < 0 || y > DisplayHeight(display, sidx) ||
464             w + x > DisplayWidth(display, sidx) ||
465             h + y > DisplayHeight(display, sidx))
466                 errx(1, "region %ux%u+%u+%u not within screen boundaries "
467                     "(%ux%u)\n", w, h, x, y,
468                     DisplayWidth(display, sidx), DisplayHeight(display, sidx));
469             
470         new_region(&screens[sidx], x, y, w, h);
471 }
472
473 int
474 varmatch(char *var, char *name, int *index)
475 {
476         char                    *p, buf[5];
477         int                     i;
478
479         i = strncmp(var, name, 255);
480         if (index == NULL)
481                 return (i);
482
483         *index = -1;
484         if (i <= 0)
485                 return (i);
486         p = var + strlen(name);
487         if (*p++ != '[')
488                 return (i);
489         bzero(buf, sizeof buf);
490         i = 0;
491         while (isdigit(*p) && i < sizeof buf)
492                 buf[i++] = *p++;
493         if (i == 0 || i >= sizeof buf || *p != ']')
494                 return (1);
495         *index = strtonum(buf, 0, 99, NULL);
496         return (0);
497 }
498
499 /* conf file stuff */
500 #define SWM_CONF_WS     "\n= \t"
501 #define SWM_CONF_FILE   "scrotwm.conf"
502 int
503 conf_load(char *filename)
504 {
505         FILE                    *config;
506         char                    *line, *cp, *var, *val;
507         size_t                  len, lineno = 0;
508         int                     i, sc;
509         unsigned int            modkey;
510
511         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
512
513         if (filename == NULL)
514                 return (1);
515
516         if ((config = fopen(filename, "r")) == NULL)
517                 return (1);
518
519         for (sc = ScreenCount(display);;) {
520                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
521                         if (feof(config))
522                                 break;
523                 cp = line;
524                 cp += (long)strspn(cp, SWM_CONF_WS);
525                 if (cp[0] == '\0') {
526                         /* empty line */
527                         free(line);
528                         continue;
529                 }
530                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
531                         break;
532                 cp += (long)strspn(cp, SWM_CONF_WS);
533                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
534                         break;
535
536                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
537                 switch (var[0]) {
538                 case 'b':
539                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
540                                 bar_enabled = atoi(val);
541                         else if (!varmatch(var, "bar_border", &i))
542                                 setscreencolor(val, i, SWM_S_COLOR_BAR_BORDER);
543                         else if (!varmatch(var, "bar_color", &i))
544                                 setscreencolor(val, i, SWM_S_COLOR_BAR);
545                         else if (!varmatch(var, "bar_font_color", &i))
546                                 setscreencolor(val, i, SWM_S_COLOR_BAR_FONT);
547                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
548                                 asprintf(&bar_fonts[0], "%s", val);
549                         else if (!strncmp(var, "bar_action", strlen("bar_action")))
550                                 asprintf(&bar_argv[0], "%s", val);
551                         else if (!strncmp(var, "bar_delay", strlen("bar_delay")))
552                                 bar_delay = atoi(val);
553                         else
554                                 goto bad;
555                         break;
556
557                 case 'c':
558                         if (!strncmp(var, "clock_enabled", strlen("clock_enabled")))
559                                 clock_enabled = atoi(val);
560                         else if (!varmatch(var, "color_focus", &i))
561                                 setscreencolor(val, i, SWM_S_COLOR_FOCUS);
562                         else if (!varmatch(var, "color_unfocus", &i))
563                                 setscreencolor(val, i, SWM_S_COLOR_UNFOCUS);
564                         else if (!strncmp(var, "cycle_empty", strlen("cycle_empty")))
565                                 cycle_visible = atoi(val);
566                         else if (!strncmp(var, "cycle_visible", strlen("cycle_visible")))
567                                 cycle_visible = atoi(val);
568                         else
569                                 goto bad;
570                         break;
571
572                 case 'd':
573                         if (!strncmp(var, "dialog_ratio",
574                             strlen("dialog_ratio"))) {
575                                 dialog_ratio = atof(val);
576                                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
577                                         dialog_ratio = .6;
578                         } else
579                                 goto bad;
580                         break;
581
582                 case 'm':
583                         if (!strncmp(var, "modkey", strlen("modkey"))) {
584                                 modkey = MODKEY;
585                                 if (!strncmp(val, "Mod2", strlen("Mod2")))
586                                         modkey = Mod2Mask;
587                                 else if (!strncmp(val, "Mod3", strlen("Mod3")))
588                                         modkey = Mod3Mask;
589                                 else if (!strncmp(val, "Mod4", strlen("Mod4")))
590                                         modkey = Mod4Mask;
591                                 else
592                                         modkey = Mod1Mask;
593                                 update_modkey(modkey);
594                         } else
595                                 goto bad;
596                         break;
597
598                 case 'r':
599                         if (!strncmp(var, "region", strlen("region")))
600                                 custom_region(val);
601                         else
602                                 goto bad;
603                         break;
604
605                 case 's':
606                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
607                                 asprintf(&spawn_term[0], "%s", val);
608                         else if (!strncmp(var, "screenshot_enabled",
609                             strlen("screenshot_enabled")))
610                                 ss_enabled = atoi(val);
611                         else if (!strncmp(var, "screenshot_app",
612                             strlen("screenshot_app")))
613                                 asprintf(&spawn_screenshot[0], "%s", val);
614                         else
615                                 goto bad;
616                         break;
617
618                 case 't':
619                         if (!strncmp(var, "term_width", strlen("term_width")))
620                                 term_width = atoi(val);
621                         else
622                                 goto bad;
623                         break;
624
625                 default:
626                         goto bad;
627                 }
628                 free(line);
629         }
630
631         fclose(config);
632         return (0);
633
634 bad:
635         errx(1, "invalid conf file entry: %s=%s", var, val);
636 }
637
638 void
639 socket_setnonblock(int fd)
640 {
641         int                     flags;
642
643         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
644                 err(1, "fcntl F_GETFL");
645         flags |= O_NONBLOCK;
646         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
647                 err(1, "fcntl F_SETFL");
648 }
649
650 void
651 bar_print(struct swm_region *r, char *s)
652 {
653         XClearWindow(display, r->bar_window);
654         XSetForeground(display, bar_gc, r->s->c[SWM_S_COLOR_BAR_FONT].color);
655         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent, s,
656             strlen(s));
657 }
658
659 void
660 bar_extra_stop(void)
661 {
662         if (bar_pipe[0]) {
663                 close(bar_pipe[0]);
664                 bzero(bar_pipe, sizeof bar_pipe);
665         }
666         if (bar_pid) {
667                 kill(bar_pid, SIGTERM);
668                 bar_pid = 0;
669         }
670         strlcpy(bar_ext, "", sizeof bar_ext);
671         bar_extra = 0;
672 }
673
674 void
675 bar_update(void)
676 {
677         time_t                  tmt;
678         struct tm               tm;
679         struct swm_region       *r;
680         int                     i, x;
681         size_t                  len;
682         char                    s[SWM_BAR_MAX];
683         char                    loc[SWM_BAR_MAX];
684         char                    *b;
685
686         if (bar_enabled == 0)
687                 return;
688         if (bar_extra && bar_extra_running) {
689                 /* ignore short reads; it'll correct itself */
690                 while ((b = fgetln(stdin, &len)) != NULL)
691                         if (b && b[len - 1] == '\n') {
692                                 b[len - 1] = '\0';
693                                 strlcpy(bar_ext, b, sizeof bar_ext);
694                         }
695                 if (b == NULL && errno != EAGAIN) {
696                         fprintf(stderr, "bar_extra failed: errno: %d %s\n",
697                             errno, strerror(errno));
698                         bar_extra_stop();
699                 }
700         } else
701                 strlcpy(bar_ext, "", sizeof bar_ext);
702
703         if (clock_enabled == 0)
704                 strlcpy(s, "", sizeof s);
705         else {
706                 time(&tmt);
707                 localtime_r(&tmt, &tm);
708                 strftime(s, sizeof s, "%a %b %d %R %Z %Y    ", &tm);
709         }
710         for (i = 0; i < ScreenCount(display); i++) {
711                 x = 1;
712                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
713                         snprintf(loc, sizeof loc, "%d:%d    %s%s    %s",
714                             x++, r->ws->idx + 1, s, bar_ext, bar_vertext);
715                         bar_print(r, loc);
716                 }
717         }
718         XSync(display, False);
719         alarm(bar_delay);
720 }
721
722 void
723 bar_signal(int sig)
724 {
725         bar_alarm = 1;
726 }
727
728 void
729 bar_toggle(struct swm_region *r, union arg *args)
730 {
731         struct swm_region       *tmpr;
732         int                     i, j, sc = ScreenCount(display);
733
734         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
735
736         if (bar_enabled)
737                 for (i = 0; i < sc; i++)
738                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
739                                 XUnmapWindow(display, tmpr->bar_window);
740         else
741                 for (i = 0; i < sc; i++)
742                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
743                                 XMapRaised(display, tmpr->bar_window);
744
745         bar_enabled = !bar_enabled;
746         for (i = 0; i < sc; i++)
747                 for (j = 0; j < SWM_WS_MAX; j++)
748                         screens[i].ws[j].restack = 1;
749
750         stack();
751         /* must be after stack */
752         bar_update();
753 }
754
755 void
756 bar_refresh(void)
757 {
758         XSetWindowAttributes    wa;
759         struct swm_region       *r;
760         int                     i;
761
762         /* do this here because the conf file is in memory */
763         if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
764                 /* launch external status app */
765                 bar_extra_running = 1;
766                 if (pipe(bar_pipe) == -1)
767                         err(1, "pipe error");
768                 socket_setnonblock(bar_pipe[0]);
769                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
770                 if (dup2(bar_pipe[0], 0) == -1)
771                         errx(1, "dup2");
772                 if (dup2(bar_pipe[1], 1) == -1)
773                         errx(1, "dup2");
774                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
775                         err(1, "could not disable SIGPIPE");
776                 switch (bar_pid = fork()) {
777                 case -1:
778                         err(1, "cannot fork");
779                         break;
780                 case 0: /* child */
781                         close(bar_pipe[0]);
782                         execvp(bar_argv[0], bar_argv);
783                         err(1, "%s external app failed", bar_argv[0]);
784                         break;
785                 default: /* parent */
786                         close(bar_pipe[1]);
787                         break;
788                 }
789         }
790
791         bzero(&wa, sizeof wa);
792         for (i = 0; i < ScreenCount(display); i++)
793                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
794                         wa.border_pixel =
795                             screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
796                         wa.background_pixel =
797                             screens[i].c[SWM_S_COLOR_BAR].color;
798                         XChangeWindowAttributes(display, r->bar_window,
799                             CWBackPixel | CWBorderPixel, &wa);
800                 }
801         bar_update();
802 }
803
804 void
805 bar_setup(struct swm_region *r)
806 {
807         int                     i;
808
809         for (i = 0; bar_fonts[i] != NULL; i++) {
810                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
811                 if (bar_fs) {
812                         bar_fidx = i;
813                         break;
814                 }
815         }
816         if (bar_fonts[i] == NULL)
817                         errx(1, "couldn't load font");
818         bar_height = bar_fs->ascent + bar_fs->descent + 3;
819
820         r->bar_window = XCreateSimpleWindow(display, 
821             r->s->root, X(r), Y(r), WIDTH(r) - 2, bar_height - 2,
822             1, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
823             r->s->c[SWM_S_COLOR_BAR].color);
824         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
825         XSetFont(display, bar_gc, bar_fs->fid);
826         XSelectInput(display, r->bar_window, VisibilityChangeMask);
827         if (bar_enabled)
828                 XMapRaised(display, r->bar_window);
829         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
830
831         if (signal(SIGALRM, bar_signal) == SIG_ERR)
832                 err(1, "could not install bar_signal");
833         bar_refresh();
834 }
835
836 void
837 version(struct swm_region *r, union arg *args)
838 {
839         bar_version = !bar_version;
840         if (bar_version)
841                 strlcpy(bar_vertext, cvstag, sizeof bar_vertext);
842         else
843                 strlcpy(bar_vertext, "", sizeof bar_vertext);
844         bar_update();
845 }
846
847 void
848 client_msg(struct ws_win *win, Atom a)
849 {
850         XClientMessageEvent     cm;
851
852         bzero(&cm, sizeof cm);
853         cm.type = ClientMessage;
854         cm.window = win->id;
855         cm.message_type = aprot;
856         cm.format = 32;
857         cm.data.l[0] = a;
858         cm.data.l[1] = CurrentTime;
859         XSendEvent(display, win->id, False, 0L, (XEvent *)&cm);
860 }
861
862 void
863 config_win(struct ws_win *win)
864 {
865         XConfigureEvent         ce;
866
867         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
868             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
869         ce.type = ConfigureNotify;
870         ce.display = display;
871         ce.event = win->id;
872         ce.window = win->id;
873         ce.x = win->g.x;
874         ce.y = win->g.y;
875         ce.width = win->g.w;
876         ce.height = win->g.h;
877         ce.border_width = 1; /* XXX store this! */
878         ce.above = None;
879         ce.override_redirect = False;
880         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
881 }
882
883 int
884 count_win(struct workspace *ws, int count_transient)
885 {
886         struct ws_win           *win;
887         int                     count = 0;
888
889         TAILQ_FOREACH(win, &ws->winlist, entry) {
890                 if (count_transient == 0 && win->floating)
891                         continue;
892                 if (count_transient == 0 && win->transient)
893                         continue;
894                 count++;
895         }
896         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
897
898         return (count);
899 }
900
901 void
902 quit(struct swm_region *r, union arg *args)
903 {
904         DNPRINTF(SWM_D_MISC, "quit\n");
905         running = 0;
906 }
907
908 void
909 unmap_all(void)
910 {
911         struct ws_win           *win;
912         int                     i, j;
913
914         for (i = 0; i < ScreenCount(display); i++)
915                 for (j = 0; j < SWM_WS_MAX; j++)
916                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
917                                 XUnmapWindow(display, win->id);
918 }
919
920 void
921 fake_keypress(struct ws_win *win, int keysym, int modifiers)
922 {
923         XKeyEvent event;
924
925         event.display = display;        /* Ignored, but what the hell */
926         event.window = win->id;
927         event.root = win->s->root;
928         event.subwindow = None;
929         event.time = CurrentTime;
930         event.x = win->g.x;
931         event.y = win->g.y;
932         event.x_root = 1;
933         event.y_root = 1;
934         event.same_screen = True;
935         event.keycode = XKeysymToKeycode(display, keysym);
936         event.state = modifiers;
937
938         event.type = KeyPress;
939         XSendEvent(event.display, event.window, True,
940             KeyPressMask, (XEvent *)&event);
941
942         event.type = KeyRelease;
943         XSendEvent(event.display, event.window, True,
944             KeyPressMask, (XEvent *)&event);
945
946 }
947
948 void
949 restart(struct swm_region *r, union arg *args)
950 {
951         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
952
953         /* disable alarm because the following code may not be interrupted */
954         alarm(0);
955         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
956                 errx(1, "can't disable alarm");
957
958         bar_extra_stop();
959         bar_extra = 1;
960         unmap_all();
961         XCloseDisplay(display);
962         execvp(start_argv[0], start_argv);
963         fprintf(stderr, "execvp failed\n");
964         perror(" failed");
965         quit(NULL, NULL);
966 }
967
968 struct swm_region *
969 root_to_region(Window root)
970 {
971         struct swm_region       *r = NULL;
972         Window                  rr, cr;
973         int                     i, x, y, wx, wy;
974         unsigned int            mask;
975
976         for (i = 0; i < ScreenCount(display); i++)
977                 if (screens[i].root == root)
978                         break;
979
980         if (XQueryPointer(display, screens[i].root, 
981             &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
982                 /* choose a region based on pointer location */
983                 TAILQ_FOREACH(r, &screens[i].rl, entry)
984                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
985                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
986                                 break;
987         }
988
989         if (r == NULL)
990                 r = TAILQ_FIRST(&screens[i].rl);
991
992         return (r);
993 }
994
995 struct ws_win *
996 find_window(Window id)
997 {
998         struct ws_win           *win;
999         int                     i, j;
1000
1001         for (i = 0; i < ScreenCount(display); i++)
1002                 for (j = 0; j < SWM_WS_MAX; j++)
1003                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1004                                 if (id == win->id)
1005                                         return (win);
1006         return (NULL);
1007 }
1008
1009 void
1010 spawn(struct swm_region *r, union arg *args)
1011 {
1012         char                    *ret;
1013         int                     si;
1014
1015         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
1016         /*
1017          * The double-fork construct avoids zombie processes and keeps the code
1018          * clean from stupid signal handlers.
1019          */
1020         if (fork() == 0) {
1021                 if (fork() == 0) {
1022                         if (display)
1023                                 close(ConnectionNumber(display));
1024                         setenv("LD_PRELOAD", SWM_LIB, 1);
1025                         if (asprintf(&ret, "%d", r->ws->idx)) {
1026                                 setenv("_SWM_WS", ret, 1);
1027                                 free(ret);
1028                         }
1029                         if (asprintf(&ret, "%d", getpid())) {
1030                                 setenv("_SWM_PID", ret, 1);
1031                                 free(ret);
1032                         }
1033                         setsid();
1034                         /* kill stdin, mplayer, ssh-add etc. need that */
1035                         si = open("/dev/null", O_RDONLY, 0);
1036                         if (si == -1)
1037                                 err(1, "open /dev/null");
1038                         if (dup2(si, 0) == -1)
1039                                 err(1, "dup2 /dev/null");
1040                         execvp(args->argv[0], args->argv);
1041                         fprintf(stderr, "execvp failed\n");
1042                         perror(" failed");
1043                 }
1044                 exit(0);
1045         }
1046         wait(0);
1047 }
1048
1049 void
1050 spawnterm(struct swm_region *r, union arg *args)
1051 {
1052         DNPRINTF(SWM_D_MISC, "spawnterm\n");
1053
1054         if (term_width)
1055                 setenv("_SWM_XTERM_FONTADJ", "", 1);
1056         spawn(r, args);
1057 }
1058
1059 void
1060 spawnmenu(struct swm_region *r, union arg *args)
1061 {
1062         DNPRINTF(SWM_D_MISC, "spawnmenu\n");
1063
1064         spawn_menu[SWM_MENU_FN] = bar_fonts[bar_fidx];
1065         spawn_menu[SWM_MENU_NB] = r->s->c[SWM_S_COLOR_BAR].name;
1066         spawn_menu[SWM_MENU_NF] = r->s->c[SWM_S_COLOR_BAR_FONT].name;
1067         spawn_menu[SWM_MENU_SB] = r->s->c[SWM_S_COLOR_BAR_BORDER].name;
1068         spawn_menu[SWM_MENU_SF] = r->s->c[SWM_S_COLOR_BAR].name;
1069
1070         spawn(r, args);
1071 }
1072
1073 void
1074 unfocus_win(struct ws_win *win)
1075 {
1076         if (win == NULL)
1077                 return;
1078
1079         if (win->ws->focus != win && win->ws->focus != NULL)
1080                 win->ws->focus_prev = win->ws->focus;
1081
1082         if (win->ws->r == NULL)
1083                 return;
1084
1085         grabbuttons(win, 0);
1086         XSetWindowBorder(display, win->id,
1087             win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1088         win->got_focus = 0;
1089         if (win->ws->focus == win)
1090                 win->ws->focus = NULL;
1091         if (cur_focus == win)
1092                 cur_focus = NULL;
1093 }
1094
1095 void
1096 unfocus_all(void)
1097 {
1098         struct ws_win           *win;
1099         int                     i, j;
1100
1101         DNPRINTF(SWM_D_FOCUS, "unfocus_all:\n");
1102
1103         for (i = 0; i < ScreenCount(display); i++)
1104                 for (j = 0; j < SWM_WS_MAX; j++)
1105                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1106                                 unfocus_win(win);
1107 }
1108
1109 void
1110 focus_win(struct ws_win *win)
1111 {
1112         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
1113
1114         if (win == NULL)
1115                 return;
1116
1117         if (cur_focus)
1118                 unfocus_win(cur_focus);
1119         if (win->ws->focus) {
1120                 /* probably shouldn't happen due to the previous unfocus_win */
1121                 DNPRINTF(SWM_D_FOCUS, "unfocusing win->ws->focus: %lu\n",
1122                     win->ws->focus->id);
1123                 unfocus_win(win->ws->focus);
1124         }
1125         win->ws->focus = win;
1126         if (win->ws->r != NULL) {
1127                 cur_focus = win;
1128                 if (!win->got_focus) {
1129                         XSetWindowBorder(display, win->id,
1130                             win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
1131                         grabbuttons(win, 1);
1132                 }
1133                 win->got_focus = 1;
1134                 XSetInputFocus(display, win->id,
1135                     RevertToPointerRoot, CurrentTime);
1136         }
1137 }
1138
1139 void
1140 switchws(struct swm_region *r, union arg *args)
1141 {
1142         int                     wsid = args->id;
1143         struct swm_region       *this_r, *other_r;
1144         struct ws_win           *win;
1145         struct workspace        *new_ws, *old_ws;
1146
1147         this_r = r;
1148         old_ws = this_r->ws;
1149         new_ws = &this_r->s->ws[wsid];
1150
1151         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
1152             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
1153             old_ws->idx, wsid);
1154
1155         if (new_ws == old_ws)
1156                 return;
1157
1158         other_r = new_ws->r;
1159         if (!other_r) {
1160                 /* if the other workspace is hidden, switch windows */
1161                 /* map new window first to prevent ugly blinking */
1162                 old_ws->r = NULL;
1163                 old_ws->restack = 1;
1164
1165                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
1166                         XMapRaised(display, win->id);
1167
1168                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
1169                         XUnmapWindow(display, win->id);
1170         } else {
1171                 other_r->ws = old_ws;
1172                 old_ws->r = other_r;
1173         }
1174         this_r->ws = new_ws;
1175         new_ws->r = this_r;
1176
1177         ignore_enter = 1;
1178         /* set focus */
1179         if (new_ws->focus == NULL)
1180                 new_ws->focus = TAILQ_FIRST(&new_ws->winlist);
1181         if (new_ws->focus)
1182                 focus_win(new_ws->focus);
1183         stack();
1184         bar_update();
1185 }
1186
1187 void
1188 cyclews(struct swm_region *r, union arg *args)
1189 {
1190         union                   arg a;
1191         struct swm_screen       *s = r->s;
1192
1193         DNPRINTF(SWM_D_WS, "cyclews id %d "
1194             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
1195             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1196
1197         a.id = r->ws->idx;
1198         do {
1199                 switch (args->id) {
1200                 case SWM_ARG_ID_CYCLEWS_UP:
1201                         if (a.id < SWM_WS_MAX - 1)
1202                                 a.id++;
1203                         else
1204                                 a.id = 0;
1205                         break;
1206                 case SWM_ARG_ID_CYCLEWS_DOWN:
1207                         if (a.id > 0)
1208                                 a.id--;
1209                         else
1210                                 a.id = SWM_WS_MAX - 1;
1211                         break;
1212                 default:
1213                         return;
1214                 };
1215
1216                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
1217                         continue;
1218                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
1219                         continue;
1220
1221                 switchws(r, &a);
1222         } while (a.id != r->ws->idx);
1223 }
1224
1225 void
1226 cyclescr(struct swm_region *r, union arg *args)
1227 {
1228         struct swm_region       *rr;
1229         int                     i;
1230
1231         i = r->s->idx;
1232         switch (args->id) {
1233         case SWM_ARG_ID_CYCLESC_UP:
1234                 rr = TAILQ_NEXT(r, entry);
1235                 if (rr == NULL)
1236                         rr = TAILQ_FIRST(&screens[i].rl);
1237                 break;
1238         case SWM_ARG_ID_CYCLESC_DOWN:
1239                 rr = TAILQ_PREV(r, swm_region_list, entry);
1240                 if (rr == NULL)
1241                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
1242                 break;
1243         default:
1244                 return;
1245         };
1246         unfocus_all();
1247         XSetInputFocus(display, PointerRoot, RevertToPointerRoot, CurrentTime);
1248         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, rr->g.x,
1249             rr->g.y + bar_enabled ? bar_height : 0);
1250 }
1251
1252 void
1253 swapwin(struct swm_region *r, union arg *args)
1254 {
1255         struct ws_win           *target, *source;
1256         struct ws_win_list      *wl;
1257
1258
1259         DNPRINTF(SWM_D_WS, "swapwin id %d "
1260             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
1261             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1262         if (cur_focus == NULL)
1263                 return;
1264
1265         source = cur_focus;
1266         wl = &source->ws->winlist;
1267
1268         switch (args->id) {
1269         case SWM_ARG_ID_SWAPPREV:
1270                 target = TAILQ_PREV(source, ws_win_list, entry);
1271                 TAILQ_REMOVE(wl, cur_focus, entry);
1272                 if (target == NULL)
1273                         TAILQ_INSERT_TAIL(wl, source, entry);
1274                 else
1275                         TAILQ_INSERT_BEFORE(target, source, entry);
1276                 break;
1277         case SWM_ARG_ID_SWAPNEXT: 
1278                 target = TAILQ_NEXT(source, entry);
1279                 TAILQ_REMOVE(wl, source, entry);
1280                 if (target == NULL)
1281                         TAILQ_INSERT_HEAD(wl, source, entry);
1282                 else
1283                         TAILQ_INSERT_AFTER(wl, target, source, entry);
1284                 break;
1285         case SWM_ARG_ID_SWAPMAIN:
1286                 target = TAILQ_FIRST(wl);
1287                 if (target == source) {
1288                         if (source->ws->focus_prev != NULL &&
1289                             source->ws->focus_prev != target)  
1290                                 
1291                                 source = source->ws->focus_prev;
1292                         else
1293                                 return;
1294                 }
1295                 source->ws->focus_prev = target;
1296                 TAILQ_REMOVE(wl, target, entry);
1297                 TAILQ_INSERT_BEFORE(source, target, entry);
1298                 TAILQ_REMOVE(wl, source, entry);
1299                 TAILQ_INSERT_HEAD(wl, source, entry);
1300                 break;
1301         default:
1302                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
1303                 return;
1304         }
1305
1306         ignore_enter = 1;
1307         stack();
1308 }
1309
1310 void
1311 focus(struct swm_region *r, union arg *args)
1312 {
1313         struct ws_win           *winfocus, *winlostfocus;
1314         struct ws_win_list      *wl;
1315
1316         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
1317         if (cur_focus == NULL)
1318                 return;
1319
1320         wl = &cur_focus->ws->winlist;
1321
1322         winlostfocus = cur_focus;
1323
1324         switch (args->id) {
1325         case SWM_ARG_ID_FOCUSPREV:
1326                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
1327                 if (winfocus == NULL)
1328                         winfocus = TAILQ_LAST(wl, ws_win_list);
1329                 break;
1330
1331         case SWM_ARG_ID_FOCUSNEXT:
1332                 winfocus = TAILQ_NEXT(cur_focus, entry);
1333                 if (winfocus == NULL)
1334                         winfocus = TAILQ_FIRST(wl);
1335                 break;
1336
1337         case SWM_ARG_ID_FOCUSMAIN:
1338                 winfocus = TAILQ_FIRST(wl);
1339                 if (winfocus == cur_focus)
1340                         winfocus = cur_focus->ws->focus_prev;
1341                 if (winfocus == NULL)
1342                         return;
1343                 break;
1344
1345         default:
1346                 return;
1347         }
1348
1349         if (winfocus == winlostfocus || winfocus == NULL)
1350                 return;
1351
1352         XMapRaised(display, winfocus->id);
1353         focus_win(winfocus);
1354         XSync(display, False);
1355 }
1356
1357 void
1358 cycle_layout(struct swm_region *r, union arg *args)
1359 {
1360         struct workspace        *ws = r->ws;
1361
1362         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
1363
1364         ws->cur_layout++;
1365         if (ws->cur_layout->l_stack == NULL)
1366                 ws->cur_layout = &layouts[0];
1367         ignore_enter = 1;
1368         stack();
1369 }
1370
1371 void
1372 stack_config(struct swm_region *r, union arg *args)
1373 {
1374         struct workspace        *ws = r->ws;
1375
1376         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
1377             args->id, ws->idx);
1378
1379         if (ws->cur_layout->l_config != NULL)
1380                 ws->cur_layout->l_config(ws, args->id);
1381
1382         if (args->id != SWM_ARG_ID_STACKINIT);
1383                 stack();
1384 }
1385
1386 void
1387 stack(void) {
1388         struct swm_geometry     g;
1389         struct swm_region       *r;
1390         int                     i, j;
1391
1392         DNPRINTF(SWM_D_STACK, "stack\n");
1393
1394         for (i = 0; i < ScreenCount(display); i++) {
1395                 j = 0;
1396                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1397                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
1398                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
1399
1400                         /* start with screen geometry, adjust for bar */
1401                         g = r->g;
1402                         g.w -= 2;
1403                         g.h -= 2;
1404                         if (bar_enabled) {
1405                                 g.y += bar_height;
1406                                 g.h -= bar_height;
1407                         } 
1408
1409                         r->ws->restack = 0;
1410                         r->ws->cur_layout->l_stack(r->ws, &g);
1411                 }
1412         }
1413         if (font_adjusted)
1414                 font_adjusted--;
1415         XSync(display, False);
1416 }
1417
1418 void
1419 stack_floater(struct ws_win *win, struct swm_region *r)
1420 {
1421         unsigned int            mask;
1422         XWindowChanges          wc;
1423
1424         bzero(&wc, sizeof wc);
1425         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
1426         if ((win->quirks & SWM_Q_FULLSCREEN) && (win->g.w == WIDTH(r)) &&
1427             (win->g.h == HEIGHT(r)))
1428                 wc.border_width = 0;
1429         else
1430                 wc.border_width = 1;
1431         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
1432                 win->g.w = (double)WIDTH(r) * dialog_ratio;
1433                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
1434         }
1435         wc.width = win->g.w;
1436         wc.height = win->g.h;
1437         if (win->manual) {
1438                 wc.x = win->g.x;
1439                 wc.y = win->g.y;
1440         } else {
1441                 wc.x = (WIDTH(r) - win->g.w) / 2;
1442                 wc.y = (HEIGHT(r) - win->g.h) / 2;
1443         }
1444
1445         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
1446             win->id, wc.x, wc.y, wc.width, wc.height);
1447
1448         XConfigureWindow(display, win->id, mask, &wc);
1449 }
1450
1451 /*
1452  * Send keystrokes to terminal to decrease/increase the font size as the
1453  * window size changes.
1454  */
1455 void
1456 adjust_font(struct ws_win *win)
1457 {
1458         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
1459             win->floating || win->transient)
1460                 return;
1461         
1462         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
1463             win->g.w / win->sh.width_inc < term_width &&
1464             win->font_steps < SWM_MAX_FONT_STEPS) {
1465                 win->font_size_boundary[win->font_steps] =
1466                     (win->sh.width_inc * term_width) + win->sh.base_width;
1467                 win->font_steps++;
1468                 font_adjusted++;
1469                 win->last_inc = win->sh.width_inc;
1470                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
1471         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
1472             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
1473                 win->font_steps--;
1474                 font_adjusted++;
1475                 win->last_inc = win->sh.width_inc;
1476                 fake_keypress(win, XK_KP_Add, ShiftMask);
1477         }
1478 }
1479
1480 #define SWAPXY(g)       do {                            \
1481         int tmp;                                        \
1482         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
1483         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
1484 } while (0)
1485 void
1486 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
1487 {
1488         XWindowChanges          wc;
1489         struct swm_geometry     win_g, r_g = *g;
1490         struct ws_win           *win, *winfocus;
1491         int                     i, j, s, stacks; 
1492         int                     w_inc = 1, h_inc, w_base = 1, h_base;
1493         int                     hrh, extra = 0, h_slice, last_h = 0;
1494         int                     split, colno, winno, mwin, msize, mscale;
1495         int                     remain, missing, v_slice;;
1496         unsigned int            mask;
1497
1498         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
1499             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
1500
1501         if ((winno = count_win(ws, 0)) == 0)
1502                 return;
1503
1504         if (ws->focus == NULL)
1505                 ws->focus = TAILQ_FIRST(&ws->winlist);
1506         winfocus = cur_focus ? cur_focus : ws->focus;
1507
1508         TAILQ_FOREACH(win, &ws->winlist, entry)
1509                 if (win->transient == 0 && win->floating == 0)
1510                         break;
1511
1512         if (win == NULL)
1513                 goto notiles;
1514
1515         if (rot) {
1516                 w_inc = win->sh.width_inc;
1517                 w_base = win->sh.base_width;
1518                 mwin = ws->l_state.horizontal_mwin;
1519                 mscale = ws->l_state.horizontal_msize;
1520                 stacks = ws->l_state.horizontal_stacks;
1521                 SWAPXY(&r_g);
1522         } else {
1523                 w_inc = win->sh.height_inc;
1524                 w_base = win->sh.base_height;
1525                 mwin = ws->l_state.vertical_mwin;
1526                 mscale = ws->l_state.vertical_msize;
1527                 stacks = ws->l_state.vertical_stacks;
1528         }
1529         win_g = r_g;
1530
1531         if (stacks > winno - mwin)
1532                 stacks = winno - mwin;
1533         if (stacks < 1)
1534                 stacks = 1;
1535
1536         h_slice = r_g.h / SWM_H_SLICE;
1537         if (mwin && winno > mwin) {
1538                 v_slice = r_g.w / SWM_V_SLICE;
1539
1540                 split = mwin;
1541                 colno = split;
1542                 win_g.w = v_slice * mscale;
1543
1544                 if (w_inc > 1 && w_inc < v_slice) {
1545                         /* adjust for window's requested size increment */
1546                         remain = (win_g.w - w_base) % w_inc;
1547                         missing = w_inc - remain;
1548                         win_g.w -= remain;
1549                         extra += remain;
1550                 }
1551
1552                 msize = win_g.w;
1553                 if (flip) 
1554                         win_g.x += r_g.w - msize;
1555         } else {
1556                 msize = -2;
1557                 colno = split = winno / stacks;
1558                 win_g.w = ((r_g.w - (stacks * 2) + 2) / stacks);
1559         }
1560         hrh = r_g.h / colno;
1561         extra = r_g.h - (colno * hrh);
1562         win_g.h = hrh - 2;
1563
1564         /*  stack all the tiled windows */
1565         i = j = 0, s = stacks;
1566         TAILQ_FOREACH(win, &ws->winlist, entry) {
1567                 if (win->transient != 0 || win->floating != 0)
1568                         continue;
1569
1570                 if (split && i == split) {
1571                         colno = (winno - mwin) / stacks;
1572                         if (s <= (winno - mwin) % stacks)
1573                                 colno++;
1574                         split = split + colno;
1575                         hrh = (r_g.h / colno);
1576                         extra = r_g.h - (colno * hrh);
1577                         if (flip)
1578                                 win_g.x = r_g.x;
1579                         else
1580                                 win_g.x += win_g.w + 2;
1581                         win_g.w = (r_g.w - msize - (stacks * 2)) / stacks;
1582                         if (s == 1)
1583                                 win_g.w += (r_g.w - msize - (stacks * 2)) %
1584                                     stacks;
1585                         s--;
1586                         j = 0;
1587                 }
1588                 win_g.h = hrh - 2;
1589                 if (rot) {
1590                         h_inc = win->sh.width_inc;
1591                         h_base = win->sh.base_width;
1592                 } else {
1593                         h_inc = win->sh.height_inc;
1594                         h_base = win->sh.base_height;
1595                 }
1596                 if (j == colno - 1) {
1597                         win_g.h = hrh + extra;
1598                 } else if (h_inc > 1 && h_inc < h_slice) {
1599                         /* adjust for window's requested size increment */
1600                         remain = (win_g.h - h_base) % h_inc;
1601                         missing = h_inc - remain;
1602
1603                         if (missing <= extra || j == 0) {
1604                                 extra -= missing;
1605                                 win_g.h += missing;
1606                         } else {
1607                                 win_g.h -= remain;
1608                                 extra += remain;
1609                         }
1610                 }
1611                  
1612                 if (j == 0)
1613                         win_g.y = r_g.y;
1614                 else
1615                         win_g.y += last_h + 2;
1616
1617                 bzero(&wc, sizeof wc);
1618                 wc.border_width = 1;
1619                 if (rot) {
1620                         win->g.x = wc.x = win_g.y;
1621                         win->g.y = wc.y = win_g.x;
1622                         win->g.w = wc.width = win_g.h;
1623                         win->g.h = wc.height = win_g.w;
1624                 } else {
1625                         win->g.x = wc.x = win_g.x;
1626                         win->g.y = wc.y = win_g.y;
1627                         win->g.w = wc.width = win_g.w;
1628                         win->g.h = wc.height = win_g.h;
1629                 }
1630                 adjust_font(win);
1631                 mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1632                 XConfigureWindow(display, win->id, mask, &wc);
1633                 XMapRaised(display, win->id);
1634
1635                 last_h = win_g.h;
1636                 i++;
1637                 j++;
1638         }
1639
1640  notiles:
1641         /* now, stack all the floaters and transients */
1642         TAILQ_FOREACH(win, &ws->winlist, entry) {
1643                 if (win->transient == 0 && win->floating == 0)
1644                         continue;
1645
1646                 stack_floater(win, ws->r);
1647                 XMapRaised(display, win->id);
1648         }
1649
1650         if (winfocus)
1651                 focus_win(winfocus); /* has to be done outside of the loop */
1652 }
1653
1654 void
1655 vertical_config(struct workspace *ws, int id)
1656 {
1657         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1658
1659         switch (id) {
1660         case SWM_ARG_ID_STACKRESET:
1661         case SWM_ARG_ID_STACKINIT:
1662                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1663                 ws->l_state.vertical_mwin = 1;
1664                 ws->l_state.vertical_stacks = 1;
1665                 break;
1666         case SWM_ARG_ID_MASTERSHRINK:
1667                 if (ws->l_state.vertical_msize > 1)
1668                         ws->l_state.vertical_msize--;
1669                 break;
1670         case SWM_ARG_ID_MASTERGROW:
1671                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1672                         ws->l_state.vertical_msize++;
1673                 break;
1674         case SWM_ARG_ID_MASTERADD:
1675                 ws->l_state.vertical_mwin++;
1676                 break;
1677         case SWM_ARG_ID_MASTERDEL:
1678                 if (ws->l_state.vertical_mwin > 0)
1679                         ws->l_state.vertical_mwin--;
1680                 break;
1681         case SWM_ARG_ID_STACKINC:
1682                 ws->l_state.vertical_stacks++;
1683                 break;
1684         case SWM_ARG_ID_STACKDEC:
1685                 if (ws->l_state.vertical_stacks > 1)
1686                         ws->l_state.vertical_stacks--;
1687                 break;
1688         default:
1689                 return;
1690         }
1691 }
1692
1693 void
1694 vertical_stack(struct workspace *ws, struct swm_geometry *g)
1695 {
1696         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1697
1698         stack_master(ws, g, 0, 0);
1699 }
1700
1701 void
1702 horizontal_config(struct workspace *ws, int id)
1703 {
1704         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1705
1706         switch (id) {
1707         case SWM_ARG_ID_STACKRESET:
1708         case SWM_ARG_ID_STACKINIT:
1709                 ws->l_state.horizontal_mwin = 1;
1710                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1711                 ws->l_state.horizontal_stacks = 1;
1712                 break;
1713         case SWM_ARG_ID_MASTERSHRINK:
1714                 if (ws->l_state.horizontal_msize > 1)
1715                         ws->l_state.horizontal_msize--;
1716                 break;
1717         case SWM_ARG_ID_MASTERGROW:
1718                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1719                         ws->l_state.horizontal_msize++;
1720                 break;
1721         case SWM_ARG_ID_MASTERADD:
1722                 ws->l_state.horizontal_mwin++;
1723                 break;
1724         case SWM_ARG_ID_MASTERDEL:
1725                 if (ws->l_state.horizontal_mwin > 0)
1726                         ws->l_state.horizontal_mwin--;
1727                 break;
1728         case SWM_ARG_ID_STACKINC:
1729                 ws->l_state.horizontal_stacks++;
1730                 break;
1731         case SWM_ARG_ID_STACKDEC:
1732                 if (ws->l_state.horizontal_stacks > 1)
1733                         ws->l_state.horizontal_stacks--;
1734                 break;
1735         default:
1736                 return;
1737         }
1738 }
1739
1740 void
1741 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
1742 {
1743         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1744
1745         stack_master(ws, g, 1, 0);
1746 }
1747
1748 /* fullscreen view */
1749 void
1750 max_stack(struct workspace *ws, struct swm_geometry *g) {
1751         XWindowChanges          wc;
1752         struct swm_geometry     gg = *g;
1753         struct ws_win           *win, *winfocus;
1754         unsigned int            mask;
1755
1756         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1757
1758         if (count_win(ws, 0) == 0)
1759                 return;
1760
1761         if (ws->focus == NULL)
1762                 ws->focus = TAILQ_FIRST(&ws->winlist);
1763         winfocus = cur_focus ? cur_focus : ws->focus;
1764
1765         TAILQ_FOREACH(win, &ws->winlist, entry) {
1766                 if (win->transient != 0 || win->floating != 0) {
1767                         if (win == ws->focus) {
1768                                 /* XXX maximize? */
1769                                 stack_floater(win, ws->r);
1770                                 XMapRaised(display, win->id);
1771                         } else
1772                                 XUnmapWindow(display, win->id);
1773                 } else {
1774                         bzero(&wc, sizeof wc);
1775                         wc.border_width = 1;
1776                         win->g.x = wc.x = gg.x;
1777                         win->g.y = wc.y = gg.y;
1778                         win->g.w = wc.width = gg.w;
1779                         win->g.h = wc.height = gg.h;
1780                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1781                         XConfigureWindow(display, win->id, mask, &wc);
1782
1783                         if (win == ws->focus) {
1784                                 XMapRaised(display, win->id);
1785                         } else
1786                                 XUnmapWindow(display, win->id);
1787                 }
1788         }
1789
1790         if (winfocus)
1791                 focus_win(winfocus); /* has to be done outside of the loop */
1792 }
1793
1794 void
1795 send_to_ws(struct swm_region *r, union arg *args)
1796 {
1797         int                     wsid = args->id;
1798         struct ws_win           *win = cur_focus;
1799         struct workspace        *ws, *nws;
1800         Atom                    ws_idx_atom = 0;
1801         unsigned char           ws_idx_str[SWM_PROPLEN];
1802
1803         if (win == NULL)
1804                 return;
1805
1806         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1807
1808         ws = win->ws;
1809         nws = &win->s->ws[wsid];
1810
1811         XUnmapWindow(display, win->id);
1812
1813         /* find a window to focus */
1814         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1815         if (ws->focus == NULL)
1816                 ws->focus = TAILQ_FIRST(&ws->winlist);
1817         if (ws->focus == win)
1818                 ws->focus = NULL;
1819
1820         TAILQ_REMOVE(&ws->winlist, win, entry);
1821
1822         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1823         win->ws = nws;
1824
1825         /* Try to update the window's workspace property */
1826         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1827         if (ws_idx_atom &&
1828             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
1829                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1830                     ws_idx_str);
1831                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1832                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1833         }
1834
1835         if (count_win(nws, 1) == 1)
1836                 nws->focus = win;
1837         ws->restack = 1;
1838         nws->restack = 1;
1839
1840         stack();
1841 }
1842
1843 void
1844 wkill(struct swm_region *r, union arg *args)
1845 {
1846         DNPRINTF(SWM_D_MISC, "wkill %d\n", args->id);
1847
1848         if(r->ws->focus == NULL)
1849                 return;
1850
1851         if (args->id == SWM_ARG_ID_KILLWINDOW)
1852                 XKillClient(display, r->ws->focus->id);
1853         else
1854                 if (r->ws->focus->can_delete)
1855                         client_msg(r->ws->focus, adelete);
1856 }
1857
1858 void
1859 screenshot(struct swm_region *r, union arg *args)
1860 {
1861         union arg                       a;
1862
1863         DNPRINTF(SWM_D_MISC, "screenshot\n");
1864
1865         if (ss_enabled == 0)
1866                 return;
1867
1868         switch (args->id) {
1869         case SWM_ARG_ID_SS_ALL:
1870                 spawn_screenshot[1] = "full";
1871                 break;
1872         case SWM_ARG_ID_SS_WINDOW:
1873                 spawn_screenshot[1] = "window";
1874                 break;
1875         default:
1876                 return;
1877         }
1878         a.argv = spawn_screenshot;
1879         spawn(r, &a);
1880 }
1881
1882 void
1883 floating_toggle(struct swm_region *r, union arg *args)
1884 {
1885         struct ws_win   *win = cur_focus;
1886
1887         if (win == NULL)
1888                 return;
1889
1890         win->floating = !win->floating;
1891         win->manual = 0;
1892         stack();
1893         focus_win(win);
1894 }
1895
1896 /* key definitions */
1897 struct key {
1898         unsigned int            mod;
1899         KeySym                  keysym;
1900         void                    (*func)(struct swm_region *r, union arg *);
1901         union arg               args;
1902 } keys[] = {
1903         /* modifier             key     function                argument */
1904         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1905         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1906         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1907         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1908         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1909         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1910         { MODKEY | ShiftMask,   XK_comma,       stack_config,   {.id = SWM_ARG_ID_STACKINC} },
1911         { MODKEY | ShiftMask,   XK_period,      stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
1912         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1913         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1914         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1915         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1916         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1917         { MODKEY | ShiftMask,   XK_Return,      spawnterm,      {.argv = spawn_term} },
1918         { MODKEY,               XK_p,           spawnmenu,      {.argv = spawn_menu} },
1919         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1920         { MODKEY,               XK_q,           restart,        {0} },
1921         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1922         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1923         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1924         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1925         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1926         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1927         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1928         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1929         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1930         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1931         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1932         { MODKEY,               XK_Right,       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
1933         { MODKEY,               XK_Left,        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
1934         { MODKEY | ShiftMask,   XK_Right,       cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} }, 
1935         { MODKEY | ShiftMask,   XK_Left,        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} }, 
1936         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1937         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1938         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1939         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1940         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1941         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1942         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1943         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1944         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1945         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1946         { MODKEY,               XK_b,           bar_toggle,     {0} },
1947         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1948         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1949         { MODKEY | ShiftMask,   XK_x,           wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
1950         { MODKEY,               XK_x,           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
1951         { MODKEY,               XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_ALL} },
1952         { MODKEY | ShiftMask,   XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_WINDOW} },
1953         { MODKEY,               XK_t,           floating_toggle,{0} },
1954         { MODKEY | ShiftMask,   XK_v,           version,        {0} },
1955         { MODKEY | ShiftMask,   XK_Delete,      spawn,          {.argv = spawn_lock} },
1956         { MODKEY | ShiftMask,   XK_i,           spawn,          {.argv = spawn_initscr} },
1957 };
1958
1959 void
1960 resize_window(struct ws_win *win, int center)
1961 {
1962         unsigned int            mask;
1963         XWindowChanges          wc;
1964         struct swm_region       *r;
1965
1966         r = root_to_region(win->wa.root);
1967         bzero(&wc, sizeof wc);
1968         mask = CWBorderWidth | CWWidth | CWHeight;
1969         wc.border_width = 1;
1970         wc.width = win->g.w;
1971         wc.height = win->g.h;
1972         if (center == SWM_ARG_ID_CENTER) {
1973                 wc.x = (WIDTH(r) - win->g.w) / 2;
1974                 wc.y = (HEIGHT(r) - win->g.h) / 2;
1975                 mask |= CWX | CWY;
1976         }
1977
1978         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
1979             win->id, wc.x, wc.y, wc.width, wc.height);
1980
1981         XConfigureWindow(display, win->id, mask, &wc);
1982         config_win(win);
1983 }
1984
1985 void
1986 resize(struct ws_win *win, union arg *args)
1987 {
1988         XEvent                  ev;
1989         Time                    time = 0;
1990
1991         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %d\n",
1992             win->id, win->floating, win->transient);
1993
1994         if (!(win->transient != 0 || win->floating != 0))
1995                 return;
1996
1997         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
1998             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
1999                 return;
2000         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w, win->g.h);
2001         do {
2002                 XMaskEvent(display, MOUSEMASK | ExposureMask |
2003                     SubstructureRedirectMask, &ev);
2004                 switch(ev.type) {
2005                 case ConfigureRequest:
2006                 case Expose:
2007                 case MapRequest:
2008                         handler[ev.type](&ev);
2009                         break;
2010                 case MotionNotify:
2011                         if (ev.xmotion.x <= 1)
2012                                 ev.xmotion.x = 1;
2013                         if (ev.xmotion.y <= 1)
2014                                 ev.xmotion.y = 1;
2015                         win->g.w = ev.xmotion.x;
2016                         win->g.h = ev.xmotion.y;
2017
2018                         /* not free, don't sync more than 60 times / second */
2019                         if ((ev.xmotion.time - time) > (1000 / 60) ) {
2020                                 time = ev.xmotion.time;
2021                                 XSync(display, False);
2022                                 resize_window(win, args->id);
2023                         }
2024                         break;
2025                 }
2026         } while (ev.type != ButtonRelease);
2027         if (time) {
2028                 XSync(display, False);
2029                 resize_window(win, args->id);
2030         }
2031         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
2032             win->g.h - 1);
2033         XUngrabPointer(display, CurrentTime);
2034
2035         /* drain events */
2036         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
2037 }
2038
2039 void
2040 move_window(struct ws_win *win)
2041 {
2042         unsigned int            mask;
2043         XWindowChanges          wc;
2044         struct swm_region       *r;
2045
2046         r = root_to_region(win->wa.root);
2047         bzero(&wc, sizeof wc);
2048         mask = CWX | CWY;
2049         wc.x = win->g.x;
2050         wc.y = win->g.y;
2051
2052         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
2053             win->id, wc.x, wc.y, wc.width, wc.height);
2054
2055         XConfigureWindow(display, win->id, mask, &wc);
2056         config_win(win);
2057 }
2058
2059 void
2060 move(struct ws_win *win, union arg *args)
2061 {
2062         XEvent                  ev;
2063         Time                    time = 0;
2064         int                     restack = 0;
2065
2066         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %d\n",
2067             win->id, win->floating, win->transient);
2068
2069         if (win->floating == 0) {
2070                 win->floating = 1;
2071                 win->manual = 1;
2072                 restack = 1;
2073         }
2074
2075         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
2076             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
2077                 return;
2078         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
2079         do {
2080                 XMaskEvent(display, MOUSEMASK | ExposureMask |
2081                     SubstructureRedirectMask, &ev);
2082                 switch(ev.type) {
2083                 case ConfigureRequest:
2084                 case Expose:
2085                 case MapRequest:
2086                         handler[ev.type](&ev);
2087                         break;
2088                 case MotionNotify:
2089                         win->g.x = ev.xmotion.x_root;
2090                         win->g.y = ev.xmotion.y_root;
2091
2092                         /* not free, don't sync more than 60 times / second */
2093                         if ((ev.xmotion.time - time) > (1000 / 60) ) {
2094                                 time = ev.xmotion.time;
2095                                 XSync(display, False);
2096                                 move_window(win);
2097                         }
2098                         break;
2099                 }
2100         } while (ev.type != ButtonRelease);
2101         if (time) {
2102                 XSync(display, False);
2103                 move_window(win);
2104         }
2105         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
2106         XUngrabPointer(display, CurrentTime);
2107         if (restack)
2108                 stack();
2109
2110         /* drain events */
2111         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
2112 }
2113
2114 /* mouse */
2115 enum { client_click, root_click };
2116 struct button {
2117         unsigned int            action;
2118         unsigned int            mask;
2119         unsigned int            button;
2120         void                    (*func)(struct ws_win *, union arg *);
2121         union arg               args;
2122 } buttons[] = {
2123           /* action             key             mouse button    func            args */
2124         { client_click,         MODKEY,         Button3,        resize,         {.id = SWM_ARG_ID_DONTCENTER} },
2125         { client_click,         MODKEY | ShiftMask, Button3,    resize,         {.id = SWM_ARG_ID_CENTER} },
2126         { client_click,         MODKEY,         Button1,        move,           {0} },
2127 };
2128
2129 void
2130 update_modkey(unsigned int mod)
2131 {
2132         int                     i;
2133
2134         for (i = 0; i < LENGTH(keys); i++)
2135                 if (keys[i].mod & ShiftMask)
2136                         keys[i].mod = mod | ShiftMask;
2137                 else
2138                         keys[i].mod = mod;
2139
2140         for (i = 0; i < LENGTH(buttons); i++)
2141                 if (buttons[i].mask & ShiftMask)
2142                         buttons[i].mask = mod | ShiftMask;
2143                 else
2144                         buttons[i].mask = mod;
2145 }
2146
2147 void
2148 updatenumlockmask(void)
2149 {
2150         unsigned int            i, j;
2151         XModifierKeymap         *modmap;
2152
2153         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
2154         numlockmask = 0;
2155         modmap = XGetModifierMapping(display);
2156         for (i = 0; i < 8; i++)
2157                 for (j = 0; j < modmap->max_keypermod; j++)
2158                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
2159                           == XKeysymToKeycode(display, XK_Num_Lock))
2160                                 numlockmask = (1 << i);
2161
2162         XFreeModifiermap(modmap);
2163 }
2164
2165 void
2166 grabkeys(void)
2167 {
2168         unsigned int            i, j, k;
2169         KeyCode                 code;
2170         unsigned int            modifiers[] =
2171             { 0, LockMask, numlockmask, numlockmask | LockMask };
2172
2173         DNPRINTF(SWM_D_MISC, "grabkeys\n");
2174         updatenumlockmask();
2175
2176         for (k = 0; k < ScreenCount(display); k++) {
2177                 if (TAILQ_EMPTY(&screens[k].rl))
2178                         continue;
2179                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
2180                 for (i = 0; i < LENGTH(keys); i++) {
2181                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
2182                                 for (j = 0; j < LENGTH(modifiers); j++)
2183                                         XGrabKey(display, code,
2184                                             keys[i].mod | modifiers[j],
2185                                             screens[k].root, True,
2186                                             GrabModeAsync, GrabModeAsync);
2187                 }
2188         }
2189 }
2190
2191 void
2192 grabbuttons(struct ws_win *win, int focused)
2193 {
2194         unsigned int            i, j;
2195         unsigned int            modifiers[] =
2196             { 0, LockMask, numlockmask, numlockmask|LockMask };
2197
2198         updatenumlockmask();
2199         XUngrabButton(display, AnyButton, AnyModifier, win->id);
2200         if(focused) {
2201                 for (i = 0; i < LENGTH(buttons); i++)
2202                         if (buttons[i].action == client_click)
2203                                 for (j = 0; j < LENGTH(modifiers); j++)
2204                                         XGrabButton(display, buttons[i].button,
2205                                             buttons[i].mask | modifiers[j],
2206                                             win->id, False, BUTTONMASK,
2207                                             GrabModeAsync, GrabModeSync, None,
2208                                             None);
2209         } else
2210                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
2211                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
2212 }
2213
2214 void
2215 expose(XEvent *e)
2216 {
2217         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
2218 }
2219
2220 void
2221 keypress(XEvent *e)
2222 {
2223         unsigned int            i;
2224         KeySym                  keysym;
2225         XKeyEvent               *ev = &e->xkey;
2226
2227         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
2228
2229         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
2230         for (i = 0; i < LENGTH(keys); i++)
2231                 if (keysym == keys[i].keysym
2232                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
2233                    && keys[i].func)
2234                         keys[i].func(root_to_region(ev->root),
2235                             &(keys[i].args));
2236 }
2237
2238 void
2239 buttonpress(XEvent *e)
2240 {
2241         XButtonPressedEvent     *ev = &e->xbutton;
2242
2243         struct ws_win           *win;
2244         int                     i, action;
2245
2246         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
2247
2248         action = root_click;
2249         if ((win = find_window(ev->window)) == NULL)
2250                 return;
2251         else {
2252                 focus_win(win);
2253                 action = client_click;
2254         }
2255
2256         for (i = 0; i < LENGTH(buttons); i++)
2257                 if (action == buttons[i].action && buttons[i].func &&
2258                     buttons[i].button == ev->button &&
2259                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
2260                         buttons[i].func(win, &buttons[i].args);
2261 }
2262
2263 void
2264 set_win_state(struct ws_win *win, long state)
2265 {
2266         long                    data[] = {state, None};
2267
2268         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
2269
2270         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
2271             (unsigned char *)data, 2);
2272 }
2273
2274 struct ws_win *
2275 manage_window(Window id)
2276 {
2277         Window                  trans;
2278         struct workspace        *ws;
2279         struct ws_win           *win;
2280         int                     format, i, ws_idx, n;
2281         unsigned long           nitems, bytes;
2282         Atom                    ws_idx_atom = 0, type;
2283         Atom                    *prot = NULL, *pp;
2284         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
2285         struct swm_region       *r;
2286         long                    mask;
2287         const char              *errstr;
2288         XWindowChanges          wc;
2289
2290         if ((win = find_window(id)) != NULL)
2291                         return (win);   /* already being managed */
2292
2293         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
2294                 errx(1, "calloc: failed to allocate memory for new window");
2295
2296         /* Get all the window data in one shot */
2297         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2298         if (ws_idx_atom)
2299                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
2300                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
2301         XGetWindowAttributes(display, id, &win->wa);
2302         XGetTransientForHint(display, id, &trans);
2303         XGetWMNormalHints(display, id, &win->sh, &mask); /* XXX function? */
2304         if (trans) {
2305                 win->transient = trans;
2306                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
2307                     (unsigned)win->id, win->transient);
2308         }
2309         /* get supported protocols */
2310         if (XGetWMProtocols(display, id, &prot, &n)) {
2311                 for (i = 0, pp = prot; i < n; i++, pp++)
2312                         if (*pp == adelete)
2313                                 win->can_delete = 1;
2314                 if (prot)
2315                         XFree(prot);
2316         }
2317
2318         /*
2319          * Figure out where to put the window. If it was previously assigned to
2320          * a workspace (either by spawn() or manually moving), and isn't
2321          * transient, * put it in the same workspace
2322          */
2323         r = root_to_region(win->wa.root);
2324         if (prop && win->transient == 0) {
2325                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
2326                 ws_idx = strtonum(prop, 0, 9, &errstr);
2327                 if (errstr) {
2328                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
2329                             errstr, prop);
2330                 }
2331                 ws = &r->s->ws[ws_idx];
2332         } else
2333                 ws = r->ws;
2334
2335         /* set up the window layout */
2336         win->id = id;
2337         win->ws = ws;
2338         win->s = r->s;  /* this never changes */
2339         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
2340
2341         win->g.w = win->wa.width;
2342         win->g.h = win->wa.height;
2343         win->g.x = win->wa.x;
2344         win->g.y = win->wa.y;
2345
2346         /* Set window properties so we can remember this after reincarnation */
2347         if (ws_idx_atom && prop == NULL &&
2348             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
2349                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2350                     ws_idx_str);
2351                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2352                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2353         }
2354         XFree(prop);
2355
2356         if (XGetClassHint(display, win->id, &win->ch)) {
2357                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
2358                     win->ch.res_class, win->ch.res_name);
2359                 for (i = 0; quirks[i].class != NULL && quirks[i].name != NULL &&
2360                     quirks[i].quirk != 0; i++){
2361                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
2362                             !strcmp(win->ch.res_name, quirks[i].name)) {
2363                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
2364                                     win->ch.res_class, win->ch.res_name);
2365                                 if (quirks[i].quirk & SWM_Q_FLOAT)
2366                                         win->floating = 1;
2367                                 win->quirks = quirks[i].quirk;
2368                         }
2369                 }
2370         }
2371
2372         /* alter window position if quirky */
2373         if (win->quirks & SWM_Q_ANYWHERE) {
2374                 win->manual = 1; /* don't center the quirky windows */
2375                 bzero(&wc, sizeof wc);
2376                 mask = 0;
2377                 if (win->g.y < bar_height) {
2378                         win->g.y = wc.y = bar_height;
2379                         mask |= CWY;
2380                 }
2381                 if (win->g.w + win->g.x > WIDTH(r)) {
2382                         win->g.x = wc.x = WIDTH(win->ws->r) - win->g.w - 2;
2383                         mask |= CWX;
2384                 }
2385                 wc.border_width = 1;
2386                 mask |= CWBorderWidth;
2387                 XConfigureWindow(display, win->id, mask, &wc);
2388         }
2389
2390         /* Reset font sizes (the bruteforce way; no default keybinding). */
2391         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
2392                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
2393                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
2394                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
2395                         fake_keypress(win, XK_KP_Add, ShiftMask);
2396         }
2397
2398         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
2399             PropertyChangeMask | StructureNotifyMask);
2400
2401         set_win_state(win, NormalState);
2402
2403         /* floaters need to be mapped if they are in the current workspace */
2404         if (win->floating && (ws->idx == r->ws->idx))
2405                 XMapRaised(display, win->id);
2406
2407         /* make new win focused */
2408         focus_win(win);
2409
2410         return (win);
2411 }
2412
2413 void
2414 unmanage_window(struct ws_win *win)
2415 {
2416         struct workspace        *ws;
2417
2418         if (win == NULL)
2419                 return;
2420
2421         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
2422
2423         /* don't unmanage if we are switching workspaces */
2424         ws = win->ws;
2425         if (ws->restack)
2426                 return;
2427
2428         /* find a window to focus */
2429         if (ws->focus == win)
2430                 ws->focus = TAILQ_PREV(win, ws_win_list, entry);
2431         if (ws->focus == NULL)
2432                 ws->focus = TAILQ_FIRST(&ws->winlist);
2433         if (ws->focus == NULL || ws->focus == win) {
2434                 ws->focus = NULL;
2435                 unfocus_win(win);
2436         } else
2437                 focus_win(ws->focus);
2438         if (ws->focus_prev == win)
2439                 ws->focus_prev = NULL;
2440
2441         TAILQ_REMOVE(&win->ws->winlist, win, entry);
2442         set_win_state(win, WithdrawnState);
2443         if (win->ch.res_class)
2444                 XFree(win->ch.res_class);
2445         if (win->ch.res_name)
2446                 XFree(win->ch.res_name);
2447         free(win);
2448 }
2449
2450 void
2451 configurerequest(XEvent *e)
2452 {
2453         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
2454         struct ws_win           *win;
2455         int                     new = 0;
2456         XWindowChanges          wc;
2457
2458         if ((win = find_window(ev->window)) == NULL)
2459                 new = 1;
2460
2461         if (new) {
2462                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
2463                     ev->window);
2464                 bzero(&wc, sizeof wc);
2465                 wc.x = ev->x;
2466                 wc.y = ev->y;
2467                 wc.width = ev->width;
2468                 wc.height = ev->height;
2469                 wc.border_width = ev->border_width;
2470                 wc.sibling = ev->above;
2471                 wc.stack_mode = ev->detail;
2472                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
2473         } else {
2474                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
2475                     ev->window);
2476                 if (win->floating) {
2477                         if (ev->value_mask & CWX)
2478                                 win->g.x = ev->x;
2479                         if (ev->value_mask & CWY)
2480                                 win->g.y = ev->y;
2481                         if (ev->value_mask & CWWidth)
2482                                 win->g.w = ev->width;
2483                         if (ev->value_mask & CWHeight)
2484                                 win->g.h = ev->height;
2485                         if (win->ws->r != NULL) {
2486                                 /* this seems to be full screen */
2487                                 if (win->g.w >= WIDTH(win->ws->r)) {
2488                                         win->g.x = 0;
2489                                         win->g.w = WIDTH(win->ws->r);
2490                                         ev->value_mask |= CWX | CWWidth;
2491                                 }
2492                                 if (win->g.h >= HEIGHT(win->ws->r)) {
2493                                         /* kill border */
2494                                         win->g.y = 0;
2495                                         win->g.h = HEIGHT(win->ws->r);
2496                                         ev->value_mask |= CWY | CWHeight;
2497                                 }
2498                         }
2499                         if ((ev->value_mask & (CWX | CWY)) &&
2500                             !(ev->value_mask & (CWWidth | CWHeight)))
2501                                 config_win(win);
2502                         XMoveResizeWindow(display, win->id,
2503                             win->g.x, win->g.y, win->g.w, win->g.h);
2504                 } else
2505                         config_win(win);
2506         }
2507 }
2508
2509 void
2510 configurenotify(XEvent *e)
2511 {
2512         struct ws_win           *win;
2513         long                    mask;
2514
2515         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
2516             e->xconfigure.window);
2517
2518         XMapWindow(display, e->xconfigure.window);
2519         win = find_window(e->xconfigure.window);
2520         if (win) {
2521                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
2522                 adjust_font(win);
2523                 XMapWindow(display, win->id);
2524                 if (font_adjusted)
2525                         stack();
2526         }
2527 }
2528
2529 void
2530 destroynotify(XEvent *e)
2531 {
2532         struct ws_win           *win;
2533         XDestroyWindowEvent     *ev = &e->xdestroywindow;
2534
2535         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
2536
2537         if ((win = find_window(ev->window)) != NULL) {
2538                 unmanage_window(win);
2539                 stack();
2540         }
2541 }
2542
2543 void
2544 enternotify(XEvent *e)
2545 {
2546         XCrossingEvent          *ev = &e->xcrossing;
2547         struct ws_win           *win;
2548
2549         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
2550
2551         if (ignore_enter) {
2552                 /* eat event(r) to prevent autofocus */
2553                 ignore_enter--;
2554                 return;
2555         }
2556
2557         if ((win = find_window(ev->window)) != NULL)
2558                 focus_win(win);
2559 }
2560
2561 void
2562 focusin(XEvent *e)
2563 {
2564         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
2565 }
2566
2567 void
2568 focusout(XEvent *e)
2569 {
2570         DNPRINTF(SWM_D_EVENT, "focusout: window: %lu\n", e->xfocus.window);
2571
2572         if (cur_focus && cur_focus->ws->r &&
2573             cur_focus->id == e->xfocus.window) {
2574                 struct swm_screen       *s = cur_focus->ws->r->s;
2575                 Window                  rr, cr;
2576                 int                     x, y, wx, wy;
2577                 unsigned int            mask;
2578
2579                 /* Try to detect synergy hiding the cursor.  */
2580                 if (XQueryPointer(display, cur_focus->id, 
2581                     &rr, &cr, &x, &y, &wx, &wy, &mask) != False &&
2582                     cr == 0 && !mask &&
2583                     x == DisplayWidth(display, s->idx)/2 &&
2584                     y == DisplayHeight(display, s->idx)/2) {
2585                         unfocus_win(cur_focus);
2586                 }
2587         }
2588 }
2589
2590 void
2591 mappingnotify(XEvent *e)
2592 {
2593         XMappingEvent           *ev = &e->xmapping;
2594
2595         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
2596
2597         XRefreshKeyboardMapping(ev);
2598         if (ev->request == MappingKeyboard)
2599                 grabkeys();
2600 }
2601
2602 void
2603 maprequest(XEvent *e)
2604 {
2605         XMapRequestEvent        *ev = &e->xmaprequest;
2606         XWindowAttributes       wa;
2607
2608         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
2609             e->xmaprequest.window);
2610
2611         if (!XGetWindowAttributes(display, ev->window, &wa))
2612                 return;
2613         if (wa.override_redirect)
2614                 return;
2615         manage_window(e->xmaprequest.window);
2616
2617         stack();
2618 }
2619
2620 void
2621 propertynotify(XEvent *e)
2622 {
2623         struct ws_win           *win;
2624         XPropertyEvent          *ev = &e->xproperty;
2625
2626         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
2627             ev->window);
2628
2629         if (ev->state == PropertyDelete)
2630                 return; /* ignore */
2631         win = find_window(ev->window);
2632         if (win == NULL)
2633                 return;
2634
2635         switch (ev->atom) {
2636         case XA_WM_NORMAL_HINTS:
2637 #if 0
2638                 long            mask;
2639                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
2640                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
2641                 if (win->sh.flags & PMinSize) {
2642                         win->g.w = win->sh.min_width;
2643                         win->g.h = win->sh.min_height;
2644                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
2645                 }
2646                 XMoveResizeWindow(display, win->id,
2647                     win->g.x, win->g.y, win->g.w, win->g.h);
2648 #endif
2649                 break;
2650         default:
2651                 break;
2652         }
2653 }
2654
2655 void
2656 unmapnotify(XEvent *e)
2657 {
2658         XDestroyWindowEvent     *ev = &e->xdestroywindow;
2659         struct ws_win           *win;
2660
2661         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
2662
2663         if ((win = find_window(ev->window)) != NULL)
2664                 if (win->transient)
2665                         unmanage_window(win);
2666 }
2667
2668 void
2669 visibilitynotify(XEvent *e)
2670 {
2671         int                     i;
2672         struct swm_region       *r;
2673
2674         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
2675             e->xvisibility.window);
2676         if (e->xvisibility.state == VisibilityUnobscured)
2677                 for (i = 0; i < ScreenCount(display); i++) 
2678                         TAILQ_FOREACH(r, &screens[i].rl, entry)
2679                                 if (e->xvisibility.window == r->bar_window)
2680                                         bar_update();
2681 }
2682
2683 int
2684 xerror_start(Display *d, XErrorEvent *ee)
2685 {
2686         other_wm = 1;
2687         return (-1);
2688 }
2689
2690 int
2691 xerror(Display *d, XErrorEvent *ee)
2692 {
2693         /* fprintf(stderr, "error: %p %p\n", display, ee); */
2694         return (-1);
2695 }
2696
2697 int
2698 active_wm(void)
2699 {
2700         other_wm = 0;
2701         xerrorxlib = XSetErrorHandler(xerror_start);
2702
2703         /* this causes an error if some other window manager is running */
2704         XSelectInput(display, DefaultRootWindow(display),
2705             SubstructureRedirectMask);
2706         XSync(display, False);
2707         if (other_wm)
2708                 return (1);
2709
2710         XSetErrorHandler(xerror);
2711         XSync(display, False);
2712         return (0);
2713 }
2714
2715 long
2716 getstate(Window w)
2717 {
2718         int                     format, status;
2719         long                    result = -1;
2720         unsigned char           *p = NULL;
2721         unsigned long           n, extra;
2722         Atom                    real;
2723
2724         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
2725             &real, &format, &n, &extra, (unsigned char **)&p);
2726         if (status != Success)
2727                 return (-1);
2728         if (n != 0)
2729                 result = *((long *)p);
2730         XFree(p);
2731         return (result);
2732 }
2733
2734 void
2735 new_region(struct swm_screen *s, int x, int y, int w, int h)
2736 {
2737         struct swm_region       *r, *n;
2738         struct workspace        *ws = NULL;
2739         int                     i;
2740
2741         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
2742              s->idx, w, h, x, y);
2743
2744         /* remove any conflicting regions */
2745         n = TAILQ_FIRST(&s->rl);
2746         while (n) {
2747                 r = n;
2748                 n = TAILQ_NEXT(r, entry);
2749                 if (X(r) < (x + w) &&
2750                     (X(r) + WIDTH(r)) > x &&
2751                     Y(r) < (y + h) &&
2752                     (Y(r) + HEIGHT(r)) > y) {
2753                         XDestroyWindow(display, r->bar_window);
2754                         TAILQ_REMOVE(&s->rl, r, entry);
2755                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
2756                 }
2757         }
2758
2759         /* search old regions for one to reuse */
2760
2761         /* size + location match */
2762         TAILQ_FOREACH(r, &s->orl, entry)
2763                 if (X(r) == x && Y(r) == y &&
2764                     HEIGHT(r) == h && WIDTH(r) == w)
2765                         break;
2766
2767         /* size match */
2768         TAILQ_FOREACH(r, &s->orl, entry)
2769                 if (HEIGHT(r) == h && WIDTH(r) == w)
2770                         break;
2771
2772         if (r != NULL) {
2773                 TAILQ_REMOVE(&s->orl, r, entry);
2774                 /* try to use old region's workspace */
2775                 if (r->ws->r == NULL)
2776                         ws = r->ws;
2777         } else
2778                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
2779                         errx(1, "calloc: failed to allocate memory for screen");
2780
2781         /* if we don't have a workspace already, find one */
2782         if (ws == NULL) {
2783                 for (i = 0; i < SWM_WS_MAX; i++)
2784                         if (s->ws[i].r == NULL) {
2785                                 ws = &s->ws[i];
2786                                 break;
2787                         }
2788         }
2789
2790         if (ws == NULL)
2791                 errx(1, "no free workspaces\n");
2792
2793         X(r) = x;
2794         Y(r) = y;
2795         WIDTH(r) = w;
2796         HEIGHT(r) = h;
2797         r->s = s;
2798         r->ws = ws;
2799         ws->r = r;
2800         TAILQ_INSERT_TAIL(&s->rl, r, entry);
2801 }
2802
2803 void
2804 scan_xrandr(int i)
2805 {
2806 #ifdef SWM_XRR_HAS_CRTC
2807         XRRCrtcInfo             *ci;
2808         XRRScreenResources      *sr;
2809         int                     c;
2810         int                     ncrtc = 0;
2811 #endif /* SWM_XRR_HAS_CRTC */
2812         struct swm_region       *r;
2813
2814
2815         if (i >= ScreenCount(display))
2816                 errx(1, "invalid screen");
2817
2818         /* remove any old regions */
2819         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
2820                 r->ws->r = NULL;
2821                 XDestroyWindow(display, r->bar_window);
2822                 TAILQ_REMOVE(&screens[i].rl, r, entry);
2823                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
2824         }
2825
2826         /* map virtual screens onto physical screens */
2827 #ifdef SWM_XRR_HAS_CRTC
2828         if (xrandr_support) {
2829                 sr = XRRGetScreenResources(display, screens[i].root);
2830                 if (sr == NULL)
2831                         new_region(&screens[i], 0, 0,
2832                             DisplayWidth(display, i),
2833                             DisplayHeight(display, i)); 
2834                 else 
2835                         ncrtc = sr->ncrtc;
2836
2837                 for (c = 0, ci = NULL; c < ncrtc; c++) {
2838                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
2839                         if (ci->noutput == 0)
2840                                 continue;
2841
2842                         if (ci != NULL && ci->mode == None)
2843                                 new_region(&screens[i], 0, 0,
2844                                     DisplayWidth(display, i),
2845                                     DisplayHeight(display, i)); 
2846                         else
2847                                 new_region(&screens[i],
2848                                     ci->x, ci->y, ci->width, ci->height);
2849                 }
2850                 if (ci)
2851                         XRRFreeCrtcInfo(ci);
2852                 XRRFreeScreenResources(sr);
2853         } else
2854 #endif /* SWM_XRR_HAS_CRTC */
2855         {
2856                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
2857                     DisplayHeight(display, i)); 
2858         }
2859 }
2860
2861 void
2862 screenchange(XEvent *e) {
2863         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
2864         struct swm_region               *r;
2865         struct ws_win                   *win;
2866         int                             i;
2867
2868         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
2869
2870         if (!XRRUpdateConfiguration(e))
2871                 return;
2872
2873         /* silly event doesn't include the screen index */
2874         for (i = 0; i < ScreenCount(display); i++)
2875                 if (screens[i].root == xe->root)
2876                         break;
2877         if (i >= ScreenCount(display))
2878                 errx(1, "screenchange: screen not found\n");
2879
2880         /* brute force for now, just re-enumerate the regions */
2881         scan_xrandr(i);
2882
2883         /* hide any windows that went away */
2884         TAILQ_FOREACH(r, &screens[i].rl, entry)
2885                 TAILQ_FOREACH(win, &r->ws->winlist, entry)
2886                         XUnmapWindow(display, win->id);
2887
2888         /* add bars to all regions */
2889         for (i = 0; i < ScreenCount(display); i++)
2890                 TAILQ_FOREACH(r, &screens[i].rl, entry)
2891                         bar_setup(r);
2892         stack();
2893 }
2894
2895 void
2896 setup_screens(void)
2897 {
2898         Window                  d1, d2, *wins = NULL;
2899         XWindowAttributes       wa;
2900         unsigned int            no;
2901         int                     i, j, k;
2902         int                     errorbase, major, minor;
2903         struct workspace        *ws;
2904         int                     ws_idx_atom;
2905
2906
2907         if ((screens = calloc(ScreenCount(display),
2908              sizeof(struct swm_screen))) == NULL)
2909                 errx(1, "calloc: screens");
2910
2911         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2912
2913         /* initial Xrandr setup */
2914         xrandr_support = XRRQueryExtension(display,
2915             &xrandr_eventbase, &errorbase);
2916         if (xrandr_support)
2917                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
2918                         xrandr_support = 0;
2919
2920         /* map physical screens */
2921         for (i = 0; i < ScreenCount(display); i++) {
2922                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
2923                 screens[i].idx = i;
2924                 TAILQ_INIT(&screens[i].rl);
2925                 TAILQ_INIT(&screens[i].orl);
2926                 screens[i].root = RootWindow(display, i);
2927
2928                 /* set default colors */
2929                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
2930                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
2931                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
2932                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
2933                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
2934
2935                 /* init all workspaces */
2936                 /* XXX these should be dynamically allocated too */
2937                 for (j = 0; j < SWM_WS_MAX; j++) {
2938                         ws = &screens[i].ws[j];
2939                         ws->idx = j;
2940                         ws->restack = 1;
2941                         ws->focus = NULL;
2942                         ws->r = NULL;
2943                         TAILQ_INIT(&ws->winlist);
2944
2945                         for (k = 0; layouts[k].l_stack != NULL; k++)
2946                                 if (layouts[k].l_config != NULL)
2947                                         layouts[k].l_config(ws,
2948                                             SWM_ARG_ID_STACKINIT);
2949                         ws->cur_layout = &layouts[0];
2950                 }
2951                 /* grab existing windows (before we build the bars)*/
2952                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
2953                         continue;
2954
2955                 scan_xrandr(i);
2956
2957                 if (xrandr_support)
2958                         XRRSelectInput(display, screens[i].root,
2959                             RRScreenChangeNotifyMask);
2960
2961                 /* attach windows to a region */
2962                 /* normal windows */
2963                 for (j = 0; j < no; j++) {
2964                         XGetWindowAttributes(display, wins[j], &wa);
2965                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
2966                             wa.override_redirect ||
2967                             XGetTransientForHint(display, wins[j], &d1))
2968                                 continue;
2969
2970                         if (wa.map_state == IsViewable ||
2971                             getstate(wins[j]) == NormalState)
2972                                 manage_window(wins[j]);
2973                 }
2974                 /* transient windows */
2975                 for (j = 0; j < no; j++) {
2976                         if (!XGetWindowAttributes(display, wins[j], &wa))
2977                                 continue;
2978
2979                         if (XGetTransientForHint(display, wins[j], &d1) &&
2980                             (wa.map_state == IsViewable || getstate(wins[j]) ==
2981                             NormalState))
2982                                 manage_window(wins[j]);
2983                 }
2984                 if (wins) {
2985                         XFree(wins);
2986                         wins = NULL;
2987                 }
2988         }
2989 }
2990
2991 void
2992 workaround(void)
2993 {
2994         int                     i;
2995         Atom                    netwmcheck, netwmname, utf8_string;
2996         Window                  root;
2997
2998         /* work around sun jdk bugs, code from wmname */
2999         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
3000         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
3001         utf8_string = XInternAtom(display, "UTF8_STRING", False);
3002         for (i = 0; i < ScreenCount(display); i++) {
3003                 root = screens[i].root;
3004                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
3005                     PropModeReplace, (unsigned char *)&root, 1);
3006                 XChangeProperty(display, root, netwmname, utf8_string, 8,
3007                     PropModeReplace, "LG3D", strlen("LG3D"));
3008         }
3009 }
3010
3011 int
3012 main(int argc, char *argv[])
3013 {
3014         struct passwd           *pwd;
3015         struct swm_region       *r;
3016         char                    conf[PATH_MAX], *cfile = NULL;
3017         struct stat             sb;
3018         XEvent                  e;
3019         int                     xfd, i;
3020         fd_set                  rd;
3021
3022         start_argv = argv;
3023         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
3024             SWM_VERSION, cvstag);
3025         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
3026                 warnx("no locale support");
3027
3028         if (!(display = XOpenDisplay(0)))
3029                 errx(1, "can not open display");
3030
3031         if (active_wm())
3032                 errx(1, "other wm running");
3033
3034         astate = XInternAtom(display, "WM_STATE", False);
3035         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
3036         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
3037
3038         /* look for local and global conf file */
3039         pwd = getpwuid(getuid());
3040         if (pwd == NULL)
3041                 errx(1, "invalid user %d", getuid());
3042
3043         setup_screens();
3044
3045         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
3046         if (stat(conf, &sb) != -1) {
3047                 if (S_ISREG(sb.st_mode))
3048                         cfile = conf;
3049         } else {
3050                 /* try global conf file */
3051                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
3052                 if (!stat(conf, &sb))
3053                         if (S_ISREG(sb.st_mode))
3054                                 cfile = conf;
3055         }
3056         if (cfile)
3057                 conf_load(cfile);
3058
3059         /* setup all bars */
3060         for (i = 0; i < ScreenCount(display); i++)
3061                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3062                         bar_setup(r);
3063
3064         /* set some values to work around bad programs */
3065         workaround();
3066
3067         grabkeys();
3068         stack();
3069
3070         xfd = ConnectionNumber(display);
3071         while (running) {
3072                 FD_ZERO(&rd);
3073                 FD_SET(xfd, &rd);
3074                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
3075                         if (errno != EINTR)
3076                                 errx(1, "select failed");
3077                 if (bar_alarm) {
3078                         bar_alarm = 0;
3079                         bar_update();
3080                 }
3081                 while (XPending(display)) {
3082                         XNextEvent(display, &e);
3083                         if (e.type < LASTEvent) {
3084                                 if (handler[e.type])
3085                                         handler[e.type](&e);
3086                                 else
3087                                         DNPRINTF(SWM_D_EVENT,
3088                                             "win: %lu unknown event: %d\n",
3089                                             e.xany.window, e.type);
3090                         } else {
3091                                 switch (e.type - xrandr_eventbase) {
3092                                 case RRScreenChangeNotify:
3093                                         screenchange(&e);
3094                                         break;
3095                                 default:
3096                                         DNPRINTF(SWM_D_EVENT,
3097                                             "win: %lu unknown xrandr event: "
3098                                             "%d\n", e.xany.window, e.type);
3099                                         break;
3100                                 }
3101                         }
3102                 }
3103         }
3104
3105         XCloseDisplay(display);
3106
3107         return (0);
3108 }