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