chamesle

chamesle.org: the site of Chamesle, a small Linux distribution
git clone https://github.com/tortr-rs/chamesle
Log | Files | Refs | README

ttywm.c (67364B)


      1 /* ttywm - floating window manager that looks like a tty */
      2 #include <ctype.h>
      3 #include <dirent.h>
      4 #include <errno.h>
      5 #include <locale.h>
      6 #include <signal.h>
      7 #include <stdint.h>
      8 #include <stdio.h>
      9 #include <stdlib.h>
     10 #include <string.h>
     11 #include <strings.h>
     12 #include <time.h>
     13 #include <unistd.h>
     14 #include <sys/select.h>
     15 #include <sys/stat.h>
     16 #include <sys/time.h>
     17 #include <dbus/dbus.h>
     18 #include <security/pam_appl.h>
     19 #include <X11/Xatom.h>
     20 #include <X11/Xlib.h>
     21 #include <X11/Xutil.h>
     22 #include <X11/XKBlib.h>
     23 #include <X11/cursorfont.h>
     24 #include <X11/Xft/Xft.h>
     25 
     26 #define LENGTH(X)       (sizeof(X) / sizeof(X)[0])
     27 #define MAX(A, B)       ((A) > (B) ? (A) : (B))
     28 #define MIN(A, B)       ((A) < (B) ? (A) : (B))
     29 #define CLEANMASK(mask) ((mask) & ~(LockMask|Mod2Mask))
     30 #define NSCR            9
     31 #define SHELLCLASS      "TtywmShell"
     32 #define SHELLCMD        "ttywm-term"
     33 
     34 enum { ColBg, ColWindow, ColOther, ColTitle, ColBar, ColLast };
     35 enum { ActRun, ActTerminal, ActMenu, ActClose, ActNext, ActFull, ActQuit, ActView, ActSend, ActVolUp, ActVolDown, ActMute,
     36        ActLightUp, ActLightDown, ActLeft, ActRight, ActMax, ActRestore, ActLock, ActRestart };
     37 enum { SegNone, SegNet, SegVol, SegLight, SegTty, SegWin };
     38 /* what the bottom line can show, in the order it's given */
     39 enum { BarCommands, BarNet, BarVol, BarLight, BarBattery, BarDate, BarClock, BarTty, BarLast };
     40 
     41 typedef struct {
     42 	unsigned int mod;
     43 	KeySym keysym;
     44 	int act, n;
     45 	char *cmd;
     46 } Key;
     47 
     48 typedef struct Notif Notif;
     49 struct Notif {
     50 	unsigned int id;
     51 	char app[64], line[4][128];
     52 	int nlines, w, h;
     53 	time_t until;
     54 	Window win;
     55 	XftDraw *draw;
     56 	Notif *next;
     57 };
     58 
     59 typedef struct Client Client;
     60 struct Client {
     61 	char name[256];
     62 	int x, y, w, h, oldx, oldy, oldw, oldh;
     63 	int scr, isfull, ignoreunmap;
     64 	int snapped, sx, sy, sw, sh;	/* where it was before super+arrows */
     65 	int typed, total;		/* the border typing itself in: cells so far, of all */
     66 	long long born;			/* when it started, ms */
     67 	Window win, frame;
     68 	Pixmap pix;			/* the frame is drawn here, then copied: no flashing */
     69 	int pw, ph;
     70 	XftDraw *draw;
     71 	Client *next;
     72 };
     73 
     74 /* window firefox = tty 2, full screen */
     75 typedef struct {
     76 	char name[64];
     77 	int scr, full;
     78 } Rule;
     79 
     80 /* settings, from ~/.config/ttywm/config */
     81 static char terminal[256] = "ttywm-term", menu[256] = "launchel";
     82 static char colname[ColLast][32] = { "black", "white", "grey", "white", "grey" };
     83 static int clock24 = 1, showclock = 1, showdate = 1, showbattery = 1, shownetwork = 1, showvolume = 1, showlight = 1, big;
     84 static int typing = 1, typespeed = 600;	/* cells a second */
     85 static int winlist = 1, shells;	/* shells: the old look, a full screen shell behind the windows */
     86 static char wallpaper[1024], wallfit[16] = "fill";
     87 static int barorder[BarLast + 1] = { BarCommands, BarNet, BarVol, BarLight, BarBattery, BarDate, BarClock, BarTty, -1 };
     88 static char barcmd[4][256], barout[4][64];
     89 static int nbarcmds;
     90 static Key *keys;
     91 static int nkeys;
     92 static Rule *rules;
     93 static int nrules;
     94 
     95 static const char defaultconfig[] =
     96 "# ttywm settings\n"
     97 "# change what's after the = and save. it works right away.\n"
     98 "\n"
     99 "# colours: black blue green cyan red magenta brown grey\n"
    100 "#          dark grey, light blue, light green, light cyan, light red, pink, yellow, white\n"
    101 "#          or #rrggbb\n"
    102 "window colour = white\n"
    103 "other windows colour = grey\n"
    104 "title colour = white\n"
    105 "bottom line colour = grey\n"
    106 "background colour = black\n"
    107 "\n"
    108 "# a picture behind the windows, png or jpeg. nothing means the background colour\n"
    109 "wallpaper =\n"
    110 "# fill the screen, fit in it, centre or tile\n"
    111 "wallpaper fit = fill\n"
    112 "# the old look: a shell on every tty, behind the windows\n"
    113 "shell behind windows = off\n"
    114 "\n"
    115 "# normal or big. big is for small, sharp screens. changes when you log in again\n"
    116 "text size = normal\n"
    117 "\n"
    118 "# new windows type their border in, closed ones type it away. on or off, and fast, normal or slow\n"
    119 "border typing = on\n"
    120 "typing speed = normal\n"
    121 "\n"
    122 "# what's on the bottom line, in this order. leave out what you don't want:\n"
    123 "#   commands network volume brightness battery date clock tty\n"
    124 "bottom line = commands network volume brightness battery date clock tty\n"
    125 "# the windows on this tty, on the left of the bottom line. click one to go to it, middle click to close it\n"
    126 "window list = on\n"
    127 "# 24 hour or 12 hour\n"
    128 "clock = 24 hour\n"
    129 "# your own things on the bottom line: a command, its first line shows. up to 4, every 5 seconds\n"
    130 "# bottom line command = cat /sys/class/thermal/thermal_zone0/temp\n"
    131 "\n"
    132 "# the terminal for new windows, and the apps menu\n"
    133 "terminal = ttywm-term\n"
    134 "apps menu = launchel\n"
    135 "\n"
    136 "# keys. super is the windows key, then shift, ctrl, alt. after the = goes one of:\n"
    137 "#   terminal, apps menu, close window, next window, full screen, log out, lock,\n"
    138 "#   left half, right half, fill screen, put back, tty 1 to tty 9, send to tty 1 to 9,\n"
    139 "#   volume up, volume down, mute, brightness up, brightness down, restart\n"
    140 "# or any program, like firefox\n"
    141 "super+enter = terminal\n"
    142 "super+d = apps menu\n"
    143 "super+q = close window\n"
    144 "super+tab = next window\n"
    145 "super+f = full screen\n"
    146 "super+shift+e = log out\n"
    147 "# these are there unless you put something else on the key:\n"
    148 "# super+1 to 9 = tty 1 to 9, super+shift+1 to 9 = send to tty 1 to 9, super+l = lock,\n"
    149 "# super+left = left half, super+right = right half, super+up = fill screen, super+down = put back\n"
    150 "\n"
    151 "# where windows go, by their name (the class xprop shows): tty 1 to 9, full screen, or both\n"
    152 "# window firefox = tty 2\n"
    153 "# window mpv = full screen\n"
    154 "\n"
    155 "# programs to start when you log in, one per line, like:\n"
    156 "# start = firefox\n"
    157 "\n"
    158 "# more settings from another file, read as if they were here\n"
    159 "# include = ~/.config/ttywm/keys\n";
    160 
    161 static Display *dpy;
    162 static Window root, bar, wmcheck;
    163 static int sw, sh, wh, cw, ch;
    164 static int cur, newshell = -1, running = 1, restarting;
    165 static char exepath[4096];
    166 static struct stat exest;	/* the binary when we started: a new one means an update */
    167 static Window shell[NSCR];
    168 static Client *clients, *sel, *ghosts;	/* ghosts: closed windows' borders, typing themselves away */
    169 static XftFont *xfont;
    170 static XftDraw *bardraw;
    171 static XftColor col[ColLast];
    172 static Atom wmprotocols, wmdelete, wmstate, netwmname, netwmstate, netfullscreen, netwmcheck, utf8string;
    173 static char cfgpath[4096];
    174 static time_t cfgmtime;
    175 static int vol = -1, muted;
    176 static void (*handler[LASTEvent])(XEvent *);
    177 static char backlight[256];	/* /sys/class/backlight/..., or empty */
    178 static DBusConnection *bus;
    179 static Notif *notifs;
    180 static unsigned int lastid;
    181 static struct { int x0, x1, seg; Client *c; } segs[48];
    182 static int nsegs;
    183 
    184 static int ulen(const char *);
    185 static void ucut(char *, const char *, int, size_t);
    186 static void focus(Client *);
    187 static void closeclient(Client *);
    188 static void view(int);
    189 static void setfullscreen(Client *, int);
    190 
    191 static void
    192 die(const char *s)
    193 {
    194 	fprintf(stderr, "ttywm: %s\n", s);
    195 	exit(1);
    196 }
    197 
    198 static int
    199 xerror(Display *d, XErrorEvent *ee)
    200 {
    201 	/* windows die while we talk to them */
    202 	if (ee->error_code == BadWindow || ee->error_code == BadMatch || ee->error_code == BadDrawable)
    203 		return 0;
    204 	fprintf(stderr, "ttywm: X error %d, request %d\n", ee->error_code, ee->request_code);
    205 	return 0;
    206 }
    207 
    208 static int
    209 xerrorstart(Display *d, XErrorEvent *ee)
    210 {
    211 	die("another window manager is already running");
    212 	return -1;
    213 }
    214 
    215 static int
    216 inpath(const char *cmd)
    217 {
    218 	char buf[4096], path[4096], *p, *dir;
    219 
    220 	snprintf(buf, sizeof buf, "%s", getenv("PATH") ? getenv("PATH") : "/usr/bin:/bin");
    221 	for (p = buf; (dir = strsep(&p, ":"));) {
    222 		snprintf(path, sizeof path, "%s/%s", *dir ? dir : ".", cmd);
    223 		if (access(path, X_OK) == 0)
    224 			return 1;
    225 	}
    226 	return 0;
    227 }
    228 
    229 static void
    230 run(const char *cmd)
    231 {
    232 	if (fork() == 0) {
    233 		if (dpy)
    234 			close(ConnectionNumber(dpy));
    235 		setsid();
    236 		execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
    237 		_exit(1);
    238 	}
    239 }
    240 
    241 /* the apps menu, or launchel if what the settings name isn't there (rofi, from before 0.6-r4) */
    242 static void
    243 runmenu(void)
    244 {
    245 	char prog[256];
    246 
    247 	sscanf(menu, "%255s", prog);
    248 	run(inpath(prog) || prog[0] == '/' ? menu : "launchel");
    249 }
    250 
    251 /* runs cmd and waits for it, keeping the first line it prints */
    252 static void
    253 runwait(const char *cmd, char *out, size_t n)
    254 {
    255 	FILE *f;
    256 
    257 	if (out)
    258 		*out = '\0';
    259 	if (!(f = popen(cmd, "r")))
    260 		return;
    261 	if (out && !fgets(out, n, f))
    262 		*out = '\0';
    263 	while (fgetc(f) != EOF);
    264 	pclose(f);
    265 }
    266 
    267 static int
    268 readfile(const char *path, char *buf, size_t n)
    269 {
    270 	FILE *f;
    271 	size_t len;
    272 
    273 	if (!(f = fopen(path, "r")))
    274 		return 0;
    275 	len = fread(buf, 1, n - 1, f);
    276 	fclose(f);
    277 	buf[len] = '\0';
    278 	while (len && isspace((unsigned char)buf[len - 1]))
    279 		buf[--len] = '\0';
    280 	return 1;
    281 }
    282 
    283 static long
    284 readnum(const char *dir, const char *file)
    285 {
    286 	char path[512], buf[64];
    287 
    288 	snprintf(path, sizeof path, "%s/%s", dir, file);
    289 	return readfile(path, buf, sizeof buf) ? atol(buf) : -1;
    290 }
    291 
    292 /* ---- settings ---- */
    293 
    294 static char *
    295 trim(char *s)
    296 {
    297 	char *e;
    298 
    299 	while (isspace((unsigned char)*s))
    300 		s++;
    301 	for (e = s + strlen(s); e > s && isspace((unsigned char)e[-1]); e--);
    302 	*e = '\0';
    303 	return s;
    304 }
    305 
    306 /* "Dark  Grey" -> "darkgrey" */
    307 static void
    308 squash(char *dst, const char *src, size_t n)
    309 {
    310 	size_t i = 0;
    311 
    312 	for (; *src && i < n - 1; src++)
    313 		if (!isspace((unsigned char)*src))
    314 			dst[i++] = tolower((unsigned char)*src);
    315 	dst[i] = '\0';
    316 }
    317 
    318 static int
    319 yes(const char *v)
    320 {
    321 	char s[16];
    322 
    323 	squash(s, v, sizeof s);
    324 	return !strcmp(s, "on") || !strcmp(s, "yes") || !strcmp(s, "true") || !strcmp(s, "1");
    325 }
    326 
    327 static const char *
    328 colourhex(const char *name)
    329 {
    330 	static const char *vga[][2] = {
    331 		{ "black", "#000000" }, { "blue", "#0000aa" }, { "green", "#00aa00" }, { "cyan", "#00aaaa" },
    332 		{ "red", "#aa0000" }, { "magenta", "#aa00aa" }, { "brown", "#aa5500" }, { "grey", "#aaaaaa" },
    333 		{ "gray", "#aaaaaa" }, { "darkgrey", "#555555" }, { "darkgray", "#555555" },
    334 		{ "lightblue", "#5555ff" }, { "lightgreen", "#55ff55" }, { "lightcyan", "#55ffff" },
    335 		{ "lightred", "#ff5555" }, { "pink", "#ff55ff" }, { "yellow", "#ffff55" }, { "white", "#ffffff" },
    336 	};
    337 	char s[32];
    338 	unsigned int i;
    339 
    340 	squash(s, name, sizeof s);
    341 	for (i = 0; i < LENGTH(vga); i++)
    342 		if (!strcmp(s, vga[i][0]))
    343 			return vga[i][1];
    344 	return name;	/* #rrggbb, or any name X knows */
    345 }
    346 
    347 /* "window colour" or "window color" */
    348 static int
    349 iskey(const char *key, const char *want)
    350 {
    351 	char alt[64];
    352 	const char *p;
    353 
    354 	if (!strcmp(key, want))
    355 		return 1;
    356 	if (!(p = strstr(want, "colour")))
    357 		return 0;
    358 	snprintf(alt, sizeof alt, "%.*scolor%s", (int)(p - want), want, p + 6);
    359 	return !strcmp(key, alt);
    360 }
    361 
    362 static KeySym
    363 keyname(const char *s)
    364 {
    365 	static const char *names[][2] = {
    366 		{ "enter", "Return" }, { "return", "Return" }, { "tab", "Tab" }, { "space", "space" },
    367 		{ "esc", "Escape" }, { "escape", "Escape" }, { "backspace", "BackSpace" }, { "delete", "Delete" },
    368 		{ "up", "Up" }, { "down", "Down" }, { "left", "Left" }, { "right", "Right" },
    369 		{ "home", "Home" }, { "end", "End" }, { "print", "Print" }, { "printscreen", "Print" },
    370 	};
    371 	char buf[32];
    372 	unsigned int i;
    373 
    374 	for (i = 0; i < LENGTH(names); i++)
    375 		if (!strcmp(s, names[i][0]))
    376 			return XStringToKeysym(names[i][1]);
    377 	if (s[0] == 'f' && isdigit((unsigned char)s[1])) {
    378 		snprintf(buf, sizeof buf, "F%s", s + 1);
    379 		return XStringToKeysym(buf);
    380 	}
    381 	return XStringToKeysym(s);
    382 }
    383 
    384 static void
    385 addkey(unsigned int mod, KeySym sym, int act, int n, const char *cmd)
    386 {
    387 	Key *k;
    388 
    389 	if (!sym || !(k = realloc(keys, (nkeys + 1) * sizeof(Key))))
    390 		return;
    391 	keys = k;
    392 	k = &keys[nkeys++];
    393 	k->mod = mod;
    394 	k->keysym = sym;
    395 	k->act = act;
    396 	k->n = n;
    397 	k->cmd = cmd ? strdup(cmd) : NULL;
    398 }
    399 
    400 /* super+shift+e = log out */
    401 static int
    402 parsekey(char *name, char *value)
    403 {
    404 	static const struct { const char *word; int act; } acts[] = {
    405 		{ "terminal", ActTerminal }, { "appsmenu", ActMenu }, { "menu", ActMenu },
    406 		{ "closewindow", ActClose }, { "close", ActClose }, { "nextwindow", ActNext },
    407 		{ "fullscreen", ActFull }, { "logout", ActQuit }, { "quit", ActQuit }, { "lock", ActLock },
    408 		{ "lockscreen", ActLock }, { "lefthalf", ActLeft }, { "righthalf", ActRight },
    409 		{ "fillscreen", ActMax }, { "putback", ActRestore }, { "volumeup", ActVolUp },
    410 		{ "volumedown", ActVolDown }, { "mute", ActMute }, { "brightnessup", ActLightUp },
    411 		{ "brightnessdown", ActLightDown }, { "restart", ActRestart },
    412 	};
    413 	unsigned int mod = 0, i;
    414 	char *tok, *last = NULL, act[64];
    415 	int n;
    416 
    417 	if (!strchr(name, '+'))
    418 		return 0;
    419 	for (tok = strtok(name, "+"); tok; tok = strtok(NULL, "+")) {
    420 		tok = trim(tok);
    421 		if (last) {
    422 			if (!strcmp(last, "super") || !strcmp(last, "win") || !strcmp(last, "windows"))
    423 				mod |= Mod4Mask;
    424 			else if (!strcmp(last, "shift"))
    425 				mod |= ShiftMask;
    426 			else if (!strcmp(last, "ctrl") || !strcmp(last, "control"))
    427 				mod |= ControlMask;
    428 			else if (!strcmp(last, "alt"))
    429 				mod |= Mod1Mask;
    430 			else
    431 				return 0;
    432 		}
    433 		last = tok;
    434 	}
    435 	if (!last)
    436 		return 0;
    437 	squash(act, value, sizeof act);
    438 	/* tty 3, send to tty 3 */
    439 	if ((!strncmp(act, "tty", 3) && (n = atoi(act + 3)) >= 1 && n <= NSCR)
    440 	|| (!strncmp(act, "sendtotty", 9) && (n = atoi(act + 9)) >= 1 && n <= NSCR)) {
    441 		addkey(mod, keyname(last), act[0] == 't' ? ActView : ActSend, n - 1, NULL);
    442 		return 1;
    443 	}
    444 	for (i = 0; i < LENGTH(acts); i++)
    445 		if (!strcmp(act, acts[i].word)) {
    446 			addkey(mod, keyname(last), acts[i].act, 0, NULL);
    447 			return 1;
    448 		}
    449 	addkey(mod, keyname(last), ActRun, 0, value);
    450 	return 1;
    451 }
    452 
    453 /* window firefox = tty 2, full screen */
    454 static void
    455 addrule(const char *name, char *value)
    456 {
    457 	Rule *r;
    458 	char *w, word[32];
    459 
    460 	if (!*name || !(r = realloc(rules, (nrules + 1) * sizeof(Rule))))
    461 		return;
    462 	rules = r;
    463 	r = &rules[nrules++];
    464 	snprintf(r->name, sizeof r->name, "%s", name);
    465 	r->scr = -1;
    466 	r->full = 0;
    467 	for (w = strtok(value, ","); w; w = strtok(NULL, ",")) {
    468 		squash(word, w, sizeof word);
    469 		if (!strncmp(word, "tty", 3) && atoi(word + 3) >= 1 && atoi(word + 3) <= NSCR)
    470 			r->scr = atoi(word + 3) - 1;
    471 		else if (!strcmp(word, "fullscreen"))
    472 			r->full = 1;
    473 	}
    474 }
    475 
    476 /* bottom line = network volume clock tty */
    477 static void
    478 setbar(char *value)
    479 {
    480 	static const char *names[] = { "commands", "network", "volume", "brightness", "battery", "date", "clock", "tty" };
    481 	char *w;
    482 	int n = 0, i;
    483 
    484 	for (w = strtok(value, " \t,"); w && n < BarLast; w = strtok(NULL, " \t,"))
    485 		for (i = 0; i < BarLast; i++)
    486 			if (!strcasecmp(w, names[i]))
    487 				barorder[n++] = i;
    488 	barorder[n] = -1;
    489 }
    490 
    491 static int
    492 haskey(unsigned int mod, KeySym sym)
    493 {
    494 	int i;
    495 
    496 	for (i = 0; i < nkeys; i++)
    497 		if (keys[i].mod == mod && keys[i].keysym == sym)
    498 			return 1;
    499 	return 0;
    500 }
    501 
    502 static void
    503 defkey(unsigned int mod, KeySym sym, int act, int n)
    504 {
    505 	if (!haskey(mod, sym))
    506 		addkey(mod, sym, act, n, NULL);
    507 }
    508 
    509 static void
    510 readconfig(FILE *f, int firsttime, int depth)
    511 {
    512 	char line[1024], path[4096], *name, *value, *eq, key[64], *home;
    513 	FILE *inc;
    514 
    515 	while (fgets(line, sizeof line, f)) {
    516 		if ((eq = strchr(line, '#')))
    517 			*eq = '\0';
    518 		if (!(eq = strchr(line, '=')))
    519 			continue;
    520 		*eq = '\0';
    521 		name = trim(line);
    522 		value = trim(eq + 1);
    523 		for (eq = name; *eq; eq++)
    524 			*eq = tolower((unsigned char)*eq);
    525 		if (parsekey(name, value))
    526 			continue;
    527 		squash(key, name, sizeof key);
    528 		if (!strncmp(name, "window ", 7) && !iskey(key, "windowcolour")) {
    529 			addrule(trim(name + 7), value);
    530 			continue;
    531 		}
    532 		if (iskey(key, "windowcolour"))
    533 			snprintf(colname[ColWindow], sizeof colname[0], "%s", value);
    534 		else if (iskey(key, "otherwindowscolour"))
    535 			snprintf(colname[ColOther], sizeof colname[0], "%s", value);
    536 		else if (iskey(key, "titlecolour"))
    537 			snprintf(colname[ColTitle], sizeof colname[0], "%s", value);
    538 		else if (iskey(key, "bottomlinecolour"))
    539 			snprintf(colname[ColBar], sizeof colname[0], "%s", value);
    540 		else if (iskey(key, "backgroundcolour"))
    541 			snprintf(colname[ColBg], sizeof colname[0], "%s", value);
    542 		else if (!strcmp(key, "textsize")) {
    543 			if (firsttime)
    544 				big = !strcasecmp(value, "big");
    545 		}
    546 		else if (!strcmp(key, "bordertyping"))
    547 			typing = yes(value);
    548 		else if (!strcmp(key, "typingspeed")) {
    549 			squash(key, value, sizeof key);
    550 			typespeed = !strcmp(key, "fast") ? 1500 : !strcmp(key, "slow") ? 250 : 600;
    551 		}
    552 		else if (!strcmp(key, "bottomline"))
    553 			setbar(value);
    554 		else if (!strcmp(key, "bottomlinecommand")) {
    555 			if (nbarcmds < (int)LENGTH(barcmd))
    556 				snprintf(barcmd[nbarcmds++], sizeof barcmd[0], "%s", value);
    557 		}
    558 		else if (!strcmp(key, "windowlist"))
    559 			winlist = yes(value);
    560 		else if (!strcmp(key, "wallpaper"))
    561 			snprintf(wallpaper, sizeof wallpaper, "%s", value);
    562 		else if (!strcmp(key, "wallpaperfit"))
    563 			squash(wallfit, value, sizeof wallfit);
    564 		else if (!strcmp(key, "shellbehindwindows"))
    565 			shells = yes(value);
    566 		else if (!strcmp(key, "network"))
    567 			shownetwork = yes(value);
    568 		else if (!strcmp(key, "volume"))
    569 			showvolume = yes(value);
    570 		else if (!strcmp(key, "brightness"))
    571 			showlight = yes(value);
    572 		else if (!strcmp(key, "battery"))
    573 			showbattery = yes(value);
    574 		else if (!strcmp(key, "date"))
    575 			showdate = yes(value);
    576 		else if (!strcmp(key, "clock")) {
    577 			squash(key, value, sizeof key);
    578 			showclock = strcmp(key, "off") != 0;
    579 			clock24 = strncmp(key, "12", 2) != 0;
    580 		} else if (!strcmp(key, "terminal"))
    581 			snprintf(terminal, sizeof terminal, "%s", value);
    582 		else if (!strcmp(key, "appsmenu") || !strcmp(key, "menu"))
    583 			snprintf(menu, sizeof menu, "%s", value);
    584 		else if (!strcmp(key, "start")) {
    585 			if (firsttime)
    586 				run(value);
    587 		}
    588 		else if (!strcmp(key, "include")) {
    589 			/* ~/x, or next to the config */
    590 			if (value[0] == '~' && (home = getenv("HOME")))
    591 				snprintf(path, sizeof path, "%s%s", home, value + 1);
    592 			else if (value[0] != '/')
    593 				snprintf(path, sizeof path, "%.*s/%s", (int)(strrchr(cfgpath, '/') - cfgpath), cfgpath, value);
    594 			else
    595 				snprintf(path, sizeof path, "%s", value);
    596 			if (depth < 4 && (inc = fopen(path, "r"))) {
    597 				readconfig(inc, firsttime, depth + 1);
    598 				fclose(inc);
    599 			} else
    600 				fprintf(stderr, "ttywm: can't include %s\n", path);
    601 		}
    602 		else
    603 			fprintf(stderr, "ttywm: %s: don't know '%s'\n", cfgpath, name);
    604 	}
    605 }
    606 
    607 static void
    608 loadconfig(int firsttime)
    609 {
    610 	FILE *f;
    611 	int i;
    612 	struct stat st;
    613 
    614 	if (stat(cfgpath, &st) < 0 && (f = fopen(cfgpath, "w"))) {
    615 		fputs(defaultconfig, f);
    616 		fclose(f);
    617 	}
    618 	if (stat(cfgpath, &st) == 0)
    619 		cfgmtime = st.st_mtime;
    620 
    621 	for (i = 0; i < nkeys; i++)
    622 		free(keys[i].cmd);
    623 	nkeys = 0;
    624 	nrules = 0;
    625 	nbarcmds = 0;
    626 	wallpaper[0] = '\0';
    627 	shells = 0;
    628 	f = fopen(cfgpath, "r");
    629 	if (!f) {
    630 		/* no file and nowhere to write one: the defaults, straight from memory */
    631 		f = fmemopen((void *)defaultconfig, sizeof defaultconfig - 1, "r");
    632 		if (!f)
    633 			return;
    634 	}
    635 	readconfig(f, firsttime, 0);
    636 	fclose(f);
    637 
    638 	/* these are there unless the key does something else */
    639 	for (i = 0; i < NSCR; i++) {
    640 		defkey(Mod4Mask, XK_1 + i, ActView, i);
    641 		defkey(Mod4Mask|ShiftMask, XK_1 + i, ActSend, i);
    642 	}
    643 	defkey(0, XStringToKeysym("XF86AudioRaiseVolume"), ActVolUp, 0);
    644 	defkey(0, XStringToKeysym("XF86AudioLowerVolume"), ActVolDown, 0);
    645 	defkey(0, XStringToKeysym("XF86AudioMute"), ActMute, 0);
    646 	defkey(0, XStringToKeysym("XF86MonBrightnessUp"), ActLightUp, 0);
    647 	defkey(0, XStringToKeysym("XF86MonBrightnessDown"), ActLightDown, 0);
    648 	defkey(Mod4Mask, XK_Left, ActLeft, 0);
    649 	defkey(Mod4Mask, XK_Right, ActRight, 0);
    650 	defkey(Mod4Mask, XK_Up, ActMax, 0);
    651 	defkey(Mod4Mask, XK_Down, ActRestore, 0);
    652 	defkey(Mod4Mask, XK_l, ActLock, 0);
    653 }
    654 
    655 static void
    656 grabkeys(void)
    657 {
    658 	unsigned int j, mods[] = { 0, LockMask, Mod2Mask, LockMask|Mod2Mask };
    659 	KeyCode code;
    660 	int i;
    661 
    662 	XUngrabKey(dpy, AnyKey, AnyModifier, root);
    663 	for (i = 0; i < nkeys; i++)
    664 		if ((code = XKeysymToKeycode(dpy, keys[i].keysym)))
    665 			for (j = 0; j < LENGTH(mods); j++)
    666 				XGrabKey(dpy, code, keys[i].mod | mods[j], root, True, GrabModeAsync, GrabModeAsync);
    667 }
    668 
    669 static void
    670 loadcolours(void)
    671 {
    672 	static int loaded;
    673 	Visual *vis = DefaultVisual(dpy, DefaultScreen(dpy));
    674 	Colormap cmap = DefaultColormap(dpy, DefaultScreen(dpy));
    675 	int i;
    676 
    677 	for (i = 0; i < ColLast; i++) {
    678 		if (loaded)
    679 			XftColorFree(dpy, vis, cmap, &col[i]);
    680 		if (!XftColorAllocName(dpy, vis, cmap, colourhex(colname[i]), &col[i])
    681 		&& !XftColorAllocName(dpy, vis, cmap, i == ColBg ? "#000000" : "#aaaaaa", &col[i]))
    682 			die("cannot allocate color");
    683 	}
    684 	loaded = 1;
    685 }
    686 
    687 /* ---- drawing ---- */
    688 
    689 static Client *
    690 wintoclient(Window w)
    691 {
    692 	Client *c;
    693 
    694 	for (c = clients; c; c = c->next)
    695 		if (c->win == w || c->frame == w)
    696 			return c;
    697 	return NULL;
    698 }
    699 
    700 static int
    701 shellof(Window w)
    702 {
    703 	int i;
    704 
    705 	for (i = 0; i < NSCR; i++)
    706 		if (shell[i] && shell[i] == w)
    707 			return i;
    708 	return -1;
    709 }
    710 
    711 static void
    712 text(XftDraw *d, int c, int x, int y, const char *s)
    713 {
    714 	XftDrawStringUtf8(d, &col[c], xfont, x, y + xfont->ascent, (const FcChar8 *)s, strlen(s));
    715 }
    716 
    717 static long long
    718 ms(void)
    719 {
    720 	struct timespec ts;
    721 
    722 	clock_gettime(CLOCK_MONOTONIC, &ts);
    723 	return ts.tv_sec * 1000LL + ts.tv_nsec / 1000000;
    724 }
    725 
    726 /* a pixmap the size of the frame, made again when the frame grows or shrinks */
    727 static void
    728 framepix(Client *c)
    729 {
    730 	int w = c->w + 2 * cw, h = c->h + 2 * ch, scr = DefaultScreen(dpy);
    731 
    732 	if (c->pix && c->pw == w && c->ph == h)
    733 		return;
    734 	if (c->draw)
    735 		XftDrawDestroy(c->draw);
    736 	if (c->pix)
    737 		XFreePixmap(dpy, c->pix);
    738 	c->pix = XCreatePixmap(dpy, c->frame, w, h, DefaultDepth(dpy, scr));
    739 	c->pw = w;
    740 	c->ph = h;
    741 	c->draw = XftDrawCreate(dpy, c->pix, DefaultVisual(dpy, scr), DefaultColormap(dpy, scr));
    742 	XftDrawRect(c->draw, &col[ColBg], 0, 0, w, h);
    743 }
    744 
    745 /* the border, the way it's typed: along the top, down the right, back along the bottom, up the left.
    746  * cell i of it, as a place and a character */
    747 static void
    748 framecell(Client *c, int i, int *x, int *y, char *ch8, int *colour)
    749 {
    750 	int cols = c->w / cw + 2, rows = c->h / ch;
    751 	int n = MIN((int)strlen(c->name), MAX(cols - 10, 0));
    752 	int bc = c == sel ? ColWindow : ColOther;
    753 
    754 	*colour = bc;
    755 	if (i < cols) {
    756 		/* ┌─[ name ]───[x]┐ */
    757 		*x = i, *y = 0;
    758 		if (i == 0) strcpy(ch8, "┌");
    759 		else if (i == 1) strcpy(ch8, "─");
    760 		else if (i == 2) strcpy(ch8, "[");
    761 		else if (i < n + 5) {
    762 			*colour = ColTitle;
    763 			ch8[0] = i == 3 || i == n + 4 ? ' ' : c->name[i - 4];
    764 			ch8[1] = '\0';
    765 		}
    766 		else if (i == n + 5) strcpy(ch8, "]");
    767 		else if (i == cols - 4) strcpy(ch8, "[");
    768 		else if (i == cols - 3) strcpy(ch8, "x");
    769 		else if (i == cols - 2) strcpy(ch8, "]");
    770 		else if (i == cols - 1) strcpy(ch8, "┐");
    771 		else strcpy(ch8, "─");
    772 		return;
    773 	}
    774 	i -= cols;
    775 	if (i < rows) {
    776 		*x = cols - 1, *y = i + 1;
    777 		strcpy(ch8, "│");
    778 		return;
    779 	}
    780 	i -= rows;
    781 	if (i < cols) {
    782 		*x = cols - 1 - i, *y = rows + 1;
    783 		strcpy(ch8, i == 0 ? "┘" : i == cols - 1 ? "└" : "─");
    784 		return;
    785 	}
    786 	i -= cols;
    787 	*x = 0, *y = rows - i;
    788 	strcpy(ch8, "│");
    789 }
    790 
    791 /* cells a to b, onto the pixmap and the screen. a cursor block after them while it's typing */
    792 static void
    793 typecells(Client *c, int a, int b)
    794 {
    795 	char g[8];
    796 	int i, x, y, colour, x0 = INT32_MAX, y0 = INT32_MAX, x1 = 0, y1 = 0;
    797 
    798 	for (i = a; i <= b && i < c->total; i++) {
    799 		framecell(c, i, &x, &y, g, &colour);
    800 		XftDrawRect(c->draw, &col[ColBg], x * cw, y * ch, cw, ch);
    801 		if (i < b || b >= c->total)
    802 			text(c->draw, colour, x * cw, y * ch, g);
    803 		else
    804 			text(c->draw, c == sel ? ColWindow : ColOther, x * cw, y * ch, "█");
    805 		x0 = MIN(x0, x); y0 = MIN(y0, y);
    806 		x1 = MAX(x1, x); y1 = MAX(y1, y);
    807 	}
    808 	if (x1 >= x0 && y1 >= y0)
    809 		XCopyArea(dpy, c->pix, c->frame, DefaultGC(dpy, DefaultScreen(dpy)), x0 * cw, y0 * ch,
    810 		          (x1 - x0 + 1) * cw, (y1 - y0 + 1) * ch, x0 * cw, y0 * ch);
    811 }
    812 
    813 /* the four edges of the pixmap onto the frame. the window covers the middle, except while the border types:
    814  * then the middle is the console's black too */
    815 static void
    816 showframe(Client *c)
    817 {
    818 	GC gc = DefaultGC(dpy, DefaultScreen(dpy));
    819 
    820 	if (c->typed < c->total) {
    821 		XCopyArea(dpy, c->pix, c->frame, gc, 0, 0, c->pw, c->ph, 0, 0);
    822 		return;
    823 	}
    824 	XCopyArea(dpy, c->pix, c->frame, gc, 0, 0, c->pw, ch, 0, 0);
    825 	XCopyArea(dpy, c->pix, c->frame, gc, 0, c->ph - ch, c->pw, ch, 0, c->ph - ch);
    826 	XCopyArea(dpy, c->pix, c->frame, gc, 0, ch, cw, c->ph - 2 * ch, 0, ch);
    827 	XCopyArea(dpy, c->pix, c->frame, gc, c->pw - cw, ch, cw, c->ph - 2 * ch, c->pw - cw, ch);
    828 }
    829 
    830 /* ┌─[ name ]───[x]┐ */
    831 static void
    832 drawframe(Client *c)
    833 {
    834 	char buf[2048], *p;
    835 	int cols = c->w / cw + 2, rows = c->h / ch;
    836 	int bc = c == sel ? ColWindow : ColOther;
    837 	int n = MIN((int)strlen(c->name), MAX(cols - 10, 0));
    838 	int i;
    839 
    840 	if (c->isfull)
    841 		return;
    842 	framepix(c);
    843 	c->total = 2 * cols + 2 * rows;
    844 	if (c->typed < c->total) {
    845 		/* still typing: what's typed so far, the rest comes with the next frames */
    846 		XftDrawRect(c->draw, &col[ColBg], 0, 0, c->pw, c->ph);
    847 		typecells(c, 0, c->typed);
    848 		showframe(c);
    849 		return;
    850 	}
    851 	XftDrawRect(c->draw, &col[ColBg], 0, 0, c->pw, ch);
    852 	XftDrawRect(c->draw, &col[ColBg], 0, c->ph - ch, c->pw, ch);
    853 	XftDrawRect(c->draw, &col[ColBg], 0, 0, cw, c->ph);
    854 	XftDrawRect(c->draw, &col[ColBg], c->pw - cw, 0, cw, c->ph);
    855 
    856 	text(c->draw, bc, 0, 0, "┌─[");
    857 	snprintf(buf, sizeof buf, " %.*s ", n, c->name);
    858 	text(c->draw, ColTitle, 3 * cw, 0, buf);
    859 	p = buf + sprintf(buf, "]");
    860 	for (i = n + 6; i < cols - 4; i++)
    861 		p += sprintf(p, "─");
    862 	sprintf(p, "[x]┐");
    863 	text(c->draw, bc, (n + 5) * cw, 0, buf);
    864 
    865 	for (i = 1; i <= rows; i++) {
    866 		text(c->draw, bc, 0, i * ch, "│");
    867 		text(c->draw, bc, (cols - 1) * cw, i * ch, "│");
    868 	}
    869 
    870 	p = buf + sprintf(buf, "└");
    871 	for (i = 2; i < cols; i++)
    872 		p += sprintf(p, "─");
    873 	sprintf(p, "┘");
    874 	text(c->draw, bc, 0, (rows + 1) * ch, buf);
    875 	showframe(c);
    876 }
    877 
    878 /* the typing, a few cells a frame. 1 while some border is still being typed */
    879 static int
    880 animate(void)
    881 {
    882 	Client *c, **pg;
    883 	int busy = 0, want;
    884 	long long now = ms();
    885 
    886 	for (c = clients; c; c = c->next) {
    887 		if (c->typed >= c->total)
    888 			continue;
    889 		want = MIN((now - c->born) * typespeed / 1000, c->total);
    890 		if (want > c->typed) {
    891 			typecells(c, c->typed, want);
    892 			c->typed = want;
    893 		}
    894 		if (c->typed >= c->total) {
    895 			/* done: the window comes out */
    896 			drawframe(c);
    897 			XMapWindow(dpy, c->win);
    898 			if (sel == c)
    899 				XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
    900 		} else
    901 			busy = 1;
    902 	}
    903 	for (pg = &ghosts; (c = *pg);) {
    904 		want = c->total - (now - c->born) * typespeed / 1000;
    905 		if (want <= 0) {
    906 			*pg = c->next;
    907 			XftDrawDestroy(c->draw);
    908 			XFreePixmap(dpy, c->pix);
    909 			XDestroyWindow(dpy, c->frame);
    910 			free(c);
    911 			continue;
    912 		}
    913 		if (want < c->typed) {
    914 			c->typed = want;
    915 			drawframe(c);
    916 		}
    917 		busy = 1;
    918 		pg = &c->next;
    919 	}
    920 	return busy;
    921 }
    922 
    923 /* ---- the bottom line ---- */
    924 
    925 static void
    926 readvolume(void)
    927 {
    928 	char buf[128];
    929 	float v;
    930 
    931 	vol = -1;
    932 	runwait("wpctl get-volume @DEFAULT_AUDIO_SINK@ 2>/dev/null", buf, sizeof buf);
    933 	if (sscanf(buf, "Volume: %f", &v) == 1) {
    934 		vol = v * 100 + 0.5;
    935 		muted = strstr(buf, "MUTED") != NULL;
    936 	}
    937 }
    938 
    939 /* the first backlight there is. the video group may write it */
    940 static void
    941 findbacklight(void)
    942 {
    943 	DIR *d;
    944 	struct dirent *e;
    945 
    946 	backlight[0] = '\0';
    947 	if (!(d = opendir("/sys/class/backlight")))
    948 		return;
    949 	while ((e = readdir(d)))
    950 		if (e->d_name[0] != '.') {
    951 			snprintf(backlight, sizeof backlight, "/sys/class/backlight/%s", e->d_name);
    952 			break;
    953 		}
    954 	closedir(d);
    955 }
    956 
    957 static int
    958 light(void)
    959 {
    960 	long now, max;
    961 
    962 	if (!backlight[0] || (now = readnum(backlight, "brightness")) < 0 || (max = readnum(backlight, "max_brightness")) <= 0)
    963 		return -1;
    964 	return (now * 100 + max / 2) / max;
    965 }
    966 
    967 static void
    968 setlight(int step)
    969 {
    970 	char path[300];
    971 	long max;
    972 	int pct = light();
    973 	FILE *f;
    974 
    975 	if (pct < 0 || (max = readnum(backlight, "max_brightness")) <= 0)
    976 		return;
    977 	/* 5% steps, but never all the way to black */
    978 	pct = MIN(MAX(pct + step, 1), 100);
    979 	snprintf(path, sizeof path, "%s/brightness", backlight);
    980 	if ((f = fopen(path, "w"))) {
    981 		fprintf(f, "%ld\n", MAX(pct * max / 100, 1));
    982 		fclose(f);
    983 	} else
    984 		fprintf(stderr, "ttywm: %s: can't write it, are you in the video group?\n", path);
    985 }
    986 
    987 static void
    988 network(char *s, size_t n)
    989 {
    990 	DIR *d;
    991 	struct dirent *e;
    992 	char path[512], state[32];
    993 	int wired = 0, wifi = 0;
    994 
    995 	if (!(d = opendir("/sys/class/net")))
    996 		return;
    997 	while ((e = readdir(d))) {
    998 		if (e->d_name[0] == '.' || !strcmp(e->d_name, "lo"))
    999 			continue;
   1000 		snprintf(path, sizeof path, "/sys/class/net/%s/operstate", e->d_name);
   1001 		if (!readfile(path, state, sizeof state) || strcmp(state, "up"))
   1002 			continue;
   1003 		snprintf(path, sizeof path, "/sys/class/net/%s/wireless", e->d_name);
   1004 		if (access(path, F_OK) == 0)
   1005 			wifi = 1;
   1006 		else
   1007 			wired = 1;
   1008 	}
   1009 	closedir(d);
   1010 	snprintf(s, n, "%s", wired ? "wired" : wifi ? "wifi" : "offline");
   1011 }
   1012 
   1013 /* all batteries together: a T480 has two */
   1014 static int
   1015 battery(char *s, size_t n)
   1016 {
   1017 	DIR *d;
   1018 	struct dirent *e;
   1019 	char dir[512], path[600], buf[32];
   1020 	long now = 0, full = 0, a, b;
   1021 	int charging = 0;
   1022 
   1023 	if (!(d = opendir("/sys/class/power_supply")))
   1024 		return 0;
   1025 	while ((e = readdir(d))) {
   1026 		snprintf(dir, sizeof dir, "/sys/class/power_supply/%s", e->d_name);
   1027 		snprintf(path, sizeof path, "%s/type", dir);
   1028 		if (!readfile(path, buf, sizeof buf) || strcmp(buf, "Battery"))
   1029 			continue;
   1030 		snprintf(path, sizeof path, "%s/status", dir);
   1031 		if (readfile(path, buf, sizeof buf) && !strcmp(buf, "Charging"))
   1032 			charging = 1;
   1033 		if ((a = readnum(dir, "energy_now")) < 0 || (b = readnum(dir, "energy_full")) <= 0) {
   1034 			a = readnum(dir, "charge_now");
   1035 			b = readnum(dir, "charge_full");
   1036 		}
   1037 		if (a >= 0 && b > 0) {
   1038 			now += a;
   1039 			full += b;
   1040 		}
   1041 	}
   1042 	closedir(d);
   1043 	if (!full)
   1044 		return 0;
   1045 	snprintf(s, n, "bat %ld%%%s", now * 100 / full, charging ? "+" : "");
   1046 	return 1;
   1047 }
   1048 
   1049 /* your own bottom line commands, every 5 seconds from tick */
   1050 static void
   1051 runbarcmds(void)
   1052 {
   1053 	int i;
   1054 
   1055 	for (i = 0; i < nbarcmds; i++) {
   1056 		runwait(barcmd[i], barout[i], sizeof barout[i]);
   1057 		barout[i][strcspn(barout[i], "\n")] = '\0';
   1058 	}
   1059 }
   1060 
   1061 /* [ firefox ] [ mpv ] on the left, the one with the keyboard in reverse, up to where the rest begins */
   1062 static void
   1063 drawwinlist(int end)
   1064 {
   1065 	char name[64], buf[80];
   1066 	Client *c, *all[64];
   1067 	int n = 0, x = 0, w;
   1068 
   1069 	for (c = clients; c && n < (int)LENGTH(all); c = c->next)
   1070 		if (c->scr == cur)
   1071 			all[n++] = c;
   1072 	while (n-- && nsegs < (int)LENGTH(segs)) {
   1073 		c = all[n];
   1074 		ucut(name, *c->name ? c->name : "window", 20, sizeof name);
   1075 		snprintf(buf, sizeof buf, "[ %s ]", name);
   1076 		w = ulen(buf) * cw;
   1077 		if (x + w > end)
   1078 			break;
   1079 		if (c == sel) {
   1080 			XftDrawRect(bardraw, &col[ColBar], x, 0, w, ch);
   1081 			text(bardraw, ColBg, x, 0, buf);
   1082 		} else
   1083 			text(bardraw, ColBar, x, 0, buf);
   1084 		segs[nsegs].x0 = x;
   1085 		segs[nsegs].x1 = x + w;
   1086 		segs[nsegs].c = c;
   1087 		segs[nsegs++].seg = SegWin;
   1088 		x += w + cw;
   1089 	}
   1090 }
   1091 
   1092 static void
   1093 drawbar(void)
   1094 {
   1095 	char seg[16][64];
   1096 	int kind[16], n = 0, i, j, x, len = 0, pct;
   1097 	time_t t = time(NULL);
   1098 	struct tm *tm = localtime(&t);
   1099 
   1100 	for (j = 0; barorder[j] >= 0 && n < (int)LENGTH(seg) - 4; j++)
   1101 		switch (barorder[j]) {
   1102 		case BarCommands:
   1103 			for (i = 0; i < nbarcmds; i++)
   1104 				if (barout[i][0]) {
   1105 					snprintf(seg[n], sizeof seg[n], "%s", barout[i]);
   1106 					kind[n++] = SegNone;
   1107 				}
   1108 			break;
   1109 		case BarNet:
   1110 			if (shownetwork) {
   1111 				network(seg[n], sizeof seg[n]);
   1112 				kind[n++] = SegNet;
   1113 			}
   1114 			break;
   1115 		case BarVol:
   1116 			if (showvolume && vol >= 0) {
   1117 				snprintf(seg[n], sizeof seg[n], muted ? "vol muted" : "vol %d%%", vol);
   1118 				kind[n++] = SegVol;
   1119 			}
   1120 			break;
   1121 		case BarLight:
   1122 			if (showlight && (pct = light()) >= 0) {
   1123 				snprintf(seg[n], sizeof seg[n], "light %d%%", pct);
   1124 				kind[n++] = SegLight;
   1125 			}
   1126 			break;
   1127 		case BarBattery:
   1128 			if (showbattery && battery(seg[n], sizeof seg[n]))
   1129 				kind[n++] = SegNone;
   1130 			break;
   1131 		case BarDate:
   1132 			if (showdate) {
   1133 				strftime(seg[n], sizeof seg[n], "%a %d %b", tm);
   1134 				kind[n++] = SegNone;
   1135 			}
   1136 			break;
   1137 		case BarClock:
   1138 			if (showclock) {
   1139 				strftime(seg[n], sizeof seg[n], clock24 ? "%H:%M" : "%I:%M %p", tm);
   1140 				kind[n++] = SegNone;
   1141 			}
   1142 			break;
   1143 		case BarTty:
   1144 			snprintf(seg[n], sizeof seg[n], "tty%d", cur + 1);
   1145 			kind[n++] = SegTty;
   1146 			break;
   1147 		}
   1148 
   1149 	for (i = 0; i < n; i++)
   1150 		len += ulen(seg[i]) + 2;
   1151 	XftDrawRect(bardraw, &col[ColBg], 0, 0, sw, ch);
   1152 	x = sw - len * cw;
   1153 	nsegs = 0;
   1154 	for (i = 0; i < n; i++) {
   1155 		text(bardraw, ColBar, x, 0, seg[i]);
   1156 		if (nsegs < (int)LENGTH(segs)) {
   1157 			segs[nsegs].x0 = x;
   1158 			segs[nsegs].x1 = x + ulen(seg[i]) * cw;
   1159 			segs[nsegs].c = NULL;
   1160 			segs[nsegs++].seg = kind[i];
   1161 		}
   1162 		x += (ulen(seg[i]) + 2) * cw;
   1163 	}
   1164 	if (winlist)
   1165 		drawwinlist(sw - len * cw - cw);
   1166 }
   1167 
   1168 static void
   1169 setvolume(const char *how)
   1170 {
   1171 	char cmd[128];
   1172 
   1173 	if (!strcmp(how, "mute"))
   1174 		snprintf(cmd, sizeof cmd, "wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle");
   1175 	else
   1176 		snprintf(cmd, sizeof cmd, "wpctl set-volume -l 1.5 @DEFAULT_AUDIO_SINK@ %s", how);
   1177 	runwait(cmd, NULL, 0);
   1178 	readvolume();
   1179 	drawbar();
   1180 }
   1181 
   1182 /* ---- notifications: ttywm is org.freedesktop.Notifications ---- */
   1183 
   1184 #define NOTIFCOLS 48
   1185 
   1186 /* characters, not bytes */
   1187 static int
   1188 ulen(const char *s)
   1189 {
   1190 	int n = 0;
   1191 
   1192 	for (; *s; s++)
   1193 		n += (*s & 0xc0) != 0x80;
   1194 	return n;
   1195 }
   1196 
   1197 /* the first n characters of s */
   1198 static void
   1199 ucut(char *dst, const char *s, int n, size_t size)
   1200 {
   1201 	size_t i = 0;
   1202 
   1203 	for (; *s && i < size - 1; s++) {
   1204 		if ((*s & 0xc0) != 0x80 && n-- <= 0)
   1205 			break;
   1206 		dst[i++] = *s;
   1207 	}
   1208 	dst[i] = '\0';
   1209 }
   1210 
   1211 /* <b>bold</b> &amp; co. as plain text */
   1212 static void
   1213 plain(char *dst, const char *s, size_t size)
   1214 {
   1215 	static const char *ent[][2] = { { "&amp;", "&" }, { "&lt;", "<" }, { "&gt;", ">" }, { "&quot;", "\"" }, { "&apos;", "'" } };
   1216 	size_t i = 0;
   1217 	unsigned int e;
   1218 
   1219 	while (*s && i < size - 1) {
   1220 		if (*s == '<' && strchr(s, '>')) {
   1221 			s = strchr(s, '>') + 1;
   1222 			continue;
   1223 		}
   1224 		for (e = 0; e < LENGTH(ent); e++)
   1225 			if (!strncmp(s, ent[e][0], strlen(ent[e][0])))
   1226 				break;
   1227 		if (e < LENGTH(ent)) {
   1228 			dst[i++] = ent[e][1][0];
   1229 			s += strlen(ent[e][0]);
   1230 		} else
   1231 			dst[i++] = *s == '\n' || *s == '\t' ? ' ' : *s, s++;
   1232 	}
   1233 	dst[i] = '\0';
   1234 }
   1235 
   1236 static void
   1237 drawnotif(Notif *n)
   1238 {
   1239 	char buf[1024], *p;
   1240 	int cols = n->w / cw, i;
   1241 
   1242 	XftDrawRect(n->draw, &col[ColBg], 0, 0, n->w, n->h);
   1243 	text(n->draw, ColWindow, 0, 0, "┌─[");
   1244 	snprintf(buf, sizeof buf, " %s ", n->app);
   1245 	text(n->draw, ColTitle, 3 * cw, 0, buf);
   1246 	p = buf + sprintf(buf, "]");
   1247 	for (i = ulen(n->app) + 6; i < cols - 1; i++)
   1248 		p += sprintf(p, "─");
   1249 	sprintf(p, "┐");
   1250 	text(n->draw, ColWindow, (ulen(n->app) + 5) * cw, 0, buf);
   1251 	for (i = 0; i < n->nlines; i++) {
   1252 		text(n->draw, ColWindow, 0, (i + 1) * ch, "│");
   1253 		text(n->draw, i ? ColWindow : ColTitle, 2 * cw, (i + 1) * ch, n->line[i]);
   1254 		text(n->draw, ColWindow, (cols - 1) * cw, (i + 1) * ch, "│");
   1255 	}
   1256 	p = buf + sprintf(buf, "└");
   1257 	for (i = 2; i < cols; i++)
   1258 		p += sprintf(p, "─");
   1259 	sprintf(p, "┘");
   1260 	text(n->draw, ColWindow, 0, (n->nlines + 1) * ch, buf);
   1261 }
   1262 
   1263 /* stacked down from the top right corner, newest last */
   1264 static void
   1265 placenotifs(void)
   1266 {
   1267 	Notif *n;
   1268 	int y = 0;
   1269 
   1270 	for (n = notifs; n; n = n->next) {
   1271 		XMoveResizeWindow(dpy, n->win, sw / cw * cw - n->w, y, n->w, n->h);
   1272 		XRaiseWindow(dpy, n->win);
   1273 		drawnotif(n);
   1274 		y += n->h;
   1275 	}
   1276 }
   1277 
   1278 static void
   1279 closenotif(Notif *n, unsigned int why)
   1280 {
   1281 	Notif **pn;
   1282 	DBusMessage *m;
   1283 	dbus_uint32_t id = n->id, reason = why;
   1284 
   1285 	for (pn = &notifs; *pn != n; pn = &(*pn)->next);
   1286 	*pn = n->next;
   1287 	XftDrawDestroy(n->draw);
   1288 	XDestroyWindow(dpy, n->win);
   1289 	free(n);
   1290 	placenotifs();
   1291 	if (bus && (m = dbus_message_new_signal("/org/freedesktop/Notifications",
   1292 	    "org.freedesktop.Notifications", "NotificationClosed"))) {
   1293 		dbus_message_append_args(m, DBUS_TYPE_UINT32, &id, DBUS_TYPE_UINT32, &reason, DBUS_TYPE_INVALID);
   1294 		dbus_connection_send(bus, m, NULL);
   1295 		dbus_message_unref(m);
   1296 	}
   1297 }
   1298 
   1299 static unsigned int
   1300 notify(const char *app, unsigned int replaces, const char *summary, const char *body, int timeout)
   1301 {
   1302 	XSetWindowAttributes wa;
   1303 	Notif *n, **pn;
   1304 	char buf[1024], word[256], *p, *w;
   1305 	int i, len;
   1306 
   1307 	for (n = notifs; n && (!replaces || n->id != replaces); n = n->next);
   1308 	if (!n) {
   1309 		if (!(n = calloc(1, sizeof *n)))
   1310 			return 0;
   1311 		n->id = ++lastid;
   1312 		wa.override_redirect = True;
   1313 		wa.background_pixel = col[ColBg].pixel;
   1314 		wa.event_mask = ExposureMask|ButtonPressMask;
   1315 		n->win = XCreateWindow(dpy, root, 0, 0, 1, 1, 0, CopyFromParent, CopyFromParent, CopyFromParent,
   1316 		                       CWOverrideRedirect|CWBackPixel|CWEventMask, &wa);
   1317 		n->draw = XftDrawCreate(dpy, n->win, DefaultVisual(dpy, DefaultScreen(dpy)),
   1318 		                        DefaultColormap(dpy, DefaultScreen(dpy)));
   1319 		for (pn = &notifs; *pn; pn = &(*pn)->next);
   1320 		*pn = n;
   1321 		XMapRaised(dpy, n->win);
   1322 	}
   1323 	ucut(n->app, *app ? app : "notification", NOTIFCOLS - 10, sizeof n->app);
   1324 	plain(buf, summary, sizeof buf);
   1325 	ucut(n->line[0], buf, NOTIFCOLS - 4, sizeof n->line[0]);
   1326 	n->nlines = 1;
   1327 
   1328 	/* the body, a word at a time, in up to 3 lines under the summary */
   1329 	plain(buf, body, sizeof buf);
   1330 	for (p = buf; (w = strsep(&p, " "));) {
   1331 		if (!*w)
   1332 			continue;
   1333 		ucut(word, w, NOTIFCOLS - 4, sizeof word);
   1334 		i = n->nlines - 1;
   1335 		if (i > 0 && ulen(n->line[i]) + 1 + ulen(word) <= NOTIFCOLS - 4) {
   1336 			len = strlen(n->line[i]);
   1337 			snprintf(n->line[i] + len, sizeof n->line[i] - len, " %s", word);
   1338 		} else if (n->nlines < 4)
   1339 			snprintf(n->line[n->nlines++], sizeof n->line[0], "%s", word);
   1340 		else
   1341 			break;
   1342 	}
   1343 	n->w = 0;
   1344 	for (i = 0; i < n->nlines; i++)
   1345 		n->w = MAX(n->w, ulen(n->line[i]) + 4);
   1346 	n->w = MAX(n->w, ulen(n->app) + 10) * cw;
   1347 	n->h = (n->nlines + 2) * ch;
   1348 	/* -1: the usual 5 seconds. 0: until it's clicked */
   1349 	n->until = timeout == 0 ? 0 : time(NULL) + (timeout < 0 ? 5 : (timeout + 999) / 1000);
   1350 	placenotifs();
   1351 	return n->id;
   1352 }
   1353 
   1354 static void
   1355 expirenotifs(void)
   1356 {
   1357 	Notif *n, *next;
   1358 	time_t now = time(NULL);
   1359 
   1360 	for (n = notifs; n; n = next) {
   1361 		next = n->next;
   1362 		if (n->until && n->until <= now)
   1363 			closenotif(n, 1);
   1364 	}
   1365 }
   1366 
   1367 static Notif *
   1368 wintonotif(Window w)
   1369 {
   1370 	Notif *n;
   1371 
   1372 	for (n = notifs; n && n->win != w; n = n->next);
   1373 	return n;
   1374 }
   1375 
   1376 static void
   1377 arg(DBusMessageIter *it, int type, void *v)
   1378 {
   1379 	if (dbus_message_iter_get_arg_type(it) == type)
   1380 		dbus_message_iter_get_basic(it, v);
   1381 	dbus_message_iter_next(it);
   1382 }
   1383 
   1384 static void
   1385 dbusmessage(DBusMessage *m)
   1386 {
   1387 	static const char *iface = "org.freedesktop.Notifications";
   1388 	static const char *caps[] = { "body" }, **cp = caps;
   1389 	static const char *info[] = { "ttywm", "Chamesle", VERSION, "1.2" };
   1390 	const char *app = "", *icon = "", *summary = "", *body = "";
   1391 	dbus_uint32_t replaces = 0, id;
   1392 	dbus_int32_t timeout = -1;
   1393 	DBusMessageIter it;
   1394 	DBusMessage *r;
   1395 	Notif *n;
   1396 
   1397 	if (dbus_message_get_type(m) != DBUS_MESSAGE_TYPE_METHOD_CALL)
   1398 		return;
   1399 	if (dbus_message_is_method_call(m, iface, "Notify")) {
   1400 		dbus_message_iter_init(m, &it);
   1401 		arg(&it, DBUS_TYPE_STRING, &app);
   1402 		arg(&it, DBUS_TYPE_UINT32, &replaces);
   1403 		arg(&it, DBUS_TYPE_STRING, &icon);
   1404 		arg(&it, DBUS_TYPE_STRING, &summary);
   1405 		arg(&it, DBUS_TYPE_STRING, &body);
   1406 		dbus_message_iter_next(&it);	/* actions: not here */
   1407 		dbus_message_iter_next(&it);	/* hints */
   1408 		arg(&it, DBUS_TYPE_INT32, &timeout);
   1409 		id = notify(app, replaces, summary, body, timeout);
   1410 		r = dbus_message_new_method_return(m);
   1411 		dbus_message_append_args(r, DBUS_TYPE_UINT32, &id, DBUS_TYPE_INVALID);
   1412 	} else if (dbus_message_is_method_call(m, iface, "CloseNotification")) {
   1413 		dbus_message_iter_init(m, &it);
   1414 		id = 0;
   1415 		arg(&it, DBUS_TYPE_UINT32, &id);
   1416 		for (n = notifs; n && n->id != id; n = n->next);
   1417 		if (n)
   1418 			closenotif(n, 3);
   1419 		r = dbus_message_new_method_return(m);
   1420 	} else if (dbus_message_is_method_call(m, iface, "GetCapabilities")) {
   1421 		r = dbus_message_new_method_return(m);
   1422 		dbus_message_append_args(r, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &cp, 1, DBUS_TYPE_INVALID);
   1423 	} else if (dbus_message_is_method_call(m, iface, "GetServerInformation")) {
   1424 		r = dbus_message_new_method_return(m);
   1425 		dbus_message_append_args(r, DBUS_TYPE_STRING, &info[0], DBUS_TYPE_STRING, &info[1],
   1426 		                         DBUS_TYPE_STRING, &info[2], DBUS_TYPE_STRING, &info[3], DBUS_TYPE_INVALID);
   1427 	} else
   1428 		r = dbus_message_new_error(m, DBUS_ERROR_UNKNOWN_METHOD, "ttywm only shows notifications");
   1429 	if (r) {
   1430 		dbus_connection_send(bus, r, NULL);
   1431 		dbus_message_unref(r);
   1432 	}
   1433 }
   1434 
   1435 /* no session bus, or another program shows notifications already (like dunst): then not us */
   1436 static void
   1437 setupbus(void)
   1438 {
   1439 	DBusError err;
   1440 
   1441 	dbus_error_init(&err);
   1442 	if (!(bus = dbus_bus_get(DBUS_BUS_SESSION, &err))) {
   1443 		dbus_error_free(&err);
   1444 		return;
   1445 	}
   1446 	dbus_connection_set_exit_on_disconnect(bus, FALSE);
   1447 	if (dbus_bus_request_name(bus, "org.freedesktop.Notifications", DBUS_NAME_FLAG_DO_NOT_QUEUE, &err)
   1448 	    != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
   1449 		dbus_error_free(&err);
   1450 		bus = NULL;
   1451 	}
   1452 }
   1453 
   1454 static void
   1455 readbus(void)
   1456 {
   1457 	DBusMessage *m;
   1458 
   1459 	if (!bus)
   1460 		return;
   1461 	dbus_connection_read_write(bus, 0);
   1462 	while ((m = dbus_connection_pop_message(bus))) {
   1463 		dbusmessage(m);
   1464 		dbus_message_unref(m);
   1465 	}
   1466 	dbus_connection_flush(bus);
   1467 }
   1468 
   1469 /* ---- windows ---- */
   1470 
   1471 static Client *
   1472 topclient(void)
   1473 {
   1474 	Client *c;
   1475 
   1476 	for (c = clients; c && c->scr != cur; c = c->next);
   1477 	return c;
   1478 }
   1479 
   1480 /* focus(NULL) gives the keyboard to the shell */
   1481 static void
   1482 focus(Client *c)
   1483 {
   1484 	Client *old = sel;
   1485 
   1486 	sel = c;
   1487 	if (old && old != c)
   1488 		drawframe(old);
   1489 	if (old != c)
   1490 		drawbar();
   1491 	if (!c) {
   1492 		XSetInputFocus(dpy, shell[cur] ? shell[cur] : root, RevertToPointerRoot, CurrentTime);
   1493 		return;
   1494 	}
   1495 	XRaiseWindow(dpy, c->frame);
   1496 	if (c->typed >= c->total)
   1497 		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
   1498 	drawframe(c);
   1499 }
   1500 
   1501 static void
   1502 updatetitle(Client *c)
   1503 {
   1504 	XTextProperty tp;
   1505 
   1506 	c->name[0] = '\0';
   1507 	if (!XGetTextProperty(dpy, c->win, &tp, netwmname) || !tp.nitems)
   1508 		if (!XGetTextProperty(dpy, c->win, &tp, XA_WM_NAME) || !tp.nitems)
   1509 			return;
   1510 	strncpy(c->name, (char *)tp.value, sizeof c->name - 1);
   1511 	XFree(tp.value);
   1512 }
   1513 
   1514 static void
   1515 setclientstate(Window w, long state)
   1516 {
   1517 	long data[] = { state, None };
   1518 
   1519 	XChangeProperty(dpy, w, wmstate, wmstate, 32, PropModeReplace, (unsigned char *)data, 2);
   1520 }
   1521 
   1522 /* sizes are whole character cells, like a terminal */
   1523 static void
   1524 resize(Client *c, int w, int h)
   1525 {
   1526 	w = MIN(MAX(w / cw, 10), (sw - c->x) / cw - 2) * cw;
   1527 	h = MIN(MAX(h / ch, 3), (wh - c->y) / ch - 2) * ch;
   1528 	if (w == c->w && h == c->h)
   1529 		return;
   1530 	c->w = w;
   1531 	c->h = h;
   1532 	XResizeWindow(dpy, c->frame, c->w + 2 * cw, c->h + 2 * ch);
   1533 	XResizeWindow(dpy, c->win, c->w, c->h);
   1534 	drawframe(c);
   1535 }
   1536 
   1537 static void
   1538 move(Client *c, int x, int y)
   1539 {
   1540 	if (x == c->x && y == c->y)
   1541 		return;
   1542 	c->x = x;
   1543 	c->y = y;
   1544 	XMoveWindow(dpy, c->frame, x, y);
   1545 }
   1546 
   1547 /* the wallpaper through ttywmbg, or just the colour */
   1548 static void
   1549 setbackground(void)
   1550 {
   1551 	char cmd[2200], path[1100];
   1552 
   1553 	if (!wallpaper[0] || strchr(wallpaper, '\'')) {
   1554 		XSetWindowBackground(dpy, root, col[ColBg].pixel);
   1555 		XClearWindow(dpy, root);
   1556 		return;
   1557 	}
   1558 	if (wallpaper[0] == '~')
   1559 		snprintf(path, sizeof path, "%s%s", getenv("HOME") ? getenv("HOME") : "", wallpaper + 1);
   1560 	else
   1561 		snprintf(path, sizeof path, "%s", wallpaper);
   1562 	snprintf(cmd, sizeof cmd, "exec ttywmbg '%s' %s", path, wallfit);
   1563 	run(cmd);
   1564 }
   1565 
   1566 static void
   1567 spawnshell(int s)
   1568 {
   1569 	char cmd[64];
   1570 
   1571 	if (!shells)
   1572 		return;
   1573 	newshell = s;
   1574 	snprintf(cmd, sizeof cmd, "exec %s -class %s", SHELLCMD, SHELLCLASS);
   1575 	run(cmd);
   1576 }
   1577 
   1578 static void
   1579 manage(Window w, XWindowAttributes *wa)
   1580 {
   1581 	XClassHint hint = { NULL, NULL };
   1582 	Client *c;
   1583 	Rule *rule = NULL;
   1584 	int isshell = 0, i;
   1585 
   1586 	if (XGetClassHint(dpy, w, &hint)) {
   1587 		isshell = hint.res_class && !strcmp(hint.res_class, SHELLCLASS);
   1588 		for (i = 0; i < nrules && !rule; i++)
   1589 			if ((hint.res_class && !strcasecmp(hint.res_class, rules[i].name))
   1590 			|| (hint.res_name && !strcasecmp(hint.res_name, rules[i].name)))
   1591 				rule = &rules[i];
   1592 		XFree(hint.res_class);
   1593 		XFree(hint.res_name);
   1594 	}
   1595 	if (isshell) {
   1596 		int s = newshell >= 0 && !shell[newshell] ? newshell : cur;
   1597 
   1598 		newshell = -1;
   1599 		shell[s] = w;
   1600 		XSelectInput(dpy, w, StructureNotifyMask);
   1601 		XGrabButton(dpy, AnyButton, AnyModifier, w, False, ButtonPressMask,
   1602 		            GrabModeSync, GrabModeAsync, None, None);
   1603 		XSetWindowBorderWidth(dpy, w, 0);
   1604 		XMoveResizeWindow(dpy, w, 0, 0, sw, wh);
   1605 		if (s == cur) {
   1606 			XMapWindow(dpy, w);
   1607 			XLowerWindow(dpy, w);
   1608 			if (!sel)
   1609 				focus(NULL);
   1610 		}
   1611 		return;
   1612 	}
   1613 
   1614 	if (!(c = calloc(1, sizeof(Client))))
   1615 		die("calloc failed");
   1616 	c->win = w;
   1617 	c->scr = rule && rule->scr >= 0 ? rule->scr : cur;
   1618 	c->x = c->y = -1;
   1619 	/* the border types itself in first, the window comes out after */
   1620 	c->typed = typing && !(rule && rule->full) ? 0 : INT32_MAX;
   1621 	c->born = ms();
   1622 	updatetitle(c);
   1623 	c->frame = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, col[ColBg].pixel);
   1624 	/* no background: x would clear it before every redraw, and that's the flash */
   1625 	XSetWindowBackgroundPixmap(dpy, c->frame, None);
   1626 	XSelectInput(dpy, c->frame, SubstructureRedirectMask|SubstructureNotifyMask|ExposureMask|ButtonPressMask);
   1627 	move(c, MAX(0, (sw - wa->width) / 2 - cw) / cw * cw, MAX(0, (wh - wa->height) / 2 - ch) / ch * ch);
   1628 
   1629 	/* the frame is the window's parent, so they move together and clicks on the border come to us.
   1630 	 * the save set gives the window back to root if we crash */
   1631 	XAddToSaveSet(dpy, w);
   1632 	XSetWindowBorderWidth(dpy, w, 0);
   1633 	if (wa->map_state == IsViewable)
   1634 		c->ignoreunmap++;	/* reparenting unmaps it once */
   1635 	XReparentWindow(dpy, w, c->frame, cw, ch);
   1636 	XSelectInput(dpy, w, PropertyChangeMask|StructureNotifyMask);
   1637 	XGrabButton(dpy, AnyButton, AnyModifier, w, False, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None);
   1638 
   1639 	c->next = clients;
   1640 	clients = c;
   1641 	resize(c, wa->width, wa->height);
   1642 	if (c->typed >= c->total)
   1643 		XMapWindow(dpy, w);
   1644 	setclientstate(w, NormalState);
   1645 	if (c->scr != cur)
   1646 		return;
   1647 	XMapWindow(dpy, c->frame);
   1648 	focus(c);
   1649 	if (rule && rule->full)
   1650 		setfullscreen(c, 1);
   1651 }
   1652 
   1653 static void
   1654 unmanage(Client *c, int destroyed)
   1655 {
   1656 	Client **tc;
   1657 
   1658 	for (tc = &clients; *tc != c; tc = &(*tc)->next);
   1659 	*tc = c->next;
   1660 	if (!destroyed) {
   1661 		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
   1662 		XReparentWindow(dpy, c->win, root, c->x + cw, c->y + ch);
   1663 		XRemoveFromSaveSet(dpy, c->win);
   1664 		setclientstate(c->win, WithdrawnState);
   1665 	}
   1666 	if (sel == c) {
   1667 		sel = NULL;
   1668 		focus(topclient());
   1669 	}
   1670 	/* the border types itself away, then the frame goes */
   1671 	if (running && typing && c->scr == cur && !c->isfull && c->typed >= c->total && c->pix) {
   1672 		c->typed = c->total;
   1673 		c->born = ms();
   1674 		c->next = ghosts;
   1675 		ghosts = c;
   1676 		drawframe(c);
   1677 		drawbar();
   1678 		return;
   1679 	}
   1680 	if (c->draw)
   1681 		XftDrawDestroy(c->draw);
   1682 	if (c->pix)
   1683 		XFreePixmap(dpy, c->pix);
   1684 	XDestroyWindow(dpy, c->frame);
   1685 	free(c);
   1686 	drawbar();
   1687 }
   1688 
   1689 /* ICCCM: ask with WM_DELETE_WINDOW if the window understands it, so it can save its work.
   1690  * only kill it if it doesn't */
   1691 static void
   1692 closeclient(Client *c)
   1693 {
   1694 	Atom *p;
   1695 	int n, ok = 0;
   1696 	XEvent ev;
   1697 
   1698 	if (XGetWMProtocols(dpy, c->win, &p, &n)) {
   1699 		while (!ok && n--)
   1700 			ok = p[n] == wmdelete;
   1701 		XFree(p);
   1702 	}
   1703 	if (!ok) {
   1704 		XKillClient(dpy, c->win);
   1705 		return;
   1706 	}
   1707 	memset(&ev, 0, sizeof ev);
   1708 	ev.type = ClientMessage;
   1709 	ev.xclient.window = c->win;
   1710 	ev.xclient.message_type = wmprotocols;
   1711 	ev.xclient.format = 32;
   1712 	ev.xclient.data.l[0] = wmdelete;
   1713 	ev.xclient.data.l[1] = CurrentTime;
   1714 	XSendEvent(dpy, c->win, False, NoEventMask, &ev);
   1715 }
   1716 
   1717 static void
   1718 setfullscreen(Client *c, int full)
   1719 {
   1720 	if (full == c->isfull)
   1721 		return;
   1722 	if (c->typed < c->total) {
   1723 		c->typed = INT32_MAX;
   1724 		XMapWindow(dpy, c->win);
   1725 	}
   1726 	c->isfull = full;
   1727 	if (full) {
   1728 		c->oldx = c->x; c->oldy = c->y; c->oldw = c->w; c->oldh = c->h;
   1729 		XMoveResizeWindow(dpy, c->frame, 0, 0, sw, sh);
   1730 		XMoveResizeWindow(dpy, c->win, 0, 0, sw, sh);
   1731 		XChangeProperty(dpy, c->win, netwmstate, XA_ATOM, 32, PropModeReplace,
   1732 		                (unsigned char *)&netfullscreen, 1);
   1733 	} else {
   1734 		XMoveWindow(dpy, c->win, cw, ch);
   1735 		c->x = c->y = -1;
   1736 		c->w = c->h = 0;
   1737 		move(c, c->oldx, c->oldy);
   1738 		resize(c, c->oldw, c->oldh);
   1739 		XChangeProperty(dpy, c->win, netwmstate, XA_ATOM, 32, PropModeReplace, NULL, 0);
   1740 	}
   1741 	XRaiseWindow(dpy, c->frame);
   1742 }
   1743 
   1744 /* super+arrows: half the screen, all of it, or back where it was */
   1745 static void
   1746 snap(Client *c, int how)
   1747 {
   1748 	int cols = sw / cw, rows = wh / ch, half = cols / 2;
   1749 
   1750 	if (c->isfull)
   1751 		return;
   1752 	if (how == ActRestore) {
   1753 		if (c->snapped) {
   1754 			move(c, c->sx, c->sy);
   1755 			resize(c, c->sw, c->sh);
   1756 		}
   1757 		c->snapped = 0;
   1758 		return;
   1759 	}
   1760 	if (!c->snapped) {
   1761 		c->sx = c->x; c->sy = c->y; c->sw = c->w; c->sh = c->h;
   1762 		c->snapped = 1;
   1763 	}
   1764 	if (how == ActLeft) {
   1765 		move(c, 0, 0);
   1766 		resize(c, (half - 2) * cw, (rows - 2) * ch);
   1767 	} else if (how == ActRight) {
   1768 		move(c, half * cw, 0);
   1769 		resize(c, (cols - half - 2) * cw, (rows - 2) * ch);
   1770 	} else {
   1771 		move(c, 0, 0);
   1772 		resize(c, (cols - 2) * cw, (rows - 2) * ch);
   1773 	}
   1774 }
   1775 
   1776 static void
   1777 mousedrag(Client *c, int resizing)
   1778 {
   1779 	XEvent ev;
   1780 	Window dummy;
   1781 	int px, py, di, ox = c->x, oy = c->y, ow = c->w, oh = c->h;
   1782 	unsigned int dui;
   1783 	Time last = 0;
   1784 
   1785 	if (c->isfull || XGrabPointer(dpy, root, False, ButtonReleaseMask|PointerMotionMask,
   1786 	    GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess)
   1787 		return;
   1788 	XQueryPointer(dpy, root, &dummy, &dummy, &px, &py, &di, &di, &dui);
   1789 	do {
   1790 		XMaskEvent(dpy, ButtonReleaseMask|PointerMotionMask|ExposureMask|SubstructureRedirectMask, &ev);
   1791 		/* what it uncovers gets drawn again while it moves, not when it's let go.
   1792 		 * anything that isn't the mouse has no place to move to: NoExpose from our own drawing would
   1793 		 * otherwise send the window off to wherever its garbage x and y point */
   1794 		if (ev.type != MotionNotify && ev.type != ButtonRelease) {
   1795 			if (ev.type == Expose || ev.type == ConfigureRequest || ev.type == MapRequest)
   1796 				handler[ev.type](&ev);
   1797 			continue;
   1798 		}
   1799 		/* only the newest position, no more than 60 times a second, and always where it was let go */
   1800 		while (ev.type == MotionNotify && XCheckTypedEvent(dpy, MotionNotify, &ev));
   1801 		if (ev.type == MotionNotify && ev.xmotion.time - last < 16)
   1802 			continue;
   1803 		last = ev.xmotion.time;
   1804 		if (resizing)
   1805 			resize(c, ow + ev.xmotion.x_root - px, oh + ev.xmotion.y_root - py);
   1806 		else
   1807 			move(c, ox + (ev.xmotion.x_root - px) / cw * cw, oy + (ev.xmotion.y_root - py) / ch * ch);
   1808 	} while (ev.type != ButtonRelease);
   1809 	XUngrabPointer(dpy, CurrentTime);
   1810 }
   1811 
   1812 /* ---- the lock screen: a login prompt, checked by pam like a real one ---- */
   1813 
   1814 static int
   1815 conv(int n, const struct pam_message **msg, struct pam_response **resp, void *pw)
   1816 {
   1817 	int i;
   1818 
   1819 	if (!(*resp = calloc(n, sizeof **resp)))
   1820 		return PAM_BUF_ERR;
   1821 	for (i = 0; i < n; i++)
   1822 		if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF || msg[i]->msg_style == PAM_PROMPT_ECHO_ON)
   1823 			(*resp)[i].resp = strdup(pw);
   1824 	return PAM_SUCCESS;
   1825 }
   1826 
   1827 static int
   1828 checkpassword(const char *user, const char *pw)
   1829 {
   1830 	struct pam_conv pc = { conv, (void *)pw };
   1831 	pam_handle_t *ph;
   1832 	int r;
   1833 
   1834 	if (pam_start("system-local-login", user, &pc, &ph) != PAM_SUCCESS)
   1835 		return 0;
   1836 	r = pam_authenticate(ph, 0);
   1837 	pam_end(ph, r);
   1838 	return r == PAM_SUCCESS;
   1839 }
   1840 
   1841 static void
   1842 lock(void)
   1843 {
   1844 	XSetWindowAttributes wa;
   1845 	XftDraw *d;
   1846 	XEvent ev;
   1847 	KeySym sym;
   1848 	char host[64] = "", line[256], buf[8], pw[256] = "", *user = getenv("USER");
   1849 	int n = 0, wrong = 0, i, len;
   1850 	Window w;
   1851 
   1852 	gethostname(host, sizeof host);
   1853 	wa.override_redirect = True;
   1854 	wa.background_pixel = col[ColBg].pixel;
   1855 	wa.event_mask = ExposureMask|KeyPressMask;
   1856 	w = XCreateWindow(dpy, root, 0, 0, sw, sh, 0, CopyFromParent, CopyFromParent, CopyFromParent,
   1857 	                         CWOverrideRedirect|CWBackPixel|CWEventMask, &wa);
   1858 	d = XftDrawCreate(dpy, w, DefaultVisual(dpy, DefaultScreen(dpy)), DefaultColormap(dpy, DefaultScreen(dpy)));
   1859 	XMapRaised(dpy, w);
   1860 	/* the keyboard can be busy for a moment, like when the key that locked is still down */
   1861 	for (i = 0; i < 100; i++) {
   1862 		if (XGrabKeyboard(dpy, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
   1863 			break;
   1864 		usleep(10000);
   1865 	}
   1866 	XGrabPointer(dpy, w, False, 0, GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
   1867 	for (;;) {
   1868 		XftDrawRect(d, &col[ColBg], 0, 0, sw, sh);
   1869 		snprintf(line, sizeof line, "Chamesle Linux (tty%d)", cur + 1);
   1870 		text(d, ColBar, 0, 0, line);
   1871 		snprintf(line, sizeof line, "%s login: %s", host, user ? user : "");
   1872 		text(d, ColBar, 0, 2 * ch, line);
   1873 		text(d, ColBar, 0, 3 * ch, "Password: ");
   1874 		if (wrong)
   1875 			text(d, ColBar, 0, 5 * ch, "Login incorrect");
   1876 		XRaiseWindow(dpy, w);
   1877 		XNextEvent(dpy, &ev);
   1878 		if (ev.type == Expose || ev.xany.window != w) {
   1879 			/* the rest of the world goes on underneath */
   1880 			if (ev.xany.window != w && handler[ev.type] && ev.type != KeyPress && ev.type != ButtonPress)
   1881 				handler[ev.type](&ev);
   1882 			continue;
   1883 		}
   1884 		if (ev.type != KeyPress)
   1885 			continue;
   1886 		len = XLookupString(&ev.xkey, buf, sizeof buf, &sym, NULL);
   1887 		if (sym == XK_Return || sym == XK_KP_Enter) {
   1888 			pw[n] = '\0';
   1889 			if (user && checkpassword(user, pw))
   1890 				break;
   1891 			wrong = 1;
   1892 			n = 0;
   1893 		} else if (sym == XK_BackSpace && n)
   1894 			n--;
   1895 		else if (sym == XK_Escape)
   1896 			n = 0;
   1897 		else if (len > 0 && !iscntrl((unsigned char)buf[0]) && n + len < (int)sizeof pw - 1) {
   1898 			memcpy(pw + n, buf, len);
   1899 			n += len;
   1900 		}
   1901 	}
   1902 	memset(pw, 0, sizeof pw);
   1903 	XUngrabPointer(dpy, CurrentTime);
   1904 	XUngrabKeyboard(dpy, CurrentTime);
   1905 	XftDrawDestroy(d);
   1906 	XDestroyWindow(dpy, w);
   1907 	focus(sel);
   1908 }
   1909 
   1910 /* ---- what keys and clicks do ---- */
   1911 
   1912 static void
   1913 view(int n)
   1914 {
   1915 	Client *c;
   1916 
   1917 	if (n == cur)
   1918 		return;
   1919 	for (c = clients; c; c = c->next)
   1920 		if (c->scr == cur)
   1921 			XUnmapWindow(dpy, c->frame);
   1922 	if (shell[cur])
   1923 		XUnmapWindow(dpy, shell[cur]);
   1924 	cur = n;
   1925 	sel = NULL;
   1926 	if (shell[cur])
   1927 		XMapWindow(dpy, shell[cur]);
   1928 	else
   1929 		spawnshell(cur);
   1930 	for (c = clients; c; c = c->next)
   1931 		if (c->scr == cur)
   1932 			XMapWindow(dpy, c->frame);
   1933 	if (shell[cur])
   1934 		XLowerWindow(dpy, shell[cur]);
   1935 	drawbar();
   1936 	focus(topclient());
   1937 }
   1938 
   1939 static void
   1940 sendto(int n)
   1941 {
   1942 	if (!sel || n == cur)
   1943 		return;
   1944 	sel->scr = n;
   1945 	XUnmapWindow(dpy, sel->frame);
   1946 	sel = NULL;
   1947 	focus(topclient());
   1948 }
   1949 
   1950 static void
   1951 focusnext(void)
   1952 {
   1953 	Client *c = sel ? sel->next : clients;
   1954 
   1955 	for (; c && c->scr != cur; c = c->next);
   1956 	focus(c);
   1957 }
   1958 
   1959 static void
   1960 doaction(Key *k)
   1961 {
   1962 	switch (k->act) {
   1963 	case ActRun:      run(k->cmd); break;
   1964 	case ActTerminal: run(terminal); break;
   1965 	case ActMenu:     runmenu(); break;
   1966 	case ActClose:    if (sel) closeclient(sel); break;
   1967 	case ActNext:     focusnext(); break;
   1968 	case ActFull:     if (sel) setfullscreen(sel, !sel->isfull); break;
   1969 	case ActQuit:     running = 0; break;
   1970 	case ActRestart:  restarting = 1; running = 0; break;
   1971 	case ActView:     view(k->n); break;
   1972 	case ActSend:     sendto(k->n); break;
   1973 	case ActVolUp:    setvolume("5%+"); break;
   1974 	case ActVolDown:  setvolume("5%-"); break;
   1975 	case ActMute:     setvolume("mute"); break;
   1976 	case ActLightUp:  setlight(5); drawbar(); break;
   1977 	case ActLightDown: setlight(-5); drawbar(); break;
   1978 	case ActLeft: case ActRight: case ActMax: case ActRestore:
   1979 		if (sel)
   1980 			snap(sel, k->act);
   1981 		break;
   1982 	case ActLock:     lock(); break;
   1983 	}
   1984 }
   1985 
   1986 static void
   1987 barclick(XButtonPressedEvent *ev)
   1988 {
   1989 	char cmd[512];
   1990 	int i;
   1991 
   1992 	for (i = 0; i < nsegs; i++) {
   1993 		if (ev->x < segs[i].x0 || ev->x >= segs[i].x1)
   1994 			continue;
   1995 		if (segs[i].seg == SegVol) {
   1996 			if (ev->button == Button4)
   1997 				setvolume("5%+");
   1998 			else if (ev->button == Button5)
   1999 				setvolume("5%-");
   2000 			else if (ev->button == Button1)
   2001 				setvolume("mute");
   2002 		} else if (segs[i].seg == SegLight && (ev->button == Button4 || ev->button == Button5)) {
   2003 			setlight(ev->button == Button4 ? 5 : -5);
   2004 			drawbar();
   2005 		} else if (segs[i].seg == SegNet && ev->button == Button1) {
   2006 			snprintf(cmd, sizeof cmd, "exec %s -T network -e nmtui", SHELLCMD);
   2007 			run(cmd);
   2008 		} else if (segs[i].seg == SegTty) {
   2009 			/* scroll or click through the ttys */
   2010 			if (ev->button == Button4)
   2011 				view((cur + NSCR - 1) % NSCR);
   2012 			else if (ev->button == Button1 || ev->button == Button5)
   2013 				view((cur + 1) % NSCR);
   2014 		} else if (segs[i].seg == SegWin) {
   2015 			if (ev->button == Button1)
   2016 				focus(segs[i].c);
   2017 			else if (ev->button == Button2)
   2018 				closeclient(segs[i].c);
   2019 		}
   2020 		return;
   2021 	}
   2022 }
   2023 
   2024 /* ---- events ---- */
   2025 
   2026 static void
   2027 buttonpress(XEvent *e)
   2028 {
   2029 	XButtonPressedEvent *ev = &e->xbutton;
   2030 	Client *c;
   2031 	Notif *n;
   2032 	int cols;
   2033 
   2034 	if (ev->window == bar) {
   2035 		barclick(ev);
   2036 		return;
   2037 	}
   2038 	if ((n = wintonotif(ev->window))) {
   2039 		closenotif(n, 2);
   2040 		return;
   2041 	}
   2042 	if (!(c = wintoclient(ev->window))) {
   2043 		if (shellof(ev->window) >= 0 && sel)
   2044 			focus(NULL);
   2045 		XAllowEvents(dpy, ReplayPointer, CurrentTime);
   2046 		return;
   2047 	}
   2048 	focus(c);
   2049 	if (ev->window == c->win) {
   2050 		if (CLEANMASK(ev->state) == Mod4Mask && (ev->button == Button1 || ev->button == Button3)) {
   2051 			XAllowEvents(dpy, AsyncPointer, CurrentTime);
   2052 			mousedrag(c, ev->button == Button3);
   2053 		} else
   2054 			XAllowEvents(dpy, ReplayPointer, CurrentTime);
   2055 		return;
   2056 	}
   2057 	cols = c->w / cw + 2;
   2058 	if (ev->y < ch && ev->x >= (cols - 4) * cw)
   2059 		closeclient(c);
   2060 	else if (ev->y < ch)
   2061 		mousedrag(c, 0);
   2062 	else if (ev->y >= c->h + ch && ev->x >= (cols - 2) * cw)
   2063 		mousedrag(c, 1);
   2064 }
   2065 
   2066 static void
   2067 clientmessage(XEvent *e)
   2068 {
   2069 	XClientMessageEvent *cme = &e->xclient;
   2070 	Client *c = wintoclient(cme->window);
   2071 
   2072 	if (c && cme->message_type == netwmstate
   2073 	&& ((Atom)cme->data.l[1] == netfullscreen || (Atom)cme->data.l[2] == netfullscreen))
   2074 		setfullscreen(c, cme->data.l[0] == 1 || (cme->data.l[0] == 2 && !c->isfull));
   2075 }
   2076 
   2077 static void
   2078 configurerequest(XEvent *e)
   2079 {
   2080 	XConfigureRequestEvent *ev = &e->xconfigurerequest;
   2081 	XWindowChanges wc;
   2082 	Client *c;
   2083 
   2084 	if (shellof(ev->window) >= 0)
   2085 		return;
   2086 	if ((c = wintoclient(ev->window))) {
   2087 		if (!c->isfull)
   2088 			resize(c, ev->value_mask & CWWidth ? ev->width : c->w,
   2089 			          ev->value_mask & CWHeight ? ev->height : c->h);
   2090 		return;
   2091 	}
   2092 	wc.x = ev->x;
   2093 	wc.y = ev->y;
   2094 	wc.width = ev->width;
   2095 	wc.height = ev->height;
   2096 	wc.border_width = ev->border_width;
   2097 	wc.sibling = ev->above;
   2098 	wc.stack_mode = ev->detail;
   2099 	XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
   2100 }
   2101 
   2102 static void
   2103 destroynotify(XEvent *e)
   2104 {
   2105 	Window w = e->xdestroywindow.window;
   2106 	Client *c;
   2107 	int s;
   2108 
   2109 	if ((c = wintoclient(w)) && c->win == w)
   2110 		unmanage(c, 1);
   2111 	else if ((s = shellof(w)) >= 0) {
   2112 		/* respawn, like a getty */
   2113 		shell[s] = 0;
   2114 		if (s == cur && running)
   2115 			spawnshell(s);
   2116 	}
   2117 }
   2118 
   2119 static void
   2120 expose(XEvent *e)
   2121 {
   2122 	Client *c;
   2123 
   2124 	if (e->xexpose.count)
   2125 		return;
   2126 	if (e->xexpose.window == bar)
   2127 		drawbar();
   2128 	else if (wintonotif(e->xexpose.window))
   2129 		drawnotif(wintonotif(e->xexpose.window));
   2130 	else if ((c = wintoclient(e->xexpose.window)) && c->frame == e->xexpose.window) {
   2131 		if (c->pix)
   2132 			showframe(c);
   2133 		else
   2134 			drawframe(c);
   2135 	}
   2136 }
   2137 
   2138 static void
   2139 keypress(XEvent *e)
   2140 {
   2141 	KeySym keysym = XkbKeycodeToKeysym(dpy, (KeyCode)e->xkey.keycode, 0, 0);
   2142 	int i;
   2143 
   2144 	for (i = 0; i < nkeys; i++)
   2145 		if (keysym == keys[i].keysym && CLEANMASK(keys[i].mod) == CLEANMASK(e->xkey.state))
   2146 			doaction(&keys[i]);
   2147 }
   2148 
   2149 static void
   2150 maprequest(XEvent *e)
   2151 {
   2152 	XWindowAttributes wa;
   2153 	Window w = e->xmaprequest.window;
   2154 
   2155 	if (XGetWindowAttributes(dpy, w, &wa) && !wa.override_redirect && !wintoclient(w) && shellof(w) < 0)
   2156 		manage(w, &wa);
   2157 }
   2158 
   2159 static void
   2160 propertynotify(XEvent *e)
   2161 {
   2162 	Client *c;
   2163 
   2164 	if ((c = wintoclient(e->xproperty.window))
   2165 	&& (e->xproperty.atom == XA_WM_NAME || e->xproperty.atom == netwmname)) {
   2166 		updatetitle(c);
   2167 		drawframe(c);
   2168 		drawbar();
   2169 	}
   2170 }
   2171 
   2172 static void
   2173 unmapnotify(XEvent *e)
   2174 {
   2175 	Client *c;
   2176 
   2177 	if (!(c = wintoclient(e->xunmap.window)) || c->win != e->xunmap.window)
   2178 		return;
   2179 	if (c->ignoreunmap)
   2180 		c->ignoreunmap--;
   2181 	else
   2182 		unmanage(c, 0);
   2183 }
   2184 
   2185 static void (*handler[LASTEvent])(XEvent *) = {
   2186 	[ButtonPress] = buttonpress,
   2187 	[ClientMessage] = clientmessage,
   2188 	[ConfigureRequest] = configurerequest,
   2189 	[DestroyNotify] = destroynotify,
   2190 	[Expose] = expose,
   2191 	[KeyPress] = keypress,
   2192 	[MapRequest] = maprequest,
   2193 	[PropertyNotify] = propertynotify,
   2194 	[UnmapNotify] = unmapnotify
   2195 };
   2196 
   2197 /* a new ttywm without logging out: the windows go back to root, where they are is written down,
   2198  * and the new binary picks them up again. x keeps them alive in between */
   2199 static void
   2200 restart(char **argv)
   2201 {
   2202 	char buf[16384], *p = buf, out[64], cmd[4200];
   2203 	Client *c, *all[256];
   2204 	int i, n = 0;
   2205 
   2206 	/* a broken binary would end the session: it has to answer first */
   2207 	snprintf(cmd, sizeof cmd, "'%s' -v 2>&1", exepath);
   2208 	runwait(cmd, out, sizeof out);
   2209 	if (!strstr(out, "ttywm-")) {
   2210 		fprintf(stderr, "ttywm: %s doesn't run, staying\n", exepath);
   2211 		return;
   2212 	}
   2213 	p += snprintf(p, sizeof buf, "%d", cur);
   2214 	for (i = 0; i < NSCR; i++)
   2215 		if (shell[i] && p < buf + sizeof buf - 64)
   2216 			p += sprintf(p, " s %d %lu", i, shell[i]);
   2217 	/* oldest first, so they stack the same way again */
   2218 	for (c = clients; c && n < (int)LENGTH(all); c = c->next)
   2219 		all[n++] = c;
   2220 	while (n--) {
   2221 		c = all[n];
   2222 		if (p >= buf + sizeof buf - 128)
   2223 			break;
   2224 		if (c->isfull)
   2225 			p += sprintf(p, " c %lu %d %d %d %d %d 1", c->win, c->scr, c->oldx, c->oldy, c->oldw, c->oldh);
   2226 		else
   2227 			p += sprintf(p, " c %lu %d %d %d %d %d 0", c->win, c->scr, c->x, c->y, c->w, c->h);
   2228 		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
   2229 		XReparentWindow(dpy, c->win, root, c->x + cw, c->y + ch);
   2230 		if (c->scr != cur)
   2231 			XUnmapWindow(dpy, c->win);
   2232 	}
   2233 	setenv("TTYWM_STATE", buf, 1);
   2234 	XSync(dpy, False);
   2235 	XCloseDisplay(dpy);
   2236 	execv(exepath, argv);
   2237 	die("cannot run the new ttywm");
   2238 }
   2239 
   2240 /* after a restart: the shells and windows from before, where they were */
   2241 static int
   2242 adopt(void)
   2243 {
   2244 	char *st = getenv("TTYWM_STATE"), *t;
   2245 	Window w;
   2246 	XWindowAttributes wa;
   2247 	Client *c;
   2248 	int s, scr, x, y, ww, wh2, full, was = typing;
   2249 
   2250 	if (!st || !*st)
   2251 		return 0;
   2252 	st = strdup(st);
   2253 	unsetenv("TTYWM_STATE");
   2254 	typing = 0;
   2255 	cur = atoi(strtok(st, " "));
   2256 	while ((t = strtok(NULL, " "))) {
   2257 		if (!strcmp(t, "s")) {
   2258 			s = atoi(strtok(NULL, " "));
   2259 			w = strtoul(strtok(NULL, " "), NULL, 10);
   2260 			if (s < 0 || s >= NSCR || !XGetWindowAttributes(dpy, w, &wa))
   2261 				continue;
   2262 			newshell = s;
   2263 			manage(w, &wa);
   2264 			if (s != cur)
   2265 				XUnmapWindow(dpy, w);
   2266 		} else if (!strcmp(t, "c")) {
   2267 			w = strtoul(strtok(NULL, " "), NULL, 10);
   2268 			scr = atoi(strtok(NULL, " "));
   2269 			x = atoi(strtok(NULL, " "));
   2270 			y = atoi(strtok(NULL, " "));
   2271 			ww = atoi(strtok(NULL, " "));
   2272 			wh2 = atoi(strtok(NULL, " "));
   2273 			full = atoi(strtok(NULL, " "));
   2274 			if (!XGetWindowAttributes(dpy, w, &wa) || !(manage(w, &wa), c = wintoclient(w)))
   2275 				continue;
   2276 			if (c->scr != scr) {
   2277 				c->scr = scr;
   2278 				if (scr == cur)
   2279 					XMapWindow(dpy, c->frame);
   2280 				else
   2281 					XUnmapWindow(dpy, c->frame);
   2282 			}
   2283 			move(c, x, y);
   2284 			resize(c, ww, wh2);
   2285 			if (full)
   2286 				setfullscreen(c, 1);
   2287 		}
   2288 	}
   2289 	free(st);
   2290 	typing = was;
   2291 	sel = NULL;
   2292 	focus(topclient());
   2293 	return shell[cur] != 0;
   2294 }
   2295 
   2296 /* once a second: the clock, the battery, and the settings file if it changed */
   2297 static void
   2298 tick(void)
   2299 {
   2300 	static time_t last, lastvol;
   2301 	time_t now = time(NULL);
   2302 	struct stat st;
   2303 	Client *c;
   2304 	int i;
   2305 
   2306 	if (now == last)
   2307 		return;
   2308 	expirenotifs();
   2309 	if (stat(cfgpath, &st) == 0 && st.st_mtime != cfgmtime) {
   2310 		loadconfig(0);
   2311 		grabkeys();
   2312 		loadcolours();
   2313 		setbackground();
   2314 		/* the shells, turned on or off */
   2315 		for (i = 0; i < NSCR; i++)
   2316 			if (shell[i] && !shells)
   2317 				XKillClient(dpy, shell[i]);
   2318 		if (shells && !shell[cur])
   2319 			spawnshell(cur);
   2320 		for (c = clients; c; c = c->next)
   2321 			drawframe(c);
   2322 		runbarcmds();
   2323 		last = 0;
   2324 	}
   2325 	/* apk put a new ttywm there: swap to it */
   2326 	if (exepath[0] && stat(exepath, &st) == 0 && (st.st_ino != exest.st_ino || st.st_mtime != exest.st_mtime)) {
   2327 		exest = st;
   2328 		restarting = 1;
   2329 		running = 0;
   2330 	}
   2331 	if (now - lastvol >= 10) {
   2332 		readvolume();
   2333 		lastvol = now;
   2334 	}
   2335 	if (now / 5 != last / 5) {
   2336 		runbarcmds();
   2337 		drawbar();
   2338 	}
   2339 	last = now;
   2340 }
   2341 
   2342 static void
   2343 setup(void)
   2344 {
   2345 	XSetWindowAttributes wa;
   2346 	int screen = DefaultScreen(dpy);
   2347 	char font[128], *home, *xdg;
   2348 
   2349 	signal(SIGCHLD, SIG_IGN);	/* no zombies */
   2350 	sw = DisplayWidth(dpy, screen);
   2351 	sh = DisplayHeight(dpy, screen);
   2352 	root = RootWindow(dpy, screen);
   2353 
   2354 	if ((xdg = getenv("XDG_CONFIG_HOME")) && *xdg)
   2355 		snprintf(cfgpath, sizeof cfgpath, "%s", xdg);
   2356 	else
   2357 		snprintf(cfgpath, sizeof cfgpath, "%s/.config", (home = getenv("HOME")) ? home : ".");
   2358 	mkdir(cfgpath, 0755);
   2359 	strncat(cfgpath, "/ttywm", sizeof cfgpath - strlen(cfgpath) - 1);
   2360 	mkdir(cfgpath, 0755);
   2361 	strncat(cfgpath, "/config", sizeof cfgpath - strlen(cfgpath) - 1);
   2362 	loadconfig(1);
   2363 
   2364 	setenv("TTYWM_SIZE", big ? "32" : "16", 1);
   2365 	snprintf(font, sizeof font, "VGA:pixelsize=%d:antialias=false:hinting=false", big ? 32 : 16);
   2366 	if (!(xfont = XftFontOpenName(dpy, screen, font)))
   2367 		die("cannot load font");
   2368 	cw = xfont->max_advance_width;
   2369 	ch = xfont->ascent + xfont->descent;
   2370 	wh = sh - ch;	/* the last line is the bottom line */
   2371 	loadcolours();
   2372 
   2373 	wmprotocols = XInternAtom(dpy, "WM_PROTOCOLS", False);
   2374 	wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
   2375 	wmstate = XInternAtom(dpy, "WM_STATE", False);
   2376 	netwmname = XInternAtom(dpy, "_NET_WM_NAME", False);
   2377 	netwmstate = XInternAtom(dpy, "_NET_WM_STATE", False);
   2378 	netfullscreen = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
   2379 	utf8string = XInternAtom(dpy, "UTF8_STRING", False);
   2380 	netwmcheck = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
   2381 
   2382 	/* EWMH check window, so programs can tell which wm is running */
   2383 	wmcheck = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
   2384 	XChangeProperty(dpy, wmcheck, netwmcheck, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmcheck, 1);
   2385 	XChangeProperty(dpy, wmcheck, netwmname, utf8string, 8, PropModeReplace, (unsigned char *)"ttywm", 5);
   2386 	XChangeProperty(dpy, root, netwmcheck, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmcheck, 1);
   2387 
   2388 	wa.override_redirect = True;
   2389 	wa.background_pixel = col[ColBg].pixel;
   2390 	wa.event_mask = ExposureMask|ButtonPressMask;
   2391 	bar = XCreateWindow(dpy, root, 0, wh, sw, ch, 0, CopyFromParent, CopyFromParent,
   2392 	                    CopyFromParent, CWOverrideRedirect|CWBackPixel|CWEventMask, &wa);
   2393 	bardraw = XftDrawCreate(dpy, bar, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen));
   2394 	XMapWindow(dpy, bar);
   2395 
   2396 	setbackground();
   2397 	/* copying frames onto the screen needn't tell us when there was nothing to copy */
   2398 	XSetGraphicsExposures(dpy, DefaultGC(dpy, screen), False);
   2399 	XDefineCursor(dpy, root, XCreateFontCursor(dpy, XC_left_ptr));
   2400 	XSelectInput(dpy, root, SubstructureRedirectMask|SubstructureNotifyMask);
   2401 	grabkeys();
   2402 	readvolume();
   2403 	findbacklight();
   2404 	setupbus();
   2405 }
   2406 
   2407 int
   2408 main(int argc, char *argv[])
   2409 {
   2410 	XEvent ev;
   2411 	fd_set fds;
   2412 	struct timeval tv;
   2413 	int fd, bfd = -1, busy = 0;
   2414 
   2415 	if (argc == 2 && !strcmp("-v", argv[1]))
   2416 		die("ttywm-" VERSION);
   2417 	else if (argc != 1)
   2418 		die("usage: ttywm [-v]");
   2419 	setlocale(LC_CTYPE, "");
   2420 	/* no shell means a black screen you can't leave: better to go back to the login screen */
   2421 	if (!inpath(SHELLCMD))
   2422 		die("cannot find " SHELLCMD);
   2423 	if (!(dpy = XOpenDisplay(NULL)))
   2424 		die("cannot open display");
   2425 
   2426 	/* only one client can select SubstructureRedirect on root */
   2427 	XSetErrorHandler(xerrorstart);
   2428 	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
   2429 	XSync(dpy, False);
   2430 	XSetErrorHandler(xerror);
   2431 
   2432 	/* the binary, to notice when it's updated */
   2433 	if ((fd = readlink("/proc/self/exe", exepath, sizeof exepath - 1)) > 0) {
   2434 		exepath[fd] = '\0';
   2435 		if (stat(exepath, &exest) < 0)
   2436 			exepath[0] = '\0';
   2437 	}
   2438 	setup();
   2439 	if (!adopt())
   2440 		spawnshell(cur);
   2441 	drawbar();
   2442 
   2443 	/* events, notifications, and a tick every second for the bottom line */
   2444 	fd = ConnectionNumber(dpy);
   2445 	if (bus)
   2446 		dbus_connection_get_unix_fd(bus, &bfd);
   2447 loop:
   2448 	while (running) {
   2449 		if (!XPending(dpy)) {
   2450 			FD_ZERO(&fds);
   2451 			FD_SET(fd, &fds);
   2452 			if (bfd >= 0)
   2453 				FD_SET(bfd, &fds);
   2454 			/* a border typing itself in wakes us every frame, else once a second */
   2455 			tv.tv_sec = busy ? 0 : 1;
   2456 			tv.tv_usec = busy ? 16000 : 0;
   2457 			if (select(MAX(fd, bfd) + 1, &fds, NULL, NULL, &tv) < 0 && errno != EINTR)
   2458 				break;
   2459 		}
   2460 		readbus();
   2461 		while (running && XPending(dpy)) {
   2462 			XNextEvent(dpy, &ev);
   2463 			if (handler[ev.type])
   2464 				handler[ev.type](&ev);
   2465 		}
   2466 		busy = animate();
   2467 		XFlush(dpy);
   2468 		tick();
   2469 	}
   2470 
   2471 	if (restarting) {
   2472 		restart(argv);
   2473 		/* it didn't: carry on with this one */
   2474 		running = 1;
   2475 		restarting = 0;
   2476 		goto loop;
   2477 	}
   2478 	while (clients)
   2479 		unmanage(clients, 0);
   2480 	XCloseDisplay(dpy);
   2481 	return EXIT_SUCCESS;
   2482 }