chamesle

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

torrent.c (88035B)


      1 /* torrent - ttywm on wayland: the same frames, bottom line and settings, without the tty behind */
      2 #include <ctype.h>
      3 #include <dirent.h>
      4 #include <errno.h>
      5 #include <locale.h>
      6 #include <signal.h>
      7 #include <stdbool.h>
      8 #include <stdint.h>
      9 #include <stdio.h>
     10 #include <stdlib.h>
     11 #include <string.h>
     12 #include <strings.h>
     13 #include <time.h>
     14 #include <unistd.h>
     15 #include <sys/stat.h>
     16 #include <sys/wait.h>
     17 #include <linux/input-event-codes.h>
     18 #include <cairo.h>
     19 #include <dbus/dbus.h>
     20 #include <drm_fourcc.h>
     21 #include <libinput.h>
     22 #include <security/pam_appl.h>
     23 #include <wayland-server-core.h>
     24 #include <xkbcommon/xkbcommon.h>
     25 #include <wlr/backend.h>
     26 #include <wlr/backend/libinput.h>
     27 #include <wlr/backend/session.h>
     28 #include <wlr/interfaces/wlr_buffer.h>
     29 #include <wlr/render/allocator.h>
     30 #include <wlr/render/wlr_renderer.h>
     31 #include <wlr/types/wlr_compositor.h>
     32 #include <wlr/types/wlr_cursor.h>
     33 #include <wlr/types/wlr_cursor_shape_v1.h>
     34 #include <wlr/types/wlr_data_control_v1.h>
     35 #include <wlr/types/wlr_data_device.h>
     36 #include <wlr/types/wlr_export_dmabuf_v1.h>
     37 #include <wlr/types/wlr_fractional_scale_v1.h>
     38 #include <wlr/types/wlr_gamma_control_v1.h>
     39 #include <wlr/types/wlr_idle_notify_v1.h>
     40 #include <wlr/types/wlr_input_device.h>
     41 #include <wlr/types/wlr_keyboard.h>
     42 #include <wlr/types/wlr_layer_shell_v1.h>
     43 #include <wlr/types/wlr_output.h>
     44 #include <wlr/types/wlr_output_layout.h>
     45 #include <wlr/types/wlr_pointer.h>
     46 #include <wlr/types/wlr_presentation_time.h>
     47 #include <wlr/types/wlr_primary_selection.h>
     48 #include <wlr/types/wlr_primary_selection_v1.h>
     49 #include <wlr/types/wlr_relative_pointer_v1.h>
     50 #include <wlr/types/wlr_scene.h>
     51 #include <wlr/types/wlr_screencopy_v1.h>
     52 #include <wlr/types/wlr_seat.h>
     53 #include <wlr/types/wlr_server_decoration.h>
     54 #include <wlr/types/wlr_single_pixel_buffer_v1.h>
     55 #include <wlr/types/wlr_subcompositor.h>
     56 #include <wlr/types/wlr_viewporter.h>
     57 #include <wlr/types/wlr_xcursor_manager.h>
     58 #include <wlr/types/wlr_xdg_activation_v1.h>
     59 #include <wlr/types/wlr_xdg_decoration_v1.h>
     60 #include <wlr/types/wlr_xdg_output_v1.h>
     61 #include <wlr/types/wlr_xdg_shell.h>
     62 #include <wlr/util/log.h>
     63 #include <wlr/xwayland.h>
     64 
     65 #define LENGTH(X)       (sizeof(X) / sizeof(X)[0])
     66 #define MAX(A, B)       ((A) > (B) ? (A) : (B))
     67 #define MIN(A, B)       ((A) < (B) ? (A) : (B))
     68 #define CLEANMASK(mask) ((mask) & ~(WLR_MODIFIER_CAPS|WLR_MODIFIER_MOD2))
     69 #define LISTEN(S, L, F) ((L)->notify = (F), wl_signal_add((S), (L)))
     70 #define NSCR            9
     71 #define SUPER           WLR_MODIFIER_LOGO
     72 #define SHIFT           WLR_MODIFIER_SHIFT
     73 
     74 enum { ColBg, ColWindow, ColOther, ColTitle, ColBar, ColLast };
     75 enum { ActRun, ActTerminal, ActMenu, ActClose, ActNext, ActFull, ActQuit, ActView, ActSend, ActVolUp, ActVolDown, ActMute,
     76        ActLightUp, ActLightDown, ActLeft, ActRight, ActMax, ActRestore, ActLock };
     77 enum { SegNone, SegNet, SegVol, SegLight };
     78 /* what the bottom line can show, in the order it's given */
     79 enum { BarCommands, BarNet, BarVol, BarLight, BarBattery, BarDate, BarClock, BarTty, BarLast };
     80 /* what's under the pointer: the first int of each */
     81 enum { KClient = 1, KLayer, KNotif, KBar };
     82 enum { GrabNone, GrabMove, GrabResize };
     83 
     84 typedef struct {
     85 	unsigned int mod;
     86 	xkb_keysym_t keysym;
     87 	int act, n;
     88 	char *cmd;
     89 } Key;
     90 
     91 /* pixels we draw with cairo, as something wlroots can show */
     92 typedef struct {
     93 	struct wlr_buffer base;
     94 	cairo_surface_t *s;
     95 } Buf;
     96 
     97 typedef struct Notif Notif;
     98 struct Notif {
     99 	int kind;
    100 	unsigned int id;
    101 	char app[64], line[4][128];
    102 	int nlines, w, h;
    103 	time_t until;
    104 	struct wlr_scene_buffer *buf;
    105 	Notif *next;
    106 };
    107 
    108 typedef struct Client Client;
    109 struct Client {
    110 	int kind;
    111 	char name[256];
    112 	int x, y, w, h, oldx, oldy, oldw, oldh;
    113 	int scr, isfull, mapped, unmanaged, out, assoc;
    114 	int snapped, sx, sy, sw, sh;	/* where it was before super+arrows */
    115 	int typed, total;		/* the border typing itself in: cells so far, of all */
    116 	long long born;			/* when it started, ms */
    117 	struct wlr_xdg_toplevel *xdg;
    118 	struct wlr_xdg_toplevel_decoration_v1 *deco;
    119 	struct wlr_xwayland_surface *xw;
    120 	struct wlr_scene_tree *tree, *content, *surf;
    121 	struct wlr_scene_buffer *edge[4];	/* top, bottom, left, right */
    122 	struct wlr_scene_rect *back;		/* black behind the window, like the tty was */
    123 	struct wl_listener map, unmap, commit, destroy, fullscreen, maximize, move, resize, title;
    124 	struct wl_listener associate, dissociate, configure, activate, geom, decomode, decodestroy;
    125 	Client *next;
    126 };
    127 
    128 typedef struct {
    129 	struct wlr_xdg_popup *p;
    130 	struct wlr_scene_tree *parent;
    131 	struct wl_listener commit, destroy;
    132 } Popup;
    133 
    134 typedef struct Layer Layer;
    135 struct Layer {
    136 	int kind;
    137 	struct wlr_layer_surface_v1 *ls;
    138 	struct wlr_scene_layer_surface_v1 *scene;
    139 	struct wl_listener map, unmap, commit, destroy;
    140 	Layer *next;
    141 };
    142 
    143 typedef struct Output Output;
    144 struct Output {
    145 	struct wlr_output *wlr;
    146 	struct wl_listener frame, state, destroy;
    147 	Output *next;
    148 };
    149 
    150 typedef struct Kbd Kbd;
    151 struct Kbd {
    152 	struct wlr_keyboard *wlr;
    153 	struct wl_listener key, mods, destroy;
    154 	Kbd *next;
    155 };
    156 
    157 /* window firefox = tty 2, full screen */
    158 typedef struct {
    159 	char name[64];
    160 	int scr, full;
    161 } Rule;
    162 
    163 /* settings, from ~/.config/torrent/config */
    164 static char terminal[256] = "foot", menu[256] = "fuzzel";
    165 static char colname[ColLast][32] = { "black", "white", "grey", "white", "grey" };
    166 static char wallpaper[512], kblayout[64], kbvariant[64];
    167 static int clock24 = 1, showclock = 1, showdate = 1, showbattery = 1, shownetwork = 1, showvolume = 1, showlight = 1, big;
    168 static int typing = 1, typespeed = 600;	/* cells a second */
    169 static int tapclick = 1, natural;
    170 static int barorder[BarLast + 1] = { BarCommands, BarNet, BarVol, BarLight, BarBattery, BarDate, BarClock, BarTty, -1 };
    171 static char barcmd[4][256], barout[4][64];
    172 static int nbarcmds;
    173 static Key *keys;
    174 static int nkeys;
    175 static Rule *rules;
    176 static int nrules;
    177 
    178 static const char defaultconfig[] =
    179 "# torrent settings\n"
    180 "# change what's after the = and save. it works right away.\n"
    181 "\n"
    182 "# colours: black blue green cyan red magenta brown grey\n"
    183 "#          dark grey, light blue, light green, light cyan, light red, pink, yellow, white\n"
    184 "#          or #rrggbb\n"
    185 "window colour = white\n"
    186 "other windows colour = grey\n"
    187 "title colour = white\n"
    188 "bottom line colour = grey\n"
    189 "background colour = black\n"
    190 "\n"
    191 "# a png behind the windows, or nothing for just the background colour\n"
    192 "wallpaper = /usr/share/backgrounds/chamesle/default.png\n"
    193 "\n"
    194 "# normal or big. big is for small, sharp screens. changes when you log in again\n"
    195 "text size = normal\n"
    196 "\n"
    197 "# new windows type their border in, closed ones type it away. on or off, and fast, normal or slow\n"
    198 "border typing = on\n"
    199 "typing speed = normal\n"
    200 "\n"
    201 "# what's on the bottom line, in this order. leave out what you don't want:\n"
    202 "#   commands network volume brightness battery date clock tty\n"
    203 "bottom line = commands network volume brightness battery date clock tty\n"
    204 "# 24 hour or 12 hour\n"
    205 "clock = 24 hour\n"
    206 "# your own things on the bottom line: a command, its first line shows. up to 4, every 5 seconds\n"
    207 "# bottom line command = cat /sys/class/thermal/thermal_zone0/temp\n"
    208 "\n"
    209 "# the terminal for new windows, and the apps menu\n"
    210 "terminal = foot\n"
    211 "apps menu = fuzzel\n"
    212 "\n"
    213 "# the keyboard, like us, de or fr. nothing means the one you picked when installing\n"
    214 "keyboard layout =\n"
    215 "keyboard variant =\n"
    216 "# the touchpad. changes when you log in again\n"
    217 "tap to click = on\n"
    218 "natural scrolling = off\n"
    219 "\n"
    220 "# keys. super is the windows key, then shift, ctrl, alt. after the = goes one of:\n"
    221 "#   terminal, apps menu, close window, next window, full screen, log out, lock,\n"
    222 "#   left half, right half, fill screen, put back, tty 1 to tty 9, send to tty 1 to 9,\n"
    223 "#   volume up, volume down, mute, brightness up, brightness down\n"
    224 "# or any program, like firefox\n"
    225 "super+enter = terminal\n"
    226 "super+d = apps menu\n"
    227 "super+q = close window\n"
    228 "super+tab = next window\n"
    229 "super+f = full screen\n"
    230 "super+shift+e = log out\n"
    231 "# these are there unless you put something else on the key:\n"
    232 "# super+1 to 9 = tty 1 to 9, super+shift+1 to 9 = send to tty 1 to 9, super+l = lock,\n"
    233 "# super+left = left half, super+right = right half, super+up = fill screen, super+down = put back\n"
    234 "# ctrl+alt+f1 to f12 go to the consoles, like everywhere\n"
    235 "\n"
    236 "# where windows go, by their name (the app id, or the class for x11 programs): tty 1 to 9, full screen, or both\n"
    237 "# window firefox = tty 2\n"
    238 "# window mpv = full screen\n"
    239 "\n"
    240 "# programs to start when you log in, one per line, like:\n"
    241 "# start = firefox\n"
    242 "\n"
    243 "# more settings from another file, read as if they were here\n"
    244 "# include = ~/.config/torrent/keys\n";
    245 
    246 static struct wl_display *dpy;
    247 static struct wl_event_loop *loop;
    248 static struct wlr_backend *backend;
    249 static struct wlr_session *session;
    250 static struct wlr_renderer *renderer;
    251 static struct wlr_allocator *alloc;
    252 static struct wlr_compositor *compositor;
    253 static struct wlr_scene *scene;
    254 static struct wlr_scene_output_layout *sol;
    255 static struct wlr_output_layout *layout;
    256 static struct wlr_xdg_shell *xdgshell;
    257 static struct wlr_layer_shell_v1 *layershell;
    258 static struct wlr_xdg_decoration_manager_v1 *decomgr;
    259 static struct wlr_cursor_shape_manager_v1 *shapemgr;
    260 static struct wlr_xdg_activation_v1 *activation;
    261 static struct wlr_cursor *cursor;
    262 static struct wlr_xcursor_manager *xcm;
    263 static struct wlr_seat *seat;
    264 static struct wlr_xwayland *xwayland;
    265 static struct wlr_idle_notifier_v1 *idle;
    266 /* bottom to top */
    267 static struct wlr_scene_tree *bgtree, *layers[4], *wintree, *bartree, *fulltree, *ortree, *notiftree, *locktree;
    268 static struct wlr_scene_rect *bgrect, *lockrect;
    269 static struct wlr_scene_buffer *wallbuf, *barbuf, *lockbuf;
    270 static struct wl_listener newoutput_l, newinput_l, newtoplevel_l, newpopup_l, newlayer_l, newdeco_l, newxw_l, xwready_l;
    271 static struct wl_listener motion_l, motionabs_l, button_l, axis_l, frame_l;
    272 static struct wl_listener setcursor_l, setsel_l, setpsel_l, shape_l, activate_l;
    273 static Output *outputs;
    274 static Kbd *kbds;
    275 static Layer *layersurfs, *exclusive;	/* exclusive: a layer that wants the keyboard, like the apps menu */
    276 static Client *clients, *sel, *ghosts;	/* ghosts: borders typing themselves away */
    277 static int ox, oy, sw, sh, wh, cw, ch, fontpx, fasc;
    278 static int cur, locked, barkind = KBar;
    279 static float col[ColLast][4];
    280 static cairo_font_options_t *fontopts;
    281 static struct wl_event_source *ticker;
    282 static int grab, gcx, gcy, gcw, gch;
    283 static double gx, gy;
    284 static Client *grabc;
    285 static char lockpw[256];
    286 static int locklen, lockwrong;
    287 static char cfgpath[4096];
    288 static time_t cfgmtime;
    289 static int vol = -1, muted;
    290 static char backlight[256];	/* /sys/class/backlight/..., or empty */
    291 static DBusConnection *bus;
    292 static Notif *notifs;
    293 static unsigned int lastid;
    294 static struct { int x0, x1, seg; } segs[16];
    295 static int nsegs;
    296 
    297 static int ulen(const char *);
    298 static void setfullscreen(Client *, int);
    299 static void drawbar(void);
    300 static void focus(Client *);
    301 
    302 static void
    303 die(const char *s)
    304 {
    305 	fprintf(stderr, "torrent: %s\n", s);
    306 	exit(1);
    307 }
    308 
    309 /* twice, so it's init's child and never our zombie */
    310 static void
    311 run(const char *cmd)
    312 {
    313 	pid_t pid;
    314 
    315 	if ((pid = fork()) == 0) {
    316 		if (fork() == 0) {
    317 			setsid();
    318 			execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
    319 			_exit(1);
    320 		}
    321 		_exit(0);
    322 	}
    323 	if (pid > 0)
    324 		waitpid(pid, NULL, 0);
    325 }
    326 
    327 /* runs cmd and waits for it, keeping the first line it prints */
    328 static void
    329 runwait(const char *cmd, char *out, size_t n)
    330 {
    331 	FILE *f;
    332 
    333 	if (out)
    334 		*out = '\0';
    335 	if (!(f = popen(cmd, "r")))
    336 		return;
    337 	if (out && !fgets(out, n, f))
    338 		*out = '\0';
    339 	while (fgetc(f) != EOF);
    340 	pclose(f);
    341 }
    342 
    343 static int
    344 readfile(const char *path, char *buf, size_t n)
    345 {
    346 	FILE *f;
    347 	size_t len;
    348 
    349 	if (!(f = fopen(path, "r")))
    350 		return 0;
    351 	len = fread(buf, 1, n - 1, f);
    352 	fclose(f);
    353 	buf[len] = '\0';
    354 	while (len && isspace((unsigned char)buf[len - 1]))
    355 		buf[--len] = '\0';
    356 	return 1;
    357 }
    358 
    359 static long
    360 readnum(const char *dir, const char *file)
    361 {
    362 	char path[512], buf[64];
    363 
    364 	snprintf(path, sizeof path, "%s/%s", dir, file);
    365 	return readfile(path, buf, sizeof buf) ? atol(buf) : -1;
    366 }
    367 
    368 static long long
    369 ms(void)
    370 {
    371 	struct timespec ts;
    372 
    373 	clock_gettime(CLOCK_MONOTONIC, &ts);
    374 	return ts.tv_sec * 1000LL + ts.tv_nsec / 1000000;
    375 }
    376 
    377 /* ---- settings ---- */
    378 
    379 static char *
    380 trim(char *s)
    381 {
    382 	char *e;
    383 
    384 	while (isspace((unsigned char)*s))
    385 		s++;
    386 	for (e = s + strlen(s); e > s && isspace((unsigned char)e[-1]); e--);
    387 	*e = '\0';
    388 	return s;
    389 }
    390 
    391 /* "Dark  Grey" -> "darkgrey" */
    392 static void
    393 squash(char *dst, const char *src, size_t n)
    394 {
    395 	size_t i = 0;
    396 
    397 	for (; *src && i < n - 1; src++)
    398 		if (!isspace((unsigned char)*src))
    399 			dst[i++] = tolower((unsigned char)*src);
    400 	dst[i] = '\0';
    401 }
    402 
    403 static int
    404 yes(const char *v)
    405 {
    406 	char s[16];
    407 
    408 	squash(s, v, sizeof s);
    409 	return !strcmp(s, "on") || !strcmp(s, "yes") || !strcmp(s, "true") || !strcmp(s, "1");
    410 }
    411 
    412 static const char *
    413 colourhex(const char *name)
    414 {
    415 	static const char *vga[][2] = {
    416 		{ "black", "#000000" }, { "blue", "#0000aa" }, { "green", "#00aa00" }, { "cyan", "#00aaaa" },
    417 		{ "red", "#aa0000" }, { "magenta", "#aa00aa" }, { "brown", "#aa5500" }, { "grey", "#aaaaaa" },
    418 		{ "gray", "#aaaaaa" }, { "darkgrey", "#555555" }, { "darkgray", "#555555" },
    419 		{ "lightblue", "#5555ff" }, { "lightgreen", "#55ff55" }, { "lightcyan", "#55ffff" },
    420 		{ "lightred", "#ff5555" }, { "pink", "#ff55ff" }, { "yellow", "#ffff55" }, { "white", "#ffffff" },
    421 	};
    422 	char s[32];
    423 	unsigned int i;
    424 
    425 	squash(s, name, sizeof s);
    426 	for (i = 0; i < LENGTH(vga); i++)
    427 		if (!strcmp(s, vga[i][0]))
    428 			return vga[i][1];
    429 	return name;
    430 }
    431 
    432 /* "window colour" or "window color" */
    433 static int
    434 iskey(const char *key, const char *want)
    435 {
    436 	char alt[64];
    437 	const char *p;
    438 
    439 	if (!strcmp(key, want))
    440 		return 1;
    441 	if (!(p = strstr(want, "colour")))
    442 		return 0;
    443 	snprintf(alt, sizeof alt, "%.*scolor%s", (int)(p - want), want, p + 6);
    444 	return !strcmp(key, alt);
    445 }
    446 
    447 static xkb_keysym_t
    448 keyname(const char *s)
    449 {
    450 	static const char *names[][2] = {
    451 		{ "enter", "Return" }, { "return", "Return" }, { "tab", "Tab" }, { "space", "space" },
    452 		{ "esc", "Escape" }, { "escape", "Escape" }, { "backspace", "BackSpace" }, { "delete", "Delete" },
    453 		{ "up", "Up" }, { "down", "Down" }, { "left", "Left" }, { "right", "Right" },
    454 		{ "home", "Home" }, { "end", "End" }, { "print", "Print" }, { "printscreen", "Print" },
    455 	};
    456 	char buf[32];
    457 	unsigned int i;
    458 	xkb_keysym_t k;
    459 
    460 	for (i = 0; i < LENGTH(names); i++)
    461 		if (!strcmp(s, names[i][0]))
    462 			return xkb_keysym_from_name(names[i][1], 0);
    463 	if (s[0] == 'f' && isdigit((unsigned char)s[1])) {
    464 		snprintf(buf, sizeof buf, "F%s", s + 1);
    465 		return xkb_keysym_from_name(buf, 0);
    466 	}
    467 	if ((k = xkb_keysym_from_name(s, 0)) != XKB_KEY_NoSymbol)
    468 		return k;
    469 	return xkb_keysym_from_name(s, XKB_KEYSYM_CASE_INSENSITIVE);
    470 }
    471 
    472 static void
    473 addkey(unsigned int mod, xkb_keysym_t sym, int act, int n, const char *cmd)
    474 {
    475 	Key *k;
    476 
    477 	if (!sym || !(k = realloc(keys, (nkeys + 1) * sizeof(Key))))
    478 		return;
    479 	keys = k;
    480 	k = &keys[nkeys++];
    481 	k->mod = mod;
    482 	k->keysym = sym;
    483 	k->act = act;
    484 	k->n = n;
    485 	k->cmd = cmd ? strdup(cmd) : NULL;
    486 }
    487 
    488 /* super+shift+e = log out */
    489 static int
    490 parsekey(char *name, char *value)
    491 {
    492 	static const struct { const char *word; int act; } acts[] = {
    493 		{ "terminal", ActTerminal }, { "appsmenu", ActMenu }, { "menu", ActMenu },
    494 		{ "closewindow", ActClose }, { "close", ActClose }, { "nextwindow", ActNext },
    495 		{ "fullscreen", ActFull }, { "logout", ActQuit }, { "quit", ActQuit }, { "lock", ActLock },
    496 		{ "lockscreen", ActLock }, { "lefthalf", ActLeft }, { "righthalf", ActRight },
    497 		{ "fillscreen", ActMax }, { "putback", ActRestore }, { "volumeup", ActVolUp },
    498 		{ "volumedown", ActVolDown }, { "mute", ActMute }, { "brightnessup", ActLightUp },
    499 		{ "brightnessdown", ActLightDown },
    500 	};
    501 	unsigned int mod = 0, i;
    502 	char *tok, *last = NULL, act[64];
    503 	int n;
    504 
    505 	if (!strchr(name, '+'))
    506 		return 0;
    507 	for (tok = strtok(name, "+"); tok; tok = strtok(NULL, "+")) {
    508 		tok = trim(tok);
    509 		if (last) {
    510 			if (!strcmp(last, "super") || !strcmp(last, "win") || !strcmp(last, "windows"))
    511 				mod |= WLR_MODIFIER_LOGO;
    512 			else if (!strcmp(last, "shift"))
    513 				mod |= WLR_MODIFIER_SHIFT;
    514 			else if (!strcmp(last, "ctrl") || !strcmp(last, "control"))
    515 				mod |= WLR_MODIFIER_CTRL;
    516 			else if (!strcmp(last, "alt"))
    517 				mod |= WLR_MODIFIER_ALT;
    518 			else
    519 				return 0;
    520 		}
    521 		last = tok;
    522 	}
    523 	if (!last)
    524 		return 0;
    525 	squash(act, value, sizeof act);
    526 	/* tty 3, send to tty 3 */
    527 	if ((!strncmp(act, "tty", 3) && (n = atoi(act + 3)) >= 1 && n <= NSCR)
    528 	|| (!strncmp(act, "sendtotty", 9) && (n = atoi(act + 9)) >= 1 && n <= NSCR)) {
    529 		addkey(mod, keyname(last), act[0] == 't' ? ActView : ActSend, n - 1, NULL);
    530 		return 1;
    531 	}
    532 	for (i = 0; i < LENGTH(acts); i++)
    533 		if (!strcmp(act, acts[i].word)) {
    534 			addkey(mod, keyname(last), acts[i].act, 0, NULL);
    535 			return 1;
    536 		}
    537 	addkey(mod, keyname(last), ActRun, 0, value);
    538 	return 1;
    539 }
    540 
    541 static void
    542 addrule(const char *name, char *value)
    543 {
    544 	Rule *r;
    545 	char *w, word[32];
    546 
    547 	if (!*name || !(r = realloc(rules, (nrules + 1) * sizeof(Rule))))
    548 		return;
    549 	rules = r;
    550 	r = &rules[nrules++];
    551 	snprintf(r->name, sizeof r->name, "%s", name);
    552 	r->scr = -1;
    553 	r->full = 0;
    554 	for (w = strtok(value, ","); w; w = strtok(NULL, ",")) {
    555 		squash(word, w, sizeof word);
    556 		if (!strncmp(word, "tty", 3) && atoi(word + 3) >= 1 && atoi(word + 3) <= NSCR)
    557 			r->scr = atoi(word + 3) - 1;
    558 		else if (!strcmp(word, "fullscreen"))
    559 			r->full = 1;
    560 	}
    561 }
    562 
    563 /* bottom line = network volume clock tty */
    564 static void
    565 setbar(char *value)
    566 {
    567 	static const char *names[] = { "commands", "network", "volume", "brightness", "battery", "date", "clock", "tty" };
    568 	char *w;
    569 	int n = 0, i;
    570 
    571 	for (w = strtok(value, " \t,"); w && n < BarLast; w = strtok(NULL, " \t,"))
    572 		for (i = 0; i < BarLast; i++)
    573 			if (!strcasecmp(w, names[i]))
    574 				barorder[n++] = i;
    575 	barorder[n] = -1;
    576 }
    577 
    578 static int
    579 haskey(unsigned int mod, xkb_keysym_t sym)
    580 {
    581 	int i;
    582 
    583 	for (i = 0; i < nkeys; i++)
    584 		if (keys[i].mod == mod && keys[i].keysym == sym)
    585 			return 1;
    586 	return 0;
    587 }
    588 
    589 static void
    590 defkey(unsigned int mod, xkb_keysym_t sym, int act, int n)
    591 {
    592 	if (!haskey(mod, sym))
    593 		addkey(mod, sym, act, n, NULL);
    594 }
    595 
    596 static void
    597 readconfig(FILE *f, int firsttime, int depth)
    598 {
    599 	char line[1024], path[4096], *name, *value, *eq, key[64], *home;
    600 	FILE *inc;
    601 
    602 	while (fgets(line, sizeof line, f)) {
    603 		if ((eq = strchr(line, '#')))
    604 			*eq = '\0';
    605 		if (!(eq = strchr(line, '=')))
    606 			continue;
    607 		*eq = '\0';
    608 		name = trim(line);
    609 		value = trim(eq + 1);
    610 		for (eq = name; *eq; eq++)
    611 			*eq = tolower((unsigned char)*eq);
    612 		if (parsekey(name, value))
    613 			continue;
    614 		squash(key, name, sizeof key);
    615 		if (!strncmp(name, "window ", 7) && !iskey(key, "windowcolour")) {
    616 			addrule(trim(name + 7), value);
    617 			continue;
    618 		}
    619 		if (iskey(key, "windowcolour"))
    620 			snprintf(colname[ColWindow], sizeof colname[0], "%s", value);
    621 		else if (iskey(key, "otherwindowscolour"))
    622 			snprintf(colname[ColOther], sizeof colname[0], "%s", value);
    623 		else if (iskey(key, "titlecolour"))
    624 			snprintf(colname[ColTitle], sizeof colname[0], "%s", value);
    625 		else if (iskey(key, "bottomlinecolour"))
    626 			snprintf(colname[ColBar], sizeof colname[0], "%s", value);
    627 		else if (iskey(key, "backgroundcolour"))
    628 			snprintf(colname[ColBg], sizeof colname[0], "%s", value);
    629 		else if (!strcmp(key, "wallpaper"))
    630 			snprintf(wallpaper, sizeof wallpaper, "%s", value);
    631 		else if (!strcmp(key, "textsize")) {
    632 			if (firsttime)
    633 				big = !strcasecmp(value, "big");
    634 		}
    635 		else if (!strcmp(key, "bordertyping"))
    636 			typing = yes(value);
    637 		else if (!strcmp(key, "typingspeed")) {
    638 			squash(key, value, sizeof key);
    639 			typespeed = !strcmp(key, "fast") ? 1500 : !strcmp(key, "slow") ? 250 : 600;
    640 		}
    641 		else if (!strcmp(key, "bottomline"))
    642 			setbar(value);
    643 		else if (!strcmp(key, "bottomlinecommand")) {
    644 			if (nbarcmds < (int)LENGTH(barcmd))
    645 				snprintf(barcmd[nbarcmds++], sizeof barcmd[0], "%s", value);
    646 		}
    647 		else if (!strcmp(key, "keyboardlayout"))
    648 			snprintf(kblayout, sizeof kblayout, "%s", value);
    649 		else if (!strcmp(key, "keyboardvariant"))
    650 			snprintf(kbvariant, sizeof kbvariant, "%s", value);
    651 		else if (!strcmp(key, "taptoclick"))
    652 			tapclick = yes(value);
    653 		else if (!strcmp(key, "naturalscrolling"))
    654 			natural = yes(value);
    655 		else if (!strcmp(key, "network"))
    656 			shownetwork = yes(value);
    657 		else if (!strcmp(key, "volume"))
    658 			showvolume = yes(value);
    659 		else if (!strcmp(key, "brightness"))
    660 			showlight = yes(value);
    661 		else if (!strcmp(key, "battery"))
    662 			showbattery = yes(value);
    663 		else if (!strcmp(key, "date"))
    664 			showdate = yes(value);
    665 		else if (!strcmp(key, "clock")) {
    666 			squash(key, value, sizeof key);
    667 			showclock = strcmp(key, "off") != 0;
    668 			clock24 = strncmp(key, "12", 2) != 0;
    669 		} else if (!strcmp(key, "terminal"))
    670 			snprintf(terminal, sizeof terminal, "%s", value);
    671 		else if (!strcmp(key, "appsmenu") || !strcmp(key, "menu"))
    672 			snprintf(menu, sizeof menu, "%s", value);
    673 		else if (!strcmp(key, "start")) {
    674 			if (firsttime)
    675 				run(value);
    676 		}
    677 		else if (!strcmp(key, "include")) {
    678 			/* ~/x, or next to the config */
    679 			if (value[0] == '~' && (home = getenv("HOME")))
    680 				snprintf(path, sizeof path, "%s%s", home, value + 1);
    681 			else if (value[0] != '/')
    682 				snprintf(path, sizeof path, "%.*s/%s", (int)(strrchr(cfgpath, '/') - cfgpath), cfgpath, value);
    683 			else
    684 				snprintf(path, sizeof path, "%s", value);
    685 			if (depth < 4 && (inc = fopen(path, "r"))) {
    686 				readconfig(inc, firsttime, depth + 1);
    687 				fclose(inc);
    688 			} else
    689 				fprintf(stderr, "torrent: can't include %s\n", path);
    690 		}
    691 		else
    692 			fprintf(stderr, "torrent: %s: don't know '%s'\n", cfgpath, name);
    693 	}
    694 }
    695 
    696 /* the layout jiggity wrote for x: wayland has no such file of its own */
    697 static void
    698 xkbfromx(void)
    699 {
    700 	char line[256], a[64], b[64];
    701 	FILE *f;
    702 
    703 	if (!(f = fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "r")))
    704 		return;
    705 	while (fgets(line, sizeof line, f))
    706 		if (sscanf(line, " Option \"%63[^\"]\" \"%63[^\"]\"", a, b) == 2) {
    707 			if (!strcmp(a, "XkbLayout") && !kblayout[0])
    708 				snprintf(kblayout, sizeof kblayout, "%s", b);
    709 			else if (!strcmp(a, "XkbVariant") && !kbvariant[0])
    710 				snprintf(kbvariant, sizeof kbvariant, "%s", b);
    711 		}
    712 	fclose(f);
    713 }
    714 
    715 static void
    716 loadconfig(int firsttime)
    717 {
    718 	FILE *f;
    719 	int i;
    720 	struct stat st;
    721 
    722 	if (stat(cfgpath, &st) < 0 && (f = fopen(cfgpath, "w"))) {
    723 		fputs(defaultconfig, f);
    724 		fclose(f);
    725 	}
    726 	if (stat(cfgpath, &st) == 0)
    727 		cfgmtime = st.st_mtime;
    728 
    729 	for (i = 0; i < nkeys; i++)
    730 		free(keys[i].cmd);
    731 	nkeys = 0;
    732 	nrules = 0;
    733 	nbarcmds = 0;
    734 	wallpaper[0] = kblayout[0] = kbvariant[0] = '\0';
    735 	f = fopen(cfgpath, "r");
    736 	if (!f) {
    737 		/* no file and nowhere to write one: the defaults, straight from memory */
    738 		f = fmemopen((void *)defaultconfig, sizeof defaultconfig - 1, "r");
    739 		if (!f)
    740 			return;
    741 	}
    742 	readconfig(f, firsttime, 0);
    743 	fclose(f);
    744 	if (!kblayout[0] && !getenv("XKB_DEFAULT_LAYOUT"))
    745 		xkbfromx();
    746 
    747 	/* these are there unless the key does something else */
    748 	for (i = 0; i < NSCR; i++) {
    749 		defkey(SUPER, XKB_KEY_1 + i, ActView, i);
    750 		defkey(SUPER|SHIFT, XKB_KEY_1 + i, ActSend, i);
    751 	}
    752 	defkey(0, XKB_KEY_XF86AudioRaiseVolume, ActVolUp, 0);
    753 	defkey(0, XKB_KEY_XF86AudioLowerVolume, ActVolDown, 0);
    754 	defkey(0, XKB_KEY_XF86AudioMute, ActMute, 0);
    755 	defkey(0, XKB_KEY_XF86MonBrightnessUp, ActLightUp, 0);
    756 	defkey(0, XKB_KEY_XF86MonBrightnessDown, ActLightDown, 0);
    757 	defkey(SUPER, XKB_KEY_Left, ActLeft, 0);
    758 	defkey(SUPER, XKB_KEY_Right, ActRight, 0);
    759 	defkey(SUPER, XKB_KEY_Up, ActMax, 0);
    760 	defkey(SUPER, XKB_KEY_Down, ActRestore, 0);
    761 	defkey(SUPER, XKB_KEY_l, ActLock, 0);
    762 }
    763 
    764 static void
    765 loadcolours(void)
    766 {
    767 	unsigned int r, g, b;
    768 	int i;
    769 
    770 	for (i = 0; i < ColLast; i++) {
    771 		if (sscanf(colourhex(colname[i]), "#%02x%02x%02x", &r, &g, &b) != 3)
    772 			r = g = b = i == ColBg ? 0 : 0xaa;
    773 		col[i][0] = r / 255.0;
    774 		col[i][1] = g / 255.0;
    775 		col[i][2] = b / 255.0;
    776 		col[i][3] = 1;
    777 	}
    778 }
    779 
    780 /* ---- drawing ---- */
    781 
    782 static void
    783 bufdestroy(struct wlr_buffer *wb)
    784 {
    785 	Buf *b = wl_container_of(wb, b, base);
    786 
    787 	cairo_surface_destroy(b->s);
    788 	free(b);
    789 }
    790 
    791 static bool
    792 bufbegin(struct wlr_buffer *wb, uint32_t flags, void **data, uint32_t *format, size_t *stride)
    793 {
    794 	Buf *b = wl_container_of(wb, b, base);
    795 
    796 	if (flags & WLR_BUFFER_DATA_PTR_ACCESS_WRITE)
    797 		return false;
    798 	*data = cairo_image_surface_get_data(b->s);
    799 	*format = DRM_FORMAT_ARGB8888;
    800 	*stride = cairo_image_surface_get_stride(b->s);
    801 	return true;
    802 }
    803 
    804 static void
    805 bufend(struct wlr_buffer *wb)
    806 {
    807 }
    808 
    809 static const struct wlr_buffer_impl bufimpl = {
    810 	.destroy = bufdestroy,
    811 	.begin_data_ptr_access = bufbegin,
    812 	.end_data_ptr_access = bufend,
    813 };
    814 
    815 static Buf *
    816 newbuf(int w, int h, cairo_t **cr)
    817 {
    818 	Buf *b;
    819 
    820 	if (!(b = calloc(1, sizeof *b)))
    821 		die("calloc failed");
    822 	b->s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, MAX(w, 1), MAX(h, 1));
    823 	wlr_buffer_init(&b->base, &bufimpl, MAX(w, 1), MAX(h, 1));
    824 	*cr = cairo_create(b->s);
    825 	cairo_set_font_options(*cr, fontopts);
    826 	cairo_select_font_face(*cr, "VGA", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
    827 	cairo_set_font_size(*cr, fontpx);
    828 	return b;
    829 }
    830 
    831 /* done drawing: wlroots shows it from now on, and lets go of the old one */
    832 static void
    833 putbuf(struct wlr_scene_buffer *sb, Buf *b, cairo_t *cr)
    834 {
    835 	cairo_destroy(cr);
    836 	cairo_surface_flush(b->s);
    837 	wlr_scene_buffer_set_buffer(sb, &b->base);
    838 	wlr_buffer_drop(&b->base);
    839 }
    840 
    841 static void
    842 fill(cairo_t *cr, int c, int x, int y, int w, int h)
    843 {
    844 	cairo_set_source_rgba(cr, col[c][0], col[c][1], col[c][2], col[c][3]);
    845 	cairo_rectangle(cr, x, y, w, h);
    846 	cairo_fill(cr);
    847 }
    848 
    849 static void
    850 text(cairo_t *cr, int c, int x, int y, const char *s)
    851 {
    852 	cairo_set_source_rgba(cr, col[c][0], col[c][1], col[c][2], col[c][3]);
    853 	cairo_move_to(cr, x, y + fasc);
    854 	cairo_show_text(cr, s);
    855 }
    856 
    857 /* the console's font, cell by cell: no smoothing, like the vga card drew it */
    858 static void
    859 fontsetup(void)
    860 {
    861 	cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1);
    862 	cairo_t *cr = cairo_create(s);
    863 	cairo_font_extents_t fe;
    864 
    865 	fontpx = big ? 32 : 16;
    866 	fontopts = cairo_font_options_create();
    867 	cairo_font_options_set_antialias(fontopts, CAIRO_ANTIALIAS_NONE);
    868 	cairo_font_options_set_hint_style(fontopts, CAIRO_HINT_STYLE_NONE);
    869 	cairo_font_options_set_hint_metrics(fontopts, CAIRO_HINT_METRICS_ON);
    870 	cairo_set_font_options(cr, fontopts);
    871 	cairo_select_font_face(cr, "VGA", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
    872 	cairo_set_font_size(cr, fontpx);
    873 	cairo_font_extents(cr, &fe);
    874 	cw = MAX((int)(fe.max_x_advance + 0.5), 1);
    875 	ch = MAX((int)(fe.ascent + fe.descent + 0.5), 1);
    876 	fasc = (int)(fe.ascent + 0.5);
    877 	cairo_destroy(cr);
    878 	cairo_surface_destroy(s);
    879 }
    880 
    881 static void
    882 kick(void)
    883 {
    884 	Output *o;
    885 
    886 	for (o = outputs; o; o = o->next)
    887 		wlr_output_schedule_frame(o->wlr);
    888 }
    889 
    890 /* the border, the way it's typed: along the top, down the right, back along the bottom, up the left.
    891  * cell i of it, as a place and a character */
    892 static void
    893 framecell(Client *c, int i, int *x, int *y, char *ch8, int *colour)
    894 {
    895 	int cols = c->w / cw + 2, rows = c->h / ch;
    896 	int n = MIN((int)strlen(c->name), MAX(cols - 10, 0));
    897 	int bc = c == sel ? ColWindow : ColOther;
    898 
    899 	*colour = bc;
    900 	if (i < cols) {
    901 		/* ┌─[ name ]───[x]┐ */
    902 		*x = i, *y = 0;
    903 		if (i == 0) strcpy(ch8, "┌");
    904 		else if (i == 1) strcpy(ch8, "─");
    905 		else if (i == 2) strcpy(ch8, "[");
    906 		else if (i < n + 5) {
    907 			*colour = ColTitle;
    908 			ch8[0] = i == 3 || i == n + 4 ? ' ' : c->name[i - 4];
    909 			ch8[1] = '\0';
    910 		}
    911 		else if (i == n + 5) strcpy(ch8, "]");
    912 		else if (i == cols - 4) strcpy(ch8, "[");
    913 		else if (i == cols - 3) strcpy(ch8, "x");
    914 		else if (i == cols - 2) strcpy(ch8, "]");
    915 		else if (i == cols - 1) strcpy(ch8, "┐");
    916 		else strcpy(ch8, "─");
    917 		return;
    918 	}
    919 	i -= cols;
    920 	if (i < rows) {
    921 		*x = cols - 1, *y = i + 1;
    922 		strcpy(ch8, "│");
    923 		return;
    924 	}
    925 	i -= rows;
    926 	if (i < cols) {
    927 		*x = cols - 1 - i, *y = rows + 1;
    928 		strcpy(ch8, i == 0 ? "┘" : i == cols - 1 ? "└" : "─");
    929 		return;
    930 	}
    931 	i -= cols;
    932 	*x = 0, *y = rows - i;
    933 	strcpy(ch8, "│");
    934 }
    935 
    936 /* a cell goes on whichever of the four edges it's on */
    937 static void
    938 putcell(cairo_t **cr, Client *c, int x, int y, const char *g, int colour)
    939 {
    940 	int rows = c->h / ch, e, px = 0, py = 0;
    941 
    942 	if (y == 0)
    943 		e = 0, px = x * cw;
    944 	else if (y == rows + 1)
    945 		e = 1, px = x * cw;
    946 	else
    947 		e = x == 0 ? 2 : 3, py = (y - 1) * ch;
    948 	fill(cr[e], ColBg, px, py, cw, ch);
    949 	text(cr[e], colour, px, py, g);
    950 }
    951 
    952 /* ┌─[ name ]───[x]┐ : as much of it as is typed, and a cursor after while it types */
    953 static void
    954 drawframe(Client *c)
    955 {
    956 	cairo_t *cr[4];
    957 	Buf *b[4];
    958 	char g[8];
    959 	int cols, rows, i, x, y, colour, n;
    960 
    961 	if (!c->tree || c->unmanaged || c->isfull || (!c->mapped && !c->out) || !c->w)
    962 		return;
    963 	cols = c->w / cw + 2;
    964 	rows = c->h / ch;
    965 	c->total = 2 * cols + 2 * rows;
    966 	n = MIN(c->typed, c->total);
    967 	b[0] = newbuf(cols * cw, ch, &cr[0]);
    968 	b[1] = newbuf(cols * cw, ch, &cr[1]);
    969 	b[2] = newbuf(cw, rows * ch, &cr[2]);
    970 	b[3] = newbuf(cw, rows * ch, &cr[3]);
    971 	for (i = 0; i < n; i++) {
    972 		framecell(c, i, &x, &y, g, &colour);
    973 		putcell(cr, c, x, y, g, colour);
    974 	}
    975 	if (n < c->total) {
    976 		framecell(c, n, &x, &y, g, &colour);
    977 		putcell(cr, c, x, y, "█", c == sel ? ColWindow : ColOther);
    978 	}
    979 	for (i = 0; i < 4; i++)
    980 		putbuf(c->edge[i], b[i], cr[i]);
    981 	wlr_scene_node_set_position(&c->edge[1]->node, 0, (rows + 1) * ch);
    982 	wlr_scene_node_set_position(&c->edge[2]->node, 0, ch);
    983 	wlr_scene_node_set_position(&c->edge[3]->node, (cols - 1) * cw, ch);
    984 }
    985 
    986 static struct wlr_surface *
    987 csurface(Client *c)
    988 {
    989 	return c->xdg ? c->xdg->base->surface : c->xw ? c->xw->surface : NULL;
    990 }
    991 
    992 static void
    993 kbfocus(struct wlr_surface *s)
    994 {
    995 	struct wlr_keyboard *kb = wlr_seat_get_keyboard(seat);
    996 
    997 	if (!s)
    998 		wlr_seat_keyboard_notify_clear_focus(seat);
    999 	else if (kb)
   1000 		wlr_seat_keyboard_notify_enter(seat, s, kb->keycodes, kb->num_keycodes, &kb->modifiers);
   1001 	else
   1002 		wlr_seat_keyboard_notify_enter(seat, s, NULL, 0, NULL);
   1003 }
   1004 
   1005 /* the border's typed: out comes the window */
   1006 static void
   1007 showcontent(Client *c)
   1008 {
   1009 	wlr_scene_node_set_enabled(&c->back->node, true);
   1010 	wlr_scene_node_set_enabled(&c->content->node, true);
   1011 	if (sel == c && !exclusive && !locked)
   1012 		kbfocus(csurface(c));
   1013 }
   1014 
   1015 /* the typing, by the clock: 1 while some border is still typing in or away */
   1016 static int
   1017 animate(void)
   1018 {
   1019 	Client *c, *g, **pg;
   1020 	int busy = 0, want;
   1021 	long long now = ms();
   1022 
   1023 	for (c = clients; c; c = c->next) {
   1024 		if (!c->mapped || c->typed >= c->total)
   1025 			continue;
   1026 		want = MIN((now - c->born) * typespeed / 1000, c->total);
   1027 		if (want > c->typed) {
   1028 			c->typed = want;
   1029 			drawframe(c);
   1030 		}
   1031 		if (c->typed >= c->total) {
   1032 			c->typed = INT32_MAX;
   1033 			drawframe(c);
   1034 			showcontent(c);
   1035 		} else
   1036 			busy = 1;
   1037 	}
   1038 	for (pg = &ghosts; (g = *pg);) {
   1039 		want = g->total - (now - g->born) * typespeed / 1000;
   1040 		if (want <= 0) {
   1041 			*pg = g->next;
   1042 			wlr_scene_node_destroy(&g->tree->node);
   1043 			free(g);
   1044 			continue;
   1045 		}
   1046 		if (want < g->typed) {
   1047 			g->typed = want;
   1048 			drawframe(g);
   1049 		}
   1050 		busy = 1;
   1051 		pg = &g->next;
   1052 	}
   1053 	return busy;
   1054 }
   1055 
   1056 /* a closed window's border, left behind to type itself away */
   1057 static void
   1058 ghost(Client *c)
   1059 {
   1060 	Client *g;
   1061 	int i;
   1062 
   1063 	if (!typing || c->scr != cur || c->isfull || c->typed < c->total || !(g = calloc(1, sizeof *g)))
   1064 		return;
   1065 	memcpy(g->name, c->name, sizeof g->name);
   1066 	g->w = c->w;
   1067 	g->h = c->h;
   1068 	g->scr = cur;
   1069 	g->out = 1;
   1070 	g->tree = wlr_scene_tree_create(wintree);
   1071 	wlr_scene_node_set_position(&g->tree->node, ox + c->x, oy + c->y);
   1072 	for (i = 0; i < 4; i++)
   1073 		g->edge[i] = wlr_scene_buffer_create(g->tree, NULL);
   1074 	g->total = g->typed = 2 * (g->w / cw + 2) + 2 * (g->h / ch);
   1075 	g->born = ms();
   1076 	g->next = ghosts;
   1077 	ghosts = g;
   1078 	drawframe(g);
   1079 	kick();
   1080 }
   1081 
   1082 /* where everything of a window goes, from its place and size */
   1083 static void
   1084 place(Client *c)
   1085 {
   1086 	int gx0 = 0, gy0 = 0, full = c->isfull, i;
   1087 
   1088 	if (c->xdg) {
   1089 		gx0 = c->xdg->base->geometry.x;
   1090 		gy0 = c->xdg->base->geometry.y;
   1091 	}
   1092 	wlr_scene_node_set_position(&c->tree->node, full ? ox : ox + c->x, full ? oy : oy + c->y);
   1093 	for (i = 0; i < 4; i++)
   1094 		wlr_scene_node_set_enabled(&c->edge[i]->node, !full);
   1095 	wlr_scene_node_set_position(&c->back->node, full ? 0 : cw, full ? 0 : ch);
   1096 	wlr_scene_rect_set_size(c->back, full ? sw : c->w, full ? sh : c->h);
   1097 	wlr_scene_node_set_position(&c->content->node, (full ? 0 : cw) - gx0, (full ? 0 : ch) - gy0);
   1098 	/* a window that's bigger than it was told doesn't spill out of its frame */
   1099 	if (c->surf)
   1100 		wlr_scene_subsurface_tree_set_clip(&c->surf->node,
   1101 			&(struct wlr_box){ gx0, gy0, full ? sw : c->w, full ? sh : c->h });
   1102 }
   1103 
   1104 /* tells the program its size, and x11 ones where they are too */
   1105 static void
   1106 cconfigure(Client *c)
   1107 {
   1108 	if (c->xdg && c->xdg->base->initialized)
   1109 		wlr_xdg_toplevel_set_size(c->xdg, c->isfull ? sw : c->w, c->isfull ? sh : c->h);
   1110 	else if (c->xw) {
   1111 		if (c->isfull)
   1112 			wlr_xwayland_surface_configure(c->xw, ox, oy, sw, sh);
   1113 		else
   1114 			wlr_xwayland_surface_configure(c->xw, ox + c->x + cw, oy + c->y + ch, c->w, c->h);
   1115 	}
   1116 }
   1117 
   1118 /* ---- the bottom line ---- */
   1119 
   1120 static void
   1121 readvolume(void)
   1122 {
   1123 	char buf[128];
   1124 	float v;
   1125 
   1126 	vol = -1;
   1127 	runwait("wpctl get-volume @DEFAULT_AUDIO_SINK@ 2>/dev/null", buf, sizeof buf);
   1128 	if (sscanf(buf, "Volume: %f", &v) == 1) {
   1129 		vol = v * 100 + 0.5;
   1130 		muted = strstr(buf, "MUTED") != NULL;
   1131 	}
   1132 }
   1133 
   1134 /* the first backlight there is. the video group may write it */
   1135 static void
   1136 findbacklight(void)
   1137 {
   1138 	DIR *d;
   1139 	struct dirent *e;
   1140 
   1141 	backlight[0] = '\0';
   1142 	if (!(d = opendir("/sys/class/backlight")))
   1143 		return;
   1144 	while ((e = readdir(d)))
   1145 		if (e->d_name[0] != '.') {
   1146 			snprintf(backlight, sizeof backlight, "/sys/class/backlight/%s", e->d_name);
   1147 			break;
   1148 		}
   1149 	closedir(d);
   1150 }
   1151 
   1152 static int
   1153 light(void)
   1154 {
   1155 	long now, max;
   1156 
   1157 	if (!backlight[0] || (now = readnum(backlight, "brightness")) < 0 || (max = readnum(backlight, "max_brightness")) <= 0)
   1158 		return -1;
   1159 	return (now * 100 + max / 2) / max;
   1160 }
   1161 
   1162 static void
   1163 setlight(int step)
   1164 {
   1165 	char path[300];
   1166 	long max;
   1167 	int pct = light();
   1168 	FILE *f;
   1169 
   1170 	if (pct < 0 || (max = readnum(backlight, "max_brightness")) <= 0)
   1171 		return;
   1172 	/* 5% steps, but never all the way to black */
   1173 	pct = MIN(MAX(pct + step, 1), 100);
   1174 	snprintf(path, sizeof path, "%s/brightness", backlight);
   1175 	if ((f = fopen(path, "w"))) {
   1176 		fprintf(f, "%ld\n", MAX(pct * max / 100, 1));
   1177 		fclose(f);
   1178 	} else
   1179 		fprintf(stderr, "torrent: %s: can't write it, are you in the video group?\n", path);
   1180 }
   1181 
   1182 static void
   1183 network(char *s, size_t n)
   1184 {
   1185 	DIR *d;
   1186 	struct dirent *e;
   1187 	char path[512], state[32];
   1188 	int wired = 0, wifi = 0;
   1189 
   1190 	snprintf(s, n, "offline");
   1191 	if (!(d = opendir("/sys/class/net")))
   1192 		return;
   1193 	while ((e = readdir(d))) {
   1194 		if (e->d_name[0] == '.' || !strcmp(e->d_name, "lo"))
   1195 			continue;
   1196 		snprintf(path, sizeof path, "/sys/class/net/%s/operstate", e->d_name);
   1197 		if (!readfile(path, state, sizeof state) || strcmp(state, "up"))
   1198 			continue;
   1199 		snprintf(path, sizeof path, "/sys/class/net/%s/wireless", e->d_name);
   1200 		if (access(path, F_OK) == 0)
   1201 			wifi = 1;
   1202 		else
   1203 			wired = 1;
   1204 	}
   1205 	closedir(d);
   1206 	snprintf(s, n, "%s", wired ? "wired" : wifi ? "wifi" : "offline");
   1207 }
   1208 
   1209 /* all batteries together: a T480 has two */
   1210 static int
   1211 battery(char *s, size_t n)
   1212 {
   1213 	DIR *d;
   1214 	struct dirent *e;
   1215 	char dir[512], path[600], buf[32];
   1216 	long now = 0, full = 0, a, b;
   1217 	int charging = 0;
   1218 
   1219 	if (!(d = opendir("/sys/class/power_supply")))
   1220 		return 0;
   1221 	while ((e = readdir(d))) {
   1222 		snprintf(dir, sizeof dir, "/sys/class/power_supply/%s", e->d_name);
   1223 		snprintf(path, sizeof path, "%s/type", dir);
   1224 		if (!readfile(path, buf, sizeof buf) || strcmp(buf, "Battery"))
   1225 			continue;
   1226 		snprintf(path, sizeof path, "%s/status", dir);
   1227 		if (readfile(path, buf, sizeof buf) && !strcmp(buf, "Charging"))
   1228 			charging = 1;
   1229 		if ((a = readnum(dir, "energy_now")) < 0 || (b = readnum(dir, "energy_full")) <= 0) {
   1230 			a = readnum(dir, "charge_now");
   1231 			b = readnum(dir, "charge_full");
   1232 		}
   1233 		if (a >= 0 && b > 0) {
   1234 			now += a;
   1235 			full += b;
   1236 		}
   1237 	}
   1238 	closedir(d);
   1239 	if (!full)
   1240 		return 0;
   1241 	snprintf(s, n, "bat %ld%%%s", now * 100 / full, charging ? "+" : "");
   1242 	return 1;
   1243 }
   1244 
   1245 /* your own bottom line commands, every 5 seconds from tick */
   1246 static void
   1247 runbarcmds(void)
   1248 {
   1249 	int i;
   1250 
   1251 	for (i = 0; i < nbarcmds; i++) {
   1252 		runwait(barcmd[i], barout[i], sizeof barout[i]);
   1253 		barout[i][strcspn(barout[i], "\n")] = '\0';
   1254 	}
   1255 }
   1256 
   1257 static void
   1258 drawbar(void)
   1259 {
   1260 	char seg[16][64];
   1261 	int kind[16], n = 0, i, j, x, len = 0, pct;
   1262 	time_t t = time(NULL);
   1263 	struct tm *tm = localtime(&t);
   1264 	cairo_t *cr;
   1265 	Buf *b;
   1266 
   1267 	if (!sw || !cw)
   1268 		return;
   1269 	for (j = 0; barorder[j] >= 0 && n < (int)LENGTH(seg) - 4; j++)
   1270 		switch (barorder[j]) {
   1271 		case BarCommands:
   1272 			for (i = 0; i < nbarcmds; i++)
   1273 				if (barout[i][0]) {
   1274 					snprintf(seg[n], sizeof seg[n], "%s", barout[i]);
   1275 					kind[n++] = SegNone;
   1276 				}
   1277 			break;
   1278 		case BarNet:
   1279 			if (shownetwork) {
   1280 				network(seg[n], sizeof seg[n]);
   1281 				kind[n++] = SegNet;
   1282 			}
   1283 			break;
   1284 		case BarVol:
   1285 			if (showvolume && vol >= 0) {
   1286 				snprintf(seg[n], sizeof seg[n], muted ? "vol muted" : "vol %d%%", vol);
   1287 				kind[n++] = SegVol;
   1288 			}
   1289 			break;
   1290 		case BarLight:
   1291 			if (showlight && (pct = light()) >= 0) {
   1292 				snprintf(seg[n], sizeof seg[n], "light %d%%", pct);
   1293 				kind[n++] = SegLight;
   1294 			}
   1295 			break;
   1296 		case BarBattery:
   1297 			if (showbattery && battery(seg[n], sizeof seg[n]))
   1298 				kind[n++] = SegNone;
   1299 			break;
   1300 		case BarDate:
   1301 			if (showdate) {
   1302 				strftime(seg[n], sizeof seg[n], "%a %d %b", tm);
   1303 				kind[n++] = SegNone;
   1304 			}
   1305 			break;
   1306 		case BarClock:
   1307 			if (showclock) {
   1308 				strftime(seg[n], sizeof seg[n], clock24 ? "%H:%M" : "%I:%M %p", tm);
   1309 				kind[n++] = SegNone;
   1310 			}
   1311 			break;
   1312 		case BarTty:
   1313 			snprintf(seg[n], sizeof seg[n], "tty%d", cur + 1);
   1314 			kind[n++] = SegNone;
   1315 			break;
   1316 		}
   1317 
   1318 	for (i = 0; i < n; i++)
   1319 		len += ulen(seg[i]) + 2;
   1320 	b = newbuf(sw, ch, &cr);
   1321 	fill(cr, ColBg, 0, 0, sw, ch);
   1322 	x = sw - len * cw;
   1323 	nsegs = 0;
   1324 	for (i = 0; i < n; i++) {
   1325 		text(cr, ColBar, x, 0, seg[i]);
   1326 		if (nsegs < (int)LENGTH(segs)) {
   1327 			segs[nsegs].x0 = x;
   1328 			segs[nsegs].x1 = x + ulen(seg[i]) * cw;
   1329 			segs[nsegs++].seg = kind[i];
   1330 		}
   1331 		x += (ulen(seg[i]) + 2) * cw;
   1332 	}
   1333 	putbuf(barbuf, b, cr);
   1334 }
   1335 
   1336 static void
   1337 setvolume(const char *how)
   1338 {
   1339 	char cmd[128];
   1340 
   1341 	if (!strcmp(how, "mute"))
   1342 		snprintf(cmd, sizeof cmd, "wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle");
   1343 	else
   1344 		snprintf(cmd, sizeof cmd, "wpctl set-volume -l 1.5 @DEFAULT_AUDIO_SINK@ %s", how);
   1345 	runwait(cmd, NULL, 0);
   1346 	readvolume();
   1347 	drawbar();
   1348 }
   1349 
   1350 /* fills the screen with it, cut to fit */
   1351 static void
   1352 drawwallpaper(void)
   1353 {
   1354 	cairo_surface_t *img = NULL;
   1355 	cairo_t *cr;
   1356 	Buf *b;
   1357 	char path[4096], *home = getenv("HOME");
   1358 	double s;
   1359 	int iw, ih;
   1360 
   1361 	if (wallpaper[0] == '~' && home)
   1362 		snprintf(path, sizeof path, "%s%s", home, wallpaper + 1);
   1363 	else
   1364 		snprintf(path, sizeof path, "%s", wallpaper);
   1365 	if (!wallpaper[0] || !sw || !(img = cairo_image_surface_create_from_png(path))
   1366 	|| cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
   1367 		if (img)
   1368 			cairo_surface_destroy(img);
   1369 		wlr_scene_buffer_set_buffer(wallbuf, NULL);
   1370 		return;
   1371 	}
   1372 	iw = cairo_image_surface_get_width(img);
   1373 	ih = cairo_image_surface_get_height(img);
   1374 	s = MAX((double)sw / iw, (double)sh / ih);
   1375 	b = newbuf(sw, sh, &cr);
   1376 	cairo_translate(cr, (sw - iw * s) / 2, (sh - ih * s) / 2);
   1377 	cairo_scale(cr, s, s);
   1378 	cairo_set_source_surface(cr, img, 0, 0);
   1379 	cairo_paint(cr);
   1380 	putbuf(wallbuf, b, cr);
   1381 	wlr_scene_node_set_position(&wallbuf->node, ox, oy);
   1382 	cairo_surface_destroy(img);
   1383 }
   1384 
   1385 /* ---- notifications: torrent is org.freedesktop.Notifications ---- */
   1386 
   1387 #define NOTIFCOLS 48
   1388 
   1389 /* characters, not bytes */
   1390 static int
   1391 ulen(const char *s)
   1392 {
   1393 	int n = 0;
   1394 
   1395 	for (; *s; s++)
   1396 		n += (*s & 0xc0) != 0x80;
   1397 	return n;
   1398 }
   1399 
   1400 /* the first n characters of s */
   1401 static void
   1402 ucut(char *dst, const char *s, int n, size_t size)
   1403 {
   1404 	size_t i = 0;
   1405 
   1406 	for (; *s && i < size - 1; s++) {
   1407 		if ((*s & 0xc0) != 0x80 && n-- <= 0)
   1408 			break;
   1409 		dst[i++] = *s;
   1410 	}
   1411 	dst[i] = '\0';
   1412 }
   1413 
   1414 /* <b>bold</b> &amp; co. as plain text */
   1415 static void
   1416 plain(char *dst, const char *s, size_t size)
   1417 {
   1418 	static const char *ent[][2] = { { "&amp;", "&" }, { "&lt;", "<" }, { "&gt;", ">" }, { "&quot;", "\"" }, { "&apos;", "'" } };
   1419 	size_t i = 0;
   1420 	unsigned int e;
   1421 
   1422 	while (*s && i < size - 1) {
   1423 		if (*s == '<' && strchr(s, '>')) {
   1424 			s = strchr(s, '>') + 1;
   1425 			continue;
   1426 		}
   1427 		for (e = 0; e < LENGTH(ent); e++)
   1428 			if (!strncmp(s, ent[e][0], strlen(ent[e][0])))
   1429 				break;
   1430 		if (e < LENGTH(ent)) {
   1431 			dst[i++] = ent[e][1][0];
   1432 			s += strlen(ent[e][0]);
   1433 		} else
   1434 			dst[i++] = *s == '\n' || *s == '\t' ? ' ' : *s, s++;
   1435 	}
   1436 	dst[i] = '\0';
   1437 }
   1438 
   1439 static void
   1440 drawnotif(Notif *n)
   1441 {
   1442 	char buf[1024], *p;
   1443 	int cols = n->w / cw, i;
   1444 	cairo_t *cr;
   1445 	Buf *b = newbuf(n->w, n->h, &cr);
   1446 
   1447 	fill(cr, ColBg, 0, 0, n->w, n->h);
   1448 	text(cr, ColWindow, 0, 0, "┌─[");
   1449 	snprintf(buf, sizeof buf, " %s ", n->app);
   1450 	text(cr, ColTitle, 3 * cw, 0, buf);
   1451 	p = buf + sprintf(buf, "]");
   1452 	for (i = ulen(n->app) + 6; i < cols - 1; i++)
   1453 		p += sprintf(p, "─");
   1454 	sprintf(p, "┐");
   1455 	text(cr, ColWindow, (ulen(n->app) + 5) * cw, 0, buf);
   1456 	for (i = 0; i < n->nlines; i++) {
   1457 		text(cr, ColWindow, 0, (i + 1) * ch, "│");
   1458 		text(cr, i ? ColWindow : ColTitle, 2 * cw, (i + 1) * ch, n->line[i]);
   1459 		text(cr, ColWindow, (cols - 1) * cw, (i + 1) * ch, "│");
   1460 	}
   1461 	p = buf + sprintf(buf, "└");
   1462 	for (i = 2; i < cols; i++)
   1463 		p += sprintf(p, "─");
   1464 	sprintf(p, "┘");
   1465 	text(cr, ColWindow, 0, (n->nlines + 1) * ch, buf);
   1466 	putbuf(n->buf, b, cr);
   1467 }
   1468 
   1469 /* stacked down from the top right corner, newest last */
   1470 static void
   1471 placenotifs(void)
   1472 {
   1473 	Notif *n;
   1474 	int y = 0;
   1475 
   1476 	for (n = notifs; n; n = n->next) {
   1477 		wlr_scene_node_set_position(&n->buf->node, ox + sw / MAX(cw, 1) * cw - n->w, oy + y);
   1478 		drawnotif(n);
   1479 		y += n->h;
   1480 	}
   1481 }
   1482 
   1483 static void
   1484 closenotif(Notif *n, unsigned int why)
   1485 {
   1486 	Notif **pn;
   1487 	DBusMessage *m;
   1488 	dbus_uint32_t id = n->id, reason = why;
   1489 
   1490 	for (pn = &notifs; *pn != n; pn = &(*pn)->next);
   1491 	*pn = n->next;
   1492 	wlr_scene_node_destroy(&n->buf->node);
   1493 	free(n);
   1494 	placenotifs();
   1495 	if (bus && (m = dbus_message_new_signal("/org/freedesktop/Notifications",
   1496 	    "org.freedesktop.Notifications", "NotificationClosed"))) {
   1497 		dbus_message_append_args(m, DBUS_TYPE_UINT32, &id, DBUS_TYPE_UINT32, &reason, DBUS_TYPE_INVALID);
   1498 		dbus_connection_send(bus, m, NULL);
   1499 		dbus_message_unref(m);
   1500 	}
   1501 }
   1502 
   1503 static unsigned int
   1504 notify(const char *app, unsigned int replaces, const char *summary, const char *body, int timeout)
   1505 {
   1506 	Notif *n, **pn;
   1507 	char buf[1024], word[256], *p, *w;
   1508 	int i, len;
   1509 
   1510 	for (n = notifs; n && (!replaces || n->id != replaces); n = n->next);
   1511 	if (!n) {
   1512 		if (!(n = calloc(1, sizeof *n)))
   1513 			return 0;
   1514 		n->kind = KNotif;
   1515 		n->id = ++lastid;
   1516 		n->buf = wlr_scene_buffer_create(notiftree, NULL);
   1517 		n->buf->node.data = n;
   1518 		for (pn = &notifs; *pn; pn = &(*pn)->next);
   1519 		*pn = n;
   1520 	}
   1521 	ucut(n->app, *app ? app : "notification", NOTIFCOLS - 10, sizeof n->app);
   1522 	plain(buf, summary, sizeof buf);
   1523 	ucut(n->line[0], buf, NOTIFCOLS - 4, sizeof n->line[0]);
   1524 	n->nlines = 1;
   1525 
   1526 	/* the body, a word at a time, in up to 3 lines under the summary */
   1527 	plain(buf, body, sizeof buf);
   1528 	for (p = buf; (w = strsep(&p, " "));) {
   1529 		if (!*w)
   1530 			continue;
   1531 		ucut(word, w, NOTIFCOLS - 4, sizeof word);
   1532 		i = n->nlines - 1;
   1533 		if (i > 0 && ulen(n->line[i]) + 1 + ulen(word) <= NOTIFCOLS - 4) {
   1534 			len = strlen(n->line[i]);
   1535 			snprintf(n->line[i] + len, sizeof n->line[i] - len, " %s", word);
   1536 		} else if (n->nlines < 4)
   1537 			snprintf(n->line[n->nlines++], sizeof n->line[0], "%s", word);
   1538 		else
   1539 			break;
   1540 	}
   1541 	n->w = 0;
   1542 	for (i = 0; i < n->nlines; i++)
   1543 		n->w = MAX(n->w, ulen(n->line[i]) + 4);
   1544 	n->w = MAX(n->w, ulen(n->app) + 10) * cw;
   1545 	n->h = (n->nlines + 2) * ch;
   1546 	/* -1: the usual 5 seconds. 0: until it's clicked */
   1547 	n->until = timeout == 0 ? 0 : time(NULL) + (timeout < 0 ? 5 : (timeout + 999) / 1000);
   1548 	placenotifs();
   1549 	return n->id;
   1550 }
   1551 
   1552 static void
   1553 expirenotifs(void)
   1554 {
   1555 	Notif *n, *next;
   1556 	time_t now = time(NULL);
   1557 
   1558 	for (n = notifs; n; n = next) {
   1559 		next = n->next;
   1560 		if (n->until && n->until <= now)
   1561 			closenotif(n, 1);
   1562 	}
   1563 }
   1564 
   1565 static void
   1566 arg(DBusMessageIter *it, int type, void *v)
   1567 {
   1568 	if (dbus_message_iter_get_arg_type(it) == type)
   1569 		dbus_message_iter_get_basic(it, v);
   1570 	dbus_message_iter_next(it);
   1571 }
   1572 
   1573 static void
   1574 dbusmessage(DBusMessage *m)
   1575 {
   1576 	static const char *iface = "org.freedesktop.Notifications";
   1577 	static const char *caps[] = { "body" }, **cp = caps;
   1578 	static const char *info[] = { "torrent", "Chamesle", VERSION, "1.2" };
   1579 	const char *app = "", *icon = "", *summary = "", *body = "";
   1580 	dbus_uint32_t replaces = 0, id;
   1581 	dbus_int32_t timeout = -1;
   1582 	DBusMessageIter it;
   1583 	DBusMessage *r;
   1584 	Notif *n;
   1585 
   1586 	if (dbus_message_get_type(m) != DBUS_MESSAGE_TYPE_METHOD_CALL)
   1587 		return;
   1588 	if (dbus_message_is_method_call(m, iface, "Notify")) {
   1589 		dbus_message_iter_init(m, &it);
   1590 		arg(&it, DBUS_TYPE_STRING, &app);
   1591 		arg(&it, DBUS_TYPE_UINT32, &replaces);
   1592 		arg(&it, DBUS_TYPE_STRING, &icon);
   1593 		arg(&it, DBUS_TYPE_STRING, &summary);
   1594 		arg(&it, DBUS_TYPE_STRING, &body);
   1595 		dbus_message_iter_next(&it);	/* actions: not here */
   1596 		dbus_message_iter_next(&it);	/* hints */
   1597 		arg(&it, DBUS_TYPE_INT32, &timeout);
   1598 		id = notify(app, replaces, summary, body, timeout);
   1599 		r = dbus_message_new_method_return(m);
   1600 		dbus_message_append_args(r, DBUS_TYPE_UINT32, &id, DBUS_TYPE_INVALID);
   1601 	} else if (dbus_message_is_method_call(m, iface, "CloseNotification")) {
   1602 		dbus_message_iter_init(m, &it);
   1603 		id = 0;
   1604 		arg(&it, DBUS_TYPE_UINT32, &id);
   1605 		for (n = notifs; n && n->id != id; n = n->next);
   1606 		if (n)
   1607 			closenotif(n, 3);
   1608 		r = dbus_message_new_method_return(m);
   1609 	} else if (dbus_message_is_method_call(m, iface, "GetCapabilities")) {
   1610 		r = dbus_message_new_method_return(m);
   1611 		dbus_message_append_args(r, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &cp, 1, DBUS_TYPE_INVALID);
   1612 	} else if (dbus_message_is_method_call(m, iface, "GetServerInformation")) {
   1613 		r = dbus_message_new_method_return(m);
   1614 		dbus_message_append_args(r, DBUS_TYPE_STRING, &info[0], DBUS_TYPE_STRING, &info[1],
   1615 		                         DBUS_TYPE_STRING, &info[2], DBUS_TYPE_STRING, &info[3], DBUS_TYPE_INVALID);
   1616 	} else
   1617 		r = dbus_message_new_error(m, DBUS_ERROR_UNKNOWN_METHOD, "torrent only shows notifications");
   1618 	if (r) {
   1619 		dbus_connection_send(bus, r, NULL);
   1620 		dbus_message_unref(r);
   1621 	}
   1622 }
   1623 
   1624 /* no session bus, or another program shows notifications already (like mako): then not us */
   1625 static void
   1626 setupbus(void)
   1627 {
   1628 	DBusError err;
   1629 
   1630 	dbus_error_init(&err);
   1631 	if (!(bus = dbus_bus_get(DBUS_BUS_SESSION, &err))) {
   1632 		dbus_error_free(&err);
   1633 		return;
   1634 	}
   1635 	dbus_connection_set_exit_on_disconnect(bus, FALSE);
   1636 	if (dbus_bus_request_name(bus, "org.freedesktop.Notifications", DBUS_NAME_FLAG_DO_NOT_QUEUE, &err)
   1637 	    != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
   1638 		dbus_error_free(&err);
   1639 		bus = NULL;
   1640 	}
   1641 }
   1642 
   1643 static void
   1644 readbus(void)
   1645 {
   1646 	DBusMessage *m;
   1647 
   1648 	if (!bus)
   1649 		return;
   1650 	dbus_connection_read_write(bus, 0);
   1651 	while ((m = dbus_connection_pop_message(bus))) {
   1652 		dbusmessage(m);
   1653 		dbus_message_unref(m);
   1654 	}
   1655 	dbus_connection_flush(bus);
   1656 }
   1657 
   1658 static int
   1659 busready(int fd, uint32_t mask, void *data)
   1660 {
   1661 	readbus();
   1662 	return 0;
   1663 }
   1664 
   1665 /* ---- windows ---- */
   1666 
   1667 static Client *
   1668 topclient(void)
   1669 {
   1670 	Client *c;
   1671 
   1672 	for (c = clients; c && (!c->mapped || c->unmanaged || c->scr != cur); c = c->next);
   1673 	return c;
   1674 }
   1675 
   1676 static void
   1677 cactivate(Client *c, int on)
   1678 {
   1679 	if (c->xdg && c->xdg->base->initialized)
   1680 		wlr_xdg_toplevel_set_activated(c->xdg, on);
   1681 	else if (c->xw)
   1682 		wlr_xwayland_surface_activate(c->xw, on);
   1683 }
   1684 
   1685 /* focus(NULL): nothing has the keyboard */
   1686 static void
   1687 focus(Client *c)
   1688 {
   1689 	Client *old = sel;
   1690 
   1691 	if (c && (!c->mapped || c->unmanaged))
   1692 		return;
   1693 	sel = c;
   1694 	if (old && old != c) {
   1695 		drawframe(old);
   1696 		cactivate(old, 0);
   1697 	}
   1698 	if (!c) {
   1699 		if (!exclusive && !locked)
   1700 			kbfocus(NULL);
   1701 		return;
   1702 	}
   1703 	wlr_scene_node_raise_to_top(&c->tree->node);
   1704 	drawframe(c);
   1705 	cactivate(c, 1);
   1706 	if (c->typed >= c->total && !exclusive && !locked)
   1707 		kbfocus(csurface(c));
   1708 }
   1709 
   1710 static void
   1711 updatetitle(Client *c)
   1712 {
   1713 	const char *t = c->xdg ? c->xdg->title : c->xw ? c->xw->title : NULL;
   1714 
   1715 	snprintf(c->name, sizeof c->name, "%s", t ? t : "");
   1716 }
   1717 
   1718 /* sizes are whole character cells, like a terminal */
   1719 static void
   1720 resize(Client *c, int w, int h)
   1721 {
   1722 	w = MIN(MAX(w / cw, 10), (sw - c->x) / cw - 2) * cw;
   1723 	h = MIN(MAX(h / ch, 3), (wh - c->y) / ch - 2) * ch;
   1724 	if (w == c->w && h == c->h)
   1725 		return;
   1726 	c->w = w;
   1727 	c->h = h;
   1728 	cconfigure(c);
   1729 	place(c);
   1730 	drawframe(c);
   1731 }
   1732 
   1733 static void
   1734 move(Client *c, int x, int y)
   1735 {
   1736 	if (x == c->x && y == c->y)
   1737 		return;
   1738 	c->x = x;
   1739 	c->y = y;
   1740 	place(c);
   1741 	if (c->xw)
   1742 		cconfigure(c);
   1743 }
   1744 
   1745 static Rule *
   1746 findrule(Client *c)
   1747 {
   1748 	const char *a = c->xdg ? c->xdg->app_id : c->xw ? c->xw->class : NULL;
   1749 	const char *b = c->xw ? c->xw->instance : NULL;
   1750 	int i;
   1751 
   1752 	for (i = 0; i < nrules; i++)
   1753 		if ((a && !strcasecmp(a, rules[i].name)) || (b && !strcasecmp(b, rules[i].name)))
   1754 			return &rules[i];
   1755 	return NULL;
   1756 }
   1757 
   1758 static Client *
   1759 newclient(void)
   1760 {
   1761 	Client *c;
   1762 	int i;
   1763 
   1764 	if (!(c = calloc(1, sizeof *c)))
   1765 		die("calloc failed");
   1766 	c->kind = KClient;
   1767 	c->scr = cur;
   1768 	c->tree = wlr_scene_tree_create(wintree);
   1769 	c->tree->node.data = c;
   1770 	for (i = 0; i < 4; i++)
   1771 		c->edge[i] = wlr_scene_buffer_create(c->tree, NULL);
   1772 	c->back = wlr_scene_rect_create(c->tree, 1, 1, col[ColBg]);
   1773 	c->content = wlr_scene_tree_create(c->tree);
   1774 	wlr_scene_node_set_enabled(&c->tree->node, false);
   1775 	c->next = clients;
   1776 	clients = c;
   1777 	return c;
   1778 }
   1779 
   1780 static void
   1781 freeclient(Client *c)
   1782 {
   1783 	Client **pc;
   1784 
   1785 	for (pc = &clients; *pc != c; pc = &(*pc)->next);
   1786 	*pc = c->next;
   1787 	if (sel == c)
   1788 		sel = NULL;
   1789 	if (grabc == c)
   1790 		grab = GrabNone, grabc = NULL;
   1791 	wlr_scene_node_destroy(&c->tree->node);
   1792 	free(c);
   1793 }
   1794 
   1795 /* a window comes up: in the middle, its border typing in first */
   1796 static void
   1797 manage(Client *c)
   1798 {
   1799 	Rule *rule = findrule(c);
   1800 	int w, h;
   1801 
   1802 	c->mapped = 1;
   1803 	if (c->xdg) {
   1804 		w = c->xdg->base->geometry.width;
   1805 		h = c->xdg->base->geometry.height;
   1806 	} else {
   1807 		w = c->xw->width;
   1808 		h = c->xw->height;
   1809 	}
   1810 	if (w <= 0 || h <= 0)
   1811 		w = 640, h = 480;
   1812 	c->scr = rule && rule->scr >= 0 ? rule->scr : cur;
   1813 	c->typed = typing && !(rule && rule->full) ? 0 : INT32_MAX;
   1814 	c->born = ms();
   1815 	updatetitle(c);
   1816 	c->w = c->h = 0;
   1817 	c->x = MAX(0, (sw - w) / 2 - cw) / cw * cw;
   1818 	c->y = MAX(0, (wh - h) / 2 - ch) / ch * ch;
   1819 	resize(c, w, h);
   1820 	place(c);
   1821 	wlr_scene_node_set_enabled(&c->back->node, c->typed >= c->total);
   1822 	wlr_scene_node_set_enabled(&c->content->node, c->typed >= c->total);
   1823 	wlr_scene_node_set_enabled(&c->tree->node, c->scr == cur);
   1824 	if (c->typed < c->total)
   1825 		kick();
   1826 	if (c->scr == cur)
   1827 		focus(c);
   1828 	if ((rule && rule->full) || (c->xdg && c->xdg->requested.fullscreen) || (c->xw && c->xw->fullscreen))
   1829 		setfullscreen(c, 1);
   1830 }
   1831 
   1832 static void
   1833 unmanage(Client *c)
   1834 {
   1835 	if (grabc == c)
   1836 		grab = GrabNone, grabc = NULL;
   1837 	ghost(c);
   1838 	if (c->isfull) {
   1839 		c->isfull = 0;
   1840 		wlr_scene_node_reparent(&c->tree->node, wintree);
   1841 	}
   1842 	c->mapped = 0;
   1843 	wlr_scene_node_set_enabled(&c->tree->node, false);
   1844 	if (sel == c) {
   1845 		sel = NULL;
   1846 		focus(topclient());
   1847 	}
   1848 }
   1849 
   1850 /* asks first, like every window manager should */
   1851 static void
   1852 closeclient(Client *c)
   1853 {
   1854 	if (c->xdg)
   1855 		wlr_xdg_toplevel_send_close(c->xdg);
   1856 	else if (c->xw)
   1857 		wlr_xwayland_surface_close(c->xw);
   1858 }
   1859 
   1860 static void
   1861 setfullscreen(Client *c, int full)
   1862 {
   1863 	if (full == c->isfull || !c->mapped)
   1864 		return;
   1865 	if (c->typed < c->total) {
   1866 		c->typed = INT32_MAX;
   1867 		showcontent(c);
   1868 	}
   1869 	c->isfull = full;
   1870 	if (full) {
   1871 		c->oldx = c->x; c->oldy = c->y; c->oldw = c->w; c->oldh = c->h;
   1872 		/* over the bottom line too */
   1873 		wlr_scene_node_reparent(&c->tree->node, fulltree);
   1874 	} else {
   1875 		wlr_scene_node_reparent(&c->tree->node, wintree);
   1876 		c->x = c->oldx; c->y = c->oldy;
   1877 		c->w = c->h = 0;
   1878 		resize(c, c->oldw, c->oldh);
   1879 	}
   1880 	if (c->xdg && c->xdg->base->initialized)
   1881 		wlr_xdg_toplevel_set_fullscreen(c->xdg, full);
   1882 	else if (c->xw)
   1883 		wlr_xwayland_surface_set_fullscreen(c->xw, full);
   1884 	cconfigure(c);
   1885 	place(c);
   1886 	drawframe(c);
   1887 	wlr_scene_node_raise_to_top(&c->tree->node);
   1888 }
   1889 
   1890 /* super+arrows: half the screen, all of it, or back where it was */
   1891 static void
   1892 snap(Client *c, int how)
   1893 {
   1894 	int cols = sw / cw, rows = wh / ch, half = cols / 2;
   1895 
   1896 	if (c->isfull)
   1897 		return;
   1898 	if (how == ActRestore) {
   1899 		if (c->snapped) {
   1900 			move(c, c->sx, c->sy);
   1901 			resize(c, c->sw, c->sh);
   1902 		}
   1903 		c->snapped = 0;
   1904 		return;
   1905 	}
   1906 	if (!c->snapped) {
   1907 		c->sx = c->x; c->sy = c->y; c->sw = c->w; c->sh = c->h;
   1908 		c->snapped = 1;
   1909 	}
   1910 	if (how == ActLeft) {
   1911 		move(c, 0, 0);
   1912 		resize(c, (half - 2) * cw, (rows - 2) * ch);
   1913 	} else if (how == ActRight) {
   1914 		move(c, half * cw, 0);
   1915 		resize(c, (cols - half - 2) * cw, (rows - 2) * ch);
   1916 	} else {
   1917 		move(c, 0, 0);
   1918 		resize(c, (cols - 2) * cw, (rows - 2) * ch);
   1919 	}
   1920 }
   1921 
   1922 static void
   1923 startgrab(Client *c, int how)
   1924 {
   1925 	if (!c || c->isfull || !c->mapped)
   1926 		return;
   1927 	grab = how;
   1928 	grabc = c;
   1929 	gx = cursor->x;
   1930 	gy = cursor->y;
   1931 	gcx = c->x;
   1932 	gcy = c->y;
   1933 	gcw = c->w;
   1934 	gch = c->h;
   1935 	wlr_seat_pointer_clear_focus(seat);
   1936 	wlr_cursor_set_xcursor(cursor, xcm, how == GrabMove ? "grabbing" : "se-resize");
   1937 }
   1938 
   1939 /* ---- xdg windows: the wayland ones ---- */
   1940 
   1941 static void
   1942 xdgmap(struct wl_listener *l, void *data)
   1943 {
   1944 	Client *c = wl_container_of(l, c, map);
   1945 
   1946 	manage(c);
   1947 }
   1948 
   1949 static void
   1950 xdgunmap(struct wl_listener *l, void *data)
   1951 {
   1952 	Client *c = wl_container_of(l, c, unmap);
   1953 
   1954 	unmanage(c);
   1955 }
   1956 
   1957 static void
   1958 xdgcommit(struct wl_listener *l, void *data)
   1959 {
   1960 	Client *c = wl_container_of(l, c, commit);
   1961 	struct wlr_xdg_toplevel *t = c->xdg;
   1962 
   1963 	if (t->base->initial_commit) {
   1964 		if (wl_resource_get_version(t->resource) >= XDG_TOPLEVEL_WM_CAPABILITIES_SINCE_VERSION)
   1965 			wlr_xdg_toplevel_set_wm_capabilities(t, WLR_XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN
   1966 			                                     | WLR_XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE);
   1967 		/* square corners and no shadows: it's in a frame */
   1968 		if (wl_resource_get_version(t->resource) >= XDG_TOPLEVEL_STATE_TILED_LEFT_SINCE_VERSION)
   1969 			wlr_xdg_toplevel_set_tiled(t, WLR_EDGE_TOP|WLR_EDGE_BOTTOM|WLR_EDGE_LEFT|WLR_EDGE_RIGHT);
   1970 		if (c->deco)
   1971 			wlr_xdg_toplevel_decoration_v1_set_mode(c->deco, WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
   1972 		wlr_xdg_toplevel_set_size(t, 0, 0);
   1973 		return;
   1974 	}
   1975 	if (c->mapped)
   1976 		place(c);
   1977 }
   1978 
   1979 static void
   1980 xdgdestroy(struct wl_listener *l, void *data)
   1981 {
   1982 	Client *c = wl_container_of(l, c, destroy);
   1983 
   1984 	wl_list_remove(&c->map.link);
   1985 	wl_list_remove(&c->unmap.link);
   1986 	wl_list_remove(&c->commit.link);
   1987 	wl_list_remove(&c->destroy.link);
   1988 	wl_list_remove(&c->fullscreen.link);
   1989 	wl_list_remove(&c->maximize.link);
   1990 	wl_list_remove(&c->move.link);
   1991 	wl_list_remove(&c->resize.link);
   1992 	wl_list_remove(&c->title.link);
   1993 	if (c->deco) {
   1994 		wl_list_remove(&c->decomode.link);
   1995 		wl_list_remove(&c->decodestroy.link);
   1996 	}
   1997 	freeclient(c);
   1998 }
   1999 
   2000 static void
   2001 xdgfullscreen(struct wl_listener *l, void *data)
   2002 {
   2003 	Client *c = wl_container_of(l, c, fullscreen);
   2004 
   2005 	setfullscreen(c, c->xdg->requested.fullscreen);
   2006 	if (c->xdg->base->initialized)
   2007 		wlr_xdg_surface_schedule_configure(c->xdg->base);
   2008 }
   2009 
   2010 static void
   2011 xdgmaximize(struct wl_listener *l, void *data)
   2012 {
   2013 	Client *c = wl_container_of(l, c, maximize);
   2014 
   2015 	if (c->mapped)
   2016 		snap(c, c->snapped ? ActRestore : ActMax);
   2017 	if (c->xdg->base->initialized)
   2018 		wlr_xdg_surface_schedule_configure(c->xdg->base);
   2019 }
   2020 
   2021 static void
   2022 xdgmove(struct wl_listener *l, void *data)
   2023 {
   2024 	Client *c = wl_container_of(l, c, move);
   2025 
   2026 	startgrab(c, GrabMove);
   2027 }
   2028 
   2029 static void
   2030 xdgresize(struct wl_listener *l, void *data)
   2031 {
   2032 	Client *c = wl_container_of(l, c, resize);
   2033 
   2034 	startgrab(c, GrabResize);
   2035 }
   2036 
   2037 static void
   2038 settitle(struct wl_listener *l, void *data)
   2039 {
   2040 	Client *c = wl_container_of(l, c, title);
   2041 
   2042 	updatetitle(c);
   2043 	drawframe(c);
   2044 }
   2045 
   2046 static void
   2047 newtoplevel(struct wl_listener *l, void *data)
   2048 {
   2049 	struct wlr_xdg_toplevel *t = data;
   2050 	Client *c = newclient();
   2051 
   2052 	c->xdg = t;
   2053 	c->surf = wlr_scene_xdg_surface_create(c->content, t->base);
   2054 	t->base->data = c->surf;
   2055 	LISTEN(&t->base->surface->events.map, &c->map, xdgmap);
   2056 	LISTEN(&t->base->surface->events.unmap, &c->unmap, xdgunmap);
   2057 	LISTEN(&t->base->surface->events.commit, &c->commit, xdgcommit);
   2058 	LISTEN(&t->events.destroy, &c->destroy, xdgdestroy);
   2059 	LISTEN(&t->events.request_fullscreen, &c->fullscreen, xdgfullscreen);
   2060 	LISTEN(&t->events.request_maximize, &c->maximize, xdgmaximize);
   2061 	LISTEN(&t->events.request_move, &c->move, xdgmove);
   2062 	LISTEN(&t->events.request_resize, &c->resize, xdgresize);
   2063 	LISTEN(&t->events.set_title, &c->title, settitle);
   2064 }
   2065 
   2066 /* menus and such: kept on the screen */
   2067 static void
   2068 popupcommit(struct wl_listener *l, void *data)
   2069 {
   2070 	Popup *p = wl_container_of(l, p, commit);
   2071 	struct wlr_box box;
   2072 	int lx, ly;
   2073 
   2074 	if (!p->p->base->initial_commit)
   2075 		return;
   2076 	wlr_scene_node_coords(&p->parent->node, &lx, &ly);
   2077 	box = (struct wlr_box){ ox - lx, oy - ly, sw, sh };
   2078 	wlr_xdg_popup_unconstrain_from_box(p->p, &box);
   2079 	wlr_xdg_surface_schedule_configure(p->p->base);
   2080 }
   2081 
   2082 static void
   2083 popupdestroy(struct wl_listener *l, void *data)
   2084 {
   2085 	Popup *p = wl_container_of(l, p, destroy);
   2086 
   2087 	wl_list_remove(&p->commit.link);
   2088 	wl_list_remove(&p->destroy.link);
   2089 	free(p);
   2090 }
   2091 
   2092 static void
   2093 newpopup(struct wl_listener *l, void *data)
   2094 {
   2095 	struct wlr_xdg_popup *xp = data;
   2096 	struct wlr_xdg_surface *xs;
   2097 	struct wlr_layer_surface_v1 *ls;
   2098 	struct wlr_scene_tree *parent = NULL;
   2099 	Popup *p;
   2100 
   2101 	if (!xp->parent)
   2102 		return;
   2103 	if ((xs = wlr_xdg_surface_try_from_wlr_surface(xp->parent)))
   2104 		parent = xs->data;
   2105 	else if ((ls = wlr_layer_surface_v1_try_from_wlr_surface(xp->parent)))
   2106 		parent = ls->data;
   2107 	if (!parent || !(p = calloc(1, sizeof *p)))
   2108 		return;
   2109 	p->p = xp;
   2110 	p->parent = parent;
   2111 	xp->base->data = wlr_scene_xdg_surface_create(parent, xp->base);
   2112 	LISTEN(&xp->base->surface->events.commit, &p->commit, popupcommit);
   2113 	LISTEN(&xp->events.destroy, &p->destroy, popupdestroy);
   2114 }
   2115 
   2116 /* we draw the frames: programs that can leave theirs out, should */
   2117 static void
   2118 decomode(struct wl_listener *l, void *data)
   2119 {
   2120 	Client *c = wl_container_of(l, c, decomode);
   2121 
   2122 	if (c->xdg->base->initialized)
   2123 		wlr_xdg_toplevel_decoration_v1_set_mode(c->deco, WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
   2124 }
   2125 
   2126 static void
   2127 decodestroy(struct wl_listener *l, void *data)
   2128 {
   2129 	Client *c = wl_container_of(l, c, decodestroy);
   2130 
   2131 	wl_list_remove(&c->decomode.link);
   2132 	wl_list_remove(&c->decodestroy.link);
   2133 	c->deco = NULL;
   2134 }
   2135 
   2136 static void
   2137 newdeco(struct wl_listener *l, void *data)
   2138 {
   2139 	struct wlr_xdg_toplevel_decoration_v1 *d = data;
   2140 	Client *c;
   2141 
   2142 	for (c = clients; c && c->xdg != d->toplevel; c = c->next);
   2143 	if (!c || c->deco)
   2144 		return;
   2145 	c->deco = d;
   2146 	LISTEN(&d->events.request_mode, &c->decomode, decomode);
   2147 	LISTEN(&d->events.destroy, &c->decodestroy, decodestroy);
   2148 	decomode(&c->decomode, d);
   2149 }
   2150 
   2151 /* ---- x11 windows, through xwayland ---- */
   2152 
   2153 static void
   2154 xwmap(struct wl_listener *l, void *data)
   2155 {
   2156 	Client *c = wl_container_of(l, c, map);
   2157 	struct wlr_xwayland_surface *xs = c->xw;
   2158 	int i;
   2159 
   2160 	c->surf = wlr_scene_subsurface_tree_create(c->content, xs->surface);
   2161 	c->unmanaged = xs->override_redirect;
   2162 	if (!c->unmanaged) {
   2163 		manage(c);
   2164 		return;
   2165 	}
   2166 	/* menus and tooltips: where they say, no frame */
   2167 	c->mapped = 1;
   2168 	wlr_scene_node_reparent(&c->tree->node, ortree);
   2169 	for (i = 0; i < 4; i++)
   2170 		wlr_scene_node_set_enabled(&c->edge[i]->node, false);
   2171 	wlr_scene_node_set_enabled(&c->back->node, false);
   2172 	wlr_scene_node_set_position(&c->content->node, 0, 0);
   2173 	wlr_scene_node_set_position(&c->tree->node, xs->x, xs->y);
   2174 	wlr_scene_node_set_enabled(&c->tree->node, true);
   2175 	if (wlr_xwayland_surface_override_redirect_wants_focus(xs))
   2176 		kbfocus(xs->surface);
   2177 }
   2178 
   2179 static void
   2180 xwunmap(struct wl_listener *l, void *data)
   2181 {
   2182 	Client *c = wl_container_of(l, c, unmap);
   2183 
   2184 	if (c->unmanaged) {
   2185 		c->mapped = 0;
   2186 		wlr_scene_node_set_enabled(&c->tree->node, false);
   2187 		if (seat->keyboard_state.focused_surface == c->xw->surface)
   2188 			focus(sel);
   2189 	} else
   2190 		unmanage(c);
   2191 	if (c->surf) {
   2192 		wlr_scene_node_destroy(&c->surf->node);
   2193 		c->surf = NULL;
   2194 	}
   2195 	wlr_scene_node_reparent(&c->tree->node, wintree);
   2196 }
   2197 
   2198 static void
   2199 xwassociate(struct wl_listener *l, void *data)
   2200 {
   2201 	Client *c = wl_container_of(l, c, associate);
   2202 
   2203 	LISTEN(&c->xw->surface->events.map, &c->map, xwmap);
   2204 	LISTEN(&c->xw->surface->events.unmap, &c->unmap, xwunmap);
   2205 	c->assoc = 1;
   2206 }
   2207 
   2208 static void
   2209 xwdissociate(struct wl_listener *l, void *data)
   2210 {
   2211 	Client *c = wl_container_of(l, c, dissociate);
   2212 
   2213 	wl_list_remove(&c->map.link);
   2214 	wl_list_remove(&c->unmap.link);
   2215 	c->assoc = 0;
   2216 }
   2217 
   2218 static void
   2219 xwdestroy(struct wl_listener *l, void *data)
   2220 {
   2221 	Client *c = wl_container_of(l, c, destroy);
   2222 
   2223 	if (c->assoc) {
   2224 		wl_list_remove(&c->map.link);
   2225 		wl_list_remove(&c->unmap.link);
   2226 	}
   2227 	wl_list_remove(&c->associate.link);
   2228 	wl_list_remove(&c->dissociate.link);
   2229 	wl_list_remove(&c->destroy.link);
   2230 	wl_list_remove(&c->configure.link);
   2231 	wl_list_remove(&c->fullscreen.link);
   2232 	wl_list_remove(&c->activate.link);
   2233 	wl_list_remove(&c->title.link);
   2234 	wl_list_remove(&c->geom.link);
   2235 	freeclient(c);
   2236 }
   2237 
   2238 static void
   2239 xwconfigure(struct wl_listener *l, void *data)
   2240 {
   2241 	Client *c = wl_container_of(l, c, configure);
   2242 	struct wlr_xwayland_surface_configure_event *e = data;
   2243 
   2244 	if (!c->mapped || c->unmanaged) {
   2245 		wlr_xwayland_surface_configure(c->xw, e->x, e->y, e->width, e->height);
   2246 		return;
   2247 	}
   2248 	if (c->isfull || (e->width / cw * cw == c->w && e->height / ch * ch == c->h))
   2249 		cconfigure(c);
   2250 	else
   2251 		resize(c, e->width, e->height);
   2252 }
   2253 
   2254 static void
   2255 xwfullscreen(struct wl_listener *l, void *data)
   2256 {
   2257 	Client *c = wl_container_of(l, c, fullscreen);
   2258 
   2259 	setfullscreen(c, c->xw->fullscreen);
   2260 }
   2261 
   2262 static void
   2263 xwactivate(struct wl_listener *l, void *data)
   2264 {
   2265 	Client *c = wl_container_of(l, c, activate);
   2266 
   2267 	if (c->mapped && !c->unmanaged && c->scr == cur)
   2268 		focus(c);
   2269 }
   2270 
   2271 static void
   2272 xwgeom(struct wl_listener *l, void *data)
   2273 {
   2274 	Client *c = wl_container_of(l, c, geom);
   2275 
   2276 	if (c->mapped && c->unmanaged)
   2277 		wlr_scene_node_set_position(&c->tree->node, c->xw->x, c->xw->y);
   2278 }
   2279 
   2280 static void
   2281 newxw(struct wl_listener *l, void *data)
   2282 {
   2283 	struct wlr_xwayland_surface *xs = data;
   2284 	Client *c = newclient();
   2285 
   2286 	c->xw = xs;
   2287 	xs->data = c;
   2288 	LISTEN(&xs->events.associate, &c->associate, xwassociate);
   2289 	LISTEN(&xs->events.dissociate, &c->dissociate, xwdissociate);
   2290 	LISTEN(&xs->events.destroy, &c->destroy, xwdestroy);
   2291 	LISTEN(&xs->events.request_configure, &c->configure, xwconfigure);
   2292 	LISTEN(&xs->events.request_fullscreen, &c->fullscreen, xwfullscreen);
   2293 	LISTEN(&xs->events.request_activate, &c->activate, xwactivate);
   2294 	LISTEN(&xs->events.set_title, &c->title, settitle);
   2295 	LISTEN(&xs->events.set_geometry, &c->geom, xwgeom);
   2296 }
   2297 
   2298 static void
   2299 xwready(struct wl_listener *l, void *data)
   2300 {
   2301 	wlr_xwayland_set_seat(xwayland, seat);
   2302 }
   2303 
   2304 /* ---- layer surfaces: the apps menu, wallpaper programs, bars ---- */
   2305 
   2306 static void
   2307 arrangelayers(void)
   2308 {
   2309 	struct wlr_box full = { ox, oy, sw, sh }, usable = full;
   2310 	Layer *ly;
   2311 	int i;
   2312 
   2313 	for (i = 3; i >= 0; i--)
   2314 		for (ly = layersurfs; ly; ly = ly->next)
   2315 			if (ly->ls->initialized && (int)ly->ls->current.layer == i)
   2316 				wlr_scene_layer_surface_v1_configure(ly->scene, &full, &usable);
   2317 }
   2318 
   2319 static void
   2320 layermap(struct wl_listener *l, void *data)
   2321 {
   2322 	Layer *ly = wl_container_of(l, ly, map);
   2323 
   2324 	if (ly->ls->current.keyboard_interactive && ly->ls->current.layer >= ZWLR_LAYER_SHELL_V1_LAYER_TOP && !locked) {
   2325 		exclusive = ly;
   2326 		kbfocus(ly->ls->surface);
   2327 	}
   2328 	arrangelayers();
   2329 }
   2330 
   2331 static void
   2332 layerunmap(struct wl_listener *l, void *data)
   2333 {
   2334 	Layer *ly = wl_container_of(l, ly, unmap);
   2335 
   2336 	if (exclusive == ly) {
   2337 		exclusive = NULL;
   2338 		focus(sel);
   2339 	}
   2340 }
   2341 
   2342 static void
   2343 layercommit(struct wl_listener *l, void *data)
   2344 {
   2345 	Layer *ly = wl_container_of(l, ly, commit);
   2346 
   2347 	if (ly->ls->initial_commit || ly->ls->current.committed) {
   2348 		wlr_scene_node_reparent(&ly->scene->tree->node, layers[ly->ls->current.layer]);
   2349 		arrangelayers();
   2350 	}
   2351 }
   2352 
   2353 static void
   2354 layerdestroy(struct wl_listener *l, void *data)
   2355 {
   2356 	Layer *ly = wl_container_of(l, ly, destroy), **pl;
   2357 
   2358 	wl_list_remove(&ly->map.link);
   2359 	wl_list_remove(&ly->unmap.link);
   2360 	wl_list_remove(&ly->commit.link);
   2361 	wl_list_remove(&ly->destroy.link);
   2362 	for (pl = &layersurfs; *pl != ly; pl = &(*pl)->next);
   2363 	*pl = ly->next;
   2364 	if (exclusive == ly) {
   2365 		exclusive = NULL;
   2366 		focus(sel);
   2367 	}
   2368 	free(ly);
   2369 }
   2370 
   2371 static void
   2372 newlayer(struct wl_listener *l, void *data)
   2373 {
   2374 	struct wlr_layer_surface_v1 *ls = data;
   2375 	Layer *ly;
   2376 
   2377 	if (!ls->output) {
   2378 		if (!outputs) {
   2379 			wlr_layer_surface_v1_destroy(ls);
   2380 			return;
   2381 		}
   2382 		ls->output = outputs->wlr;
   2383 	}
   2384 	if (!(ly = calloc(1, sizeof *ly)))
   2385 		return;
   2386 	ly->kind = KLayer;
   2387 	ly->ls = ls;
   2388 	ly->scene = wlr_scene_layer_surface_v1_create(layers[ls->pending.layer], ls);
   2389 	ly->scene->tree->node.data = ly;
   2390 	ls->data = ly->scene->tree;
   2391 	LISTEN(&ls->surface->events.map, &ly->map, layermap);
   2392 	LISTEN(&ls->surface->events.unmap, &ly->unmap, layerunmap);
   2393 	LISTEN(&ls->surface->events.commit, &ly->commit, layercommit);
   2394 	LISTEN(&ls->events.destroy, &ly->destroy, layerdestroy);
   2395 	ly->next = layersurfs;
   2396 	layersurfs = ly;
   2397 }
   2398 
   2399 /* ---- the lock screen: a login prompt, checked by pam like a real one ---- */
   2400 
   2401 static int
   2402 conv(int n, const struct pam_message **msg, struct pam_response **resp, void *pw)
   2403 {
   2404 	int i;
   2405 
   2406 	if (!(*resp = calloc(n, sizeof **resp)))
   2407 		return PAM_BUF_ERR;
   2408 	for (i = 0; i < n; i++)
   2409 		if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF || msg[i]->msg_style == PAM_PROMPT_ECHO_ON)
   2410 			(*resp)[i].resp = strdup(pw);
   2411 	return PAM_SUCCESS;
   2412 }
   2413 
   2414 static int
   2415 checkpassword(const char *user, const char *pw)
   2416 {
   2417 	struct pam_conv pc = { conv, (void *)pw };
   2418 	pam_handle_t *ph;
   2419 	int r;
   2420 
   2421 	if (pam_start("system-local-login", user, &pc, &ph) != PAM_SUCCESS)
   2422 		return 0;
   2423 	r = pam_authenticate(ph, 0);
   2424 	pam_end(ph, r);
   2425 	return r == PAM_SUCCESS;
   2426 }
   2427 
   2428 static void
   2429 drawlock(void)
   2430 {
   2431 	char host[64] = "", line[256], *user = getenv("USER");
   2432 	cairo_t *cr;
   2433 	Buf *b;
   2434 
   2435 	if (!sw)
   2436 		return;
   2437 	gethostname(host, sizeof host);
   2438 	b = newbuf(sw, 6 * ch, &cr);
   2439 	fill(cr, ColBg, 0, 0, sw, 6 * ch);
   2440 	snprintf(line, sizeof line, "Chamesle Linux (tty%d)", cur + 1);
   2441 	text(cr, ColBar, 0, 0, line);
   2442 	snprintf(line, sizeof line, "%s login: %s", host, user ? user : "");
   2443 	text(cr, ColBar, 0, 2 * ch, line);
   2444 	text(cr, ColBar, 0, 3 * ch, "Password: ");
   2445 	if (lockwrong)
   2446 		text(cr, ColBar, 0, 5 * ch, "Login incorrect");
   2447 	putbuf(lockbuf, b, cr);
   2448 	wlr_scene_node_set_position(&lockbuf->node, ox, oy);
   2449 }
   2450 
   2451 static void
   2452 lock(void)
   2453 {
   2454 	if (locked)
   2455 		return;
   2456 	locked = 1;
   2457 	locklen = lockwrong = 0;
   2458 	grab = GrabNone;
   2459 	grabc = NULL;
   2460 	wlr_seat_keyboard_notify_clear_focus(seat);
   2461 	wlr_seat_pointer_clear_focus(seat);
   2462 	wlr_scene_node_set_enabled(&locktree->node, true);
   2463 	drawlock();
   2464 }
   2465 
   2466 static void
   2467 lockkey(struct wlr_keyboard *kb, uint32_t code)
   2468 {
   2469 	xkb_keysym_t sym = xkb_state_key_get_one_sym(kb->xkb_state, code);
   2470 	char buf[8], *user = getenv("USER");
   2471 	int len;
   2472 
   2473 	if (sym == XKB_KEY_Return || sym == XKB_KEY_KP_Enter) {
   2474 		lockpw[locklen] = '\0';
   2475 		if (user && checkpassword(user, lockpw)) {
   2476 			memset(lockpw, 0, sizeof lockpw);
   2477 			locked = 0;
   2478 			wlr_scene_node_set_enabled(&locktree->node, false);
   2479 			focus(sel);
   2480 			return;
   2481 		}
   2482 		memset(lockpw, 0, sizeof lockpw);
   2483 		lockwrong = 1;
   2484 		locklen = 0;
   2485 		drawlock();
   2486 	} else if (sym == XKB_KEY_BackSpace) {
   2487 		while (locklen && (lockpw[--locklen] & 0xc0) == 0x80);
   2488 	} else if (sym == XKB_KEY_Escape)
   2489 		locklen = 0;
   2490 	else if ((len = xkb_state_key_get_utf8(kb->xkb_state, code, buf, sizeof buf)) > 0
   2491 	&& !iscntrl((unsigned char)buf[0]) && locklen + len < (int)sizeof lockpw - 1) {
   2492 		memcpy(lockpw + locklen, buf, len);
   2493 		locklen += len;
   2494 	}
   2495 }
   2496 
   2497 /* ---- what keys and clicks do ---- */
   2498 
   2499 static void
   2500 view(int n)
   2501 {
   2502 	Client *c;
   2503 
   2504 	if (n == cur)
   2505 		return;
   2506 	cur = n;
   2507 	for (c = clients; c; c = c->next)
   2508 		if (c->mapped && !c->unmanaged)
   2509 			wlr_scene_node_set_enabled(&c->tree->node, c->scr == cur);
   2510 	drawbar();
   2511 	focus(topclient());
   2512 }
   2513 
   2514 static void
   2515 sendto(int n)
   2516 {
   2517 	if (!sel || n == cur)
   2518 		return;
   2519 	sel->scr = n;
   2520 	wlr_scene_node_set_enabled(&sel->tree->node, false);
   2521 	focus(topclient());
   2522 	if (sel && sel->scr != cur)
   2523 		sel = NULL;
   2524 }
   2525 
   2526 static void
   2527 focusnext(void)
   2528 {
   2529 	Client *c = sel ? sel->next : clients;
   2530 
   2531 	for (; c && (!c->mapped || c->unmanaged || c->scr != cur); c = c->next);
   2532 	focus(c);
   2533 }
   2534 
   2535 /* foot takes the program as it is, xterm and the rest after -e */
   2536 static void
   2537 interm(const char *prog)
   2538 {
   2539 	char cmd[512];
   2540 
   2541 	if (!strncmp(terminal, "foot", 4))
   2542 		snprintf(cmd, sizeof cmd, "%s %s", terminal, prog);
   2543 	else
   2544 		snprintf(cmd, sizeof cmd, "%s -e %s", terminal, prog);
   2545 	run(cmd);
   2546 }
   2547 
   2548 static void
   2549 doaction(Key *k)
   2550 {
   2551 	switch (k->act) {
   2552 	case ActRun:      run(k->cmd); break;
   2553 	case ActTerminal: run(terminal); break;
   2554 	case ActMenu:     run(menu); break;
   2555 	case ActClose:    if (sel) closeclient(sel); break;
   2556 	case ActNext:     focusnext(); break;
   2557 	case ActFull:     if (sel) setfullscreen(sel, !sel->isfull); break;
   2558 	case ActQuit:     wl_display_terminate(dpy); break;
   2559 	case ActView:     view(k->n); break;
   2560 	case ActSend:     sendto(k->n); break;
   2561 	case ActVolUp:    setvolume("5%+"); break;
   2562 	case ActVolDown:  setvolume("5%-"); break;
   2563 	case ActMute:     setvolume("mute"); break;
   2564 	case ActLightUp:  setlight(5); drawbar(); break;
   2565 	case ActLightDown: setlight(-5); drawbar(); break;
   2566 	case ActLeft: case ActRight: case ActMax: case ActRestore:
   2567 		if (sel)
   2568 			snap(sel, k->act);
   2569 		break;
   2570 	case ActLock:     lock(); break;
   2571 	}
   2572 }
   2573 
   2574 static int
   2575 segat(int x)
   2576 {
   2577 	int i;
   2578 
   2579 	for (i = 0; i < nsegs; i++)
   2580 		if (x >= segs[i].x0 && x < segs[i].x1)
   2581 			return segs[i].seg;
   2582 	return SegNone;
   2583 }
   2584 
   2585 static void
   2586 barclick(int x, uint32_t button)
   2587 {
   2588 	int s = segat(x);
   2589 
   2590 	if (button != BTN_LEFT)
   2591 		return;
   2592 	if (s == SegVol)
   2593 		setvolume("mute");
   2594 	else if (s == SegNet)
   2595 		interm("nmtui");
   2596 }
   2597 
   2598 /* up or down on the volume or the brightness */
   2599 static void
   2600 barscroll(int x, int up)
   2601 {
   2602 	int s = segat(x);
   2603 
   2604 	if (s == SegVol)
   2605 		setvolume(up ? "5%+" : "5%-");
   2606 	else if (s == SegLight) {
   2607 		setlight(up ? 5 : -5);
   2608 		drawbar();
   2609 	}
   2610 }
   2611 
   2612 /* ---- input ---- */
   2613 
   2614 /* what's at a point: a client, layer, notification or the bar, and the surface there if there is one */
   2615 static void *
   2616 objat(double lx, double ly, struct wlr_surface **surf, double *sx, double *sy)
   2617 {
   2618 	struct wlr_scene_node *n = wlr_scene_node_at(&scene->tree.node, lx, ly, sx, sy);
   2619 	struct wlr_scene_buffer *b;
   2620 	struct wlr_scene_surface *ss;
   2621 
   2622 	*surf = NULL;
   2623 	if (!n)
   2624 		return NULL;
   2625 	if (n->type == WLR_SCENE_NODE_BUFFER && (b = wlr_scene_buffer_from_node(n))
   2626 	&& (ss = wlr_scene_surface_try_from_buffer(b)))
   2627 		*surf = ss->surface;
   2628 	for (; n; n = n->parent ? &n->parent->node : NULL)
   2629 		if (n->data)
   2630 			return n->data;
   2631 	return NULL;
   2632 }
   2633 
   2634 static void
   2635 motion(uint32_t time)
   2636 {
   2637 	struct wlr_surface *s;
   2638 	double sx, sy;
   2639 
   2640 	wlr_idle_notifier_v1_notify_activity(idle, seat);
   2641 	if (grab == GrabMove) {
   2642 		/* a cell at a time, like everything else */
   2643 		move(grabc, gcx + (int)(cursor->x - gx) / cw * cw, gcy + (int)(cursor->y - gy) / ch * ch);
   2644 		return;
   2645 	}
   2646 	if (grab == GrabResize) {
   2647 		resize(grabc, gcw + cursor->x - gx, gch + cursor->y - gy);
   2648 		return;
   2649 	}
   2650 	if (locked)
   2651 		return;
   2652 	objat(cursor->x, cursor->y, &s, &sx, &sy);
   2653 	if (!s) {
   2654 		wlr_cursor_set_xcursor(cursor, xcm, "default");
   2655 		wlr_seat_pointer_clear_focus(seat);
   2656 		return;
   2657 	}
   2658 	wlr_seat_pointer_notify_enter(seat, s, sx, sy);
   2659 	wlr_seat_pointer_notify_motion(seat, time, sx, sy);
   2660 }
   2661 
   2662 static void
   2663 cmotion(struct wl_listener *l, void *data)
   2664 {
   2665 	struct wlr_pointer_motion_event *e = data;
   2666 
   2667 	wlr_cursor_move(cursor, &e->pointer->base, e->delta_x, e->delta_y);
   2668 	motion(e->time_msec);
   2669 }
   2670 
   2671 static void
   2672 cmotionabs(struct wl_listener *l, void *data)
   2673 {
   2674 	struct wlr_pointer_motion_absolute_event *e = data;
   2675 
   2676 	wlr_cursor_warp_absolute(cursor, &e->pointer->base, e->x, e->y);
   2677 	motion(e->time_msec);
   2678 }
   2679 
   2680 static void
   2681 cbutton(struct wl_listener *l, void *data)
   2682 {
   2683 	struct wlr_pointer_button_event *e = data;
   2684 	struct wlr_keyboard *kb = wlr_seat_get_keyboard(seat);
   2685 	struct wlr_surface *s;
   2686 	double sx, sy;
   2687 	void *o;
   2688 	Client *c;
   2689 	Layer *ly;
   2690 	uint32_t mods = kb ? wlr_keyboard_get_modifiers(kb) : 0;
   2691 	int x, y, cols;
   2692 
   2693 	wlr_idle_notifier_v1_notify_activity(idle, seat);
   2694 	if (e->state == WL_POINTER_BUTTON_STATE_RELEASED) {
   2695 		if (grab) {
   2696 			grab = GrabNone;
   2697 			grabc = NULL;
   2698 			wlr_cursor_set_xcursor(cursor, xcm, "default");
   2699 			return;
   2700 		}
   2701 		if (!locked)
   2702 			wlr_seat_pointer_notify_button(seat, e->time_msec, e->button, e->state);
   2703 		return;
   2704 	}
   2705 	if (locked)
   2706 		return;
   2707 	o = objat(cursor->x, cursor->y, &s, &sx, &sy);
   2708 	if (o == &barkind) {
   2709 		barclick(cursor->x - ox, e->button);
   2710 		return;
   2711 	}
   2712 	if (o && *(int *)o == KNotif) {
   2713 		closenotif(o, 2);
   2714 		return;
   2715 	}
   2716 	if (o && *(int *)o == KLayer) {
   2717 		ly = o;
   2718 		if (ly->ls->current.keyboard_interactive)
   2719 			kbfocus(ly->ls->surface);
   2720 		goto pass;
   2721 	}
   2722 	if (!o) {
   2723 		focus(NULL);
   2724 		goto pass;
   2725 	}
   2726 	c = o;
   2727 	if (c->unmanaged)
   2728 		goto pass;
   2729 	focus(c);
   2730 	if (s) {
   2731 		if (CLEANMASK(mods) == SUPER && (e->button == BTN_LEFT || e->button == BTN_RIGHT)) {
   2732 			startgrab(c, e->button == BTN_RIGHT ? GrabResize : GrabMove);
   2733 			return;
   2734 		}
   2735 		goto pass;
   2736 	}
   2737 	if (c->isfull)
   2738 		goto pass;
   2739 	/* the frame: [x] closes, the title moves, the bottom right corner resizes */
   2740 	x = cursor->x - ox - c->x;
   2741 	y = cursor->y - oy - c->y;
   2742 	cols = c->w / cw + 2;
   2743 	if (y < ch && x >= (cols - 4) * cw)
   2744 		closeclient(c);
   2745 	else if (y < ch)
   2746 		startgrab(c, GrabMove);
   2747 	else if (y >= c->h + ch && x >= (cols - 2) * cw)
   2748 		startgrab(c, GrabResize);
   2749 	return;
   2750 pass:
   2751 	wlr_seat_pointer_notify_button(seat, e->time_msec, e->button, e->state);
   2752 }
   2753 
   2754 static void
   2755 caxis(struct wl_listener *l, void *data)
   2756 {
   2757 	static double acc;
   2758 	struct wlr_pointer_axis_event *e = data;
   2759 	struct wlr_surface *s;
   2760 	double sx, sy;
   2761 
   2762 	if (locked)
   2763 		return;
   2764 	if (objat(cursor->x, cursor->y, &s, &sx, &sy) == &barkind) {
   2765 		if (e->orientation != WL_POINTER_AXIS_VERTICAL_SCROLL)
   2766 			return;
   2767 		/* a wheel click is a step; a touchpad, every so far */
   2768 		acc += e->delta;
   2769 		if (e->delta_discrete || acc <= -15 || acc >= 15) {
   2770 			barscroll(cursor->x - ox, acc < 0);
   2771 			acc = 0;
   2772 		}
   2773 		return;
   2774 	}
   2775 	wlr_seat_pointer_notify_axis(seat, e->time_msec, e->orientation, e->delta, e->delta_discrete,
   2776 	                             e->source, e->relative_direction);
   2777 }
   2778 
   2779 static void
   2780 cframe(struct wl_listener *l, void *data)
   2781 {
   2782 	wlr_seat_pointer_notify_frame(seat);
   2783 }
   2784 
   2785 static void
   2786 setkeymap(struct wlr_keyboard *kb)
   2787 {
   2788 	struct xkb_rule_names rn = { 0 };
   2789 	struct xkb_context *ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
   2790 	struct xkb_keymap *km;
   2791 
   2792 	rn.layout = kblayout[0] ? kblayout : NULL;
   2793 	rn.variant = kbvariant[0] ? kbvariant : NULL;
   2794 	if (!(km = xkb_keymap_new_from_names(ctx, &rn, XKB_KEYMAP_COMPILE_NO_FLAGS))) {
   2795 		fprintf(stderr, "torrent: no keyboard layout '%s', using the default\n", kblayout);
   2796 		rn.layout = rn.variant = NULL;
   2797 		km = xkb_keymap_new_from_names(ctx, &rn, XKB_KEYMAP_COMPILE_NO_FLAGS);
   2798 	}
   2799 	if (km) {
   2800 		wlr_keyboard_set_keymap(kb, km);
   2801 		xkb_keymap_unref(km);
   2802 	}
   2803 	xkb_context_unref(ctx);
   2804 }
   2805 
   2806 static void
   2807 keykey(struct wl_listener *l, void *data)
   2808 {
   2809 	Kbd *k = wl_container_of(l, k, key);
   2810 	struct wlr_keyboard_key_event *e = data;
   2811 	uint32_t code = e->keycode + 8, mods = wlr_keyboard_get_modifiers(k->wlr);
   2812 	const xkb_keysym_t *syms;
   2813 	xkb_layout_index_t lay;
   2814 	int n, i, j, done = 0;
   2815 
   2816 	wlr_idle_notifier_v1_notify_activity(idle, seat);
   2817 	if (e->state == WL_KEYBOARD_KEY_STATE_PRESSED) {
   2818 		/* ctrl+alt+f1: the consoles, like everywhere else */
   2819 		n = xkb_state_key_get_syms(k->wlr->xkb_state, code, &syms);
   2820 		for (i = 0; i < n; i++)
   2821 			if (syms[i] >= XKB_KEY_XF86Switch_VT_1 && syms[i] <= XKB_KEY_XF86Switch_VT_12) {
   2822 				if (session)
   2823 					wlr_session_change_vt(session, syms[i] - XKB_KEY_XF86Switch_VT_1 + 1);
   2824 				return;
   2825 			}
   2826 		if (locked) {
   2827 			lockkey(k->wlr, code);
   2828 			return;
   2829 		}
   2830 		/* the key as it is without shift, like super+shift+1 */
   2831 		lay = xkb_state_key_get_layout(k->wlr->xkb_state, code);
   2832 		n = xkb_keymap_key_get_syms_by_level(k->wlr->keymap, code, lay == XKB_LAYOUT_INVALID ? 0 : lay, 0, &syms);
   2833 		for (i = 0; i < n && !done; i++)
   2834 			for (j = 0; j < nkeys; j++)
   2835 				if (syms[i] == keys[j].keysym && CLEANMASK(keys[j].mod) == CLEANMASK(mods)) {
   2836 					doaction(&keys[j]);
   2837 					done = 1;
   2838 					break;
   2839 				}
   2840 	} else if (locked)
   2841 		return;
   2842 	if (!done) {
   2843 		wlr_seat_set_keyboard(seat, k->wlr);
   2844 		wlr_seat_keyboard_notify_key(seat, e->time_msec, e->keycode, e->state);
   2845 	}
   2846 }
   2847 
   2848 static void
   2849 keymods(struct wl_listener *l, void *data)
   2850 {
   2851 	Kbd *k = wl_container_of(l, k, mods);
   2852 
   2853 	wlr_seat_set_keyboard(seat, k->wlr);
   2854 	wlr_seat_keyboard_notify_modifiers(seat, &k->wlr->modifiers);
   2855 }
   2856 
   2857 static void
   2858 keydestroy(struct wl_listener *l, void *data)
   2859 {
   2860 	Kbd *k = wl_container_of(l, k, destroy), **pk;
   2861 
   2862 	wl_list_remove(&k->key.link);
   2863 	wl_list_remove(&k->mods.link);
   2864 	wl_list_remove(&k->destroy.link);
   2865 	for (pk = &kbds; *pk != k; pk = &(*pk)->next);
   2866 	*pk = k->next;
   2867 	free(k);
   2868 }
   2869 
   2870 static void
   2871 newinput(struct wl_listener *l, void *data)
   2872 {
   2873 	struct wlr_input_device *d = data;
   2874 	struct libinput_device *li;
   2875 	Kbd *k;
   2876 
   2877 	if (d->type == WLR_INPUT_DEVICE_KEYBOARD && (k = calloc(1, sizeof *k))) {
   2878 		k->wlr = wlr_keyboard_from_input_device(d);
   2879 		setkeymap(k->wlr);
   2880 		wlr_keyboard_set_repeat_info(k->wlr, 25, 600);
   2881 		LISTEN(&k->wlr->events.key, &k->key, keykey);
   2882 		LISTEN(&k->wlr->events.modifiers, &k->mods, keymods);
   2883 		LISTEN(&d->events.destroy, &k->destroy, keydestroy);
   2884 		wlr_seat_set_keyboard(seat, k->wlr);
   2885 		k->next = kbds;
   2886 		kbds = k;
   2887 	} else if (d->type == WLR_INPUT_DEVICE_POINTER) {
   2888 		if (wlr_input_device_is_libinput(d) && (li = wlr_libinput_get_device_handle(d))) {
   2889 			if (libinput_device_config_tap_get_finger_count(li))
   2890 				libinput_device_config_tap_set_enabled(li, tapclick ? LIBINPUT_CONFIG_TAP_ENABLED
   2891 				                                                    : LIBINPUT_CONFIG_TAP_DISABLED);
   2892 			if (libinput_device_config_scroll_has_natural_scroll(li))
   2893 				libinput_device_config_scroll_set_natural_scroll_enabled(li, natural);
   2894 		}
   2895 		wlr_cursor_attach_input_device(cursor, d);
   2896 	}
   2897 	wlr_seat_set_capabilities(seat, WL_SEAT_CAPABILITY_POINTER | (kbds ? WL_SEAT_CAPABILITY_KEYBOARD : 0));
   2898 }
   2899 
   2900 static void
   2901 setcursor(struct wl_listener *l, void *data)
   2902 {
   2903 	struct wlr_seat_pointer_request_set_cursor_event *e = data;
   2904 
   2905 	if (!grab && e->seat_client == seat->pointer_state.focused_client)
   2906 		wlr_cursor_set_surface(cursor, e->surface, e->hotspot_x, e->hotspot_y);
   2907 }
   2908 
   2909 static void
   2910 setshape(struct wl_listener *l, void *data)
   2911 {
   2912 	struct wlr_cursor_shape_manager_v1_request_set_shape_event *e = data;
   2913 
   2914 	if (!grab && e->seat_client == seat->pointer_state.focused_client)
   2915 		wlr_cursor_set_xcursor(cursor, xcm, wlr_cursor_shape_v1_name(e->shape));
   2916 }
   2917 
   2918 static void
   2919 setsel(struct wl_listener *l, void *data)
   2920 {
   2921 	struct wlr_seat_request_set_selection_event *e = data;
   2922 
   2923 	wlr_seat_set_selection(seat, e->source, e->serial);
   2924 }
   2925 
   2926 static void
   2927 setpsel(struct wl_listener *l, void *data)
   2928 {
   2929 	struct wlr_seat_request_set_primary_selection_event *e = data;
   2930 
   2931 	wlr_seat_set_primary_selection(seat, e->source, e->serial);
   2932 }
   2933 
   2934 /* a program wants a window of its to the front, like a browser opening a link */
   2935 static void
   2936 activate(struct wl_listener *l, void *data)
   2937 {
   2938 	struct wlr_xdg_activation_v1_request_activate_event *e = data;
   2939 	Client *c;
   2940 
   2941 	for (c = clients; c && csurface(c) != e->surface; c = c->next);
   2942 	if (c && c->mapped && c->scr == cur)
   2943 		focus(c);
   2944 }
   2945 
   2946 /* ---- screens ---- */
   2947 
   2948 /* the first screen is the one: the bottom line, the wallpaper and the windows go there */
   2949 static void
   2950 arrange(void)
   2951 {
   2952 	struct wlr_box b;
   2953 	Client *c;
   2954 
   2955 	if (!outputs)
   2956 		return;
   2957 	wlr_output_layout_get_box(layout, outputs->wlr, &b);
   2958 	ox = b.x;
   2959 	oy = b.y;
   2960 	sw = b.width;
   2961 	sh = b.height;
   2962 	wh = sh - ch;
   2963 	wlr_scene_node_set_position(&bgrect->node, ox, oy);
   2964 	wlr_scene_rect_set_size(bgrect, sw, sh);
   2965 	drawwallpaper();
   2966 	wlr_scene_node_set_position(&barbuf->node, ox, oy + wh);
   2967 	drawbar();
   2968 	arrangelayers();
   2969 	wlr_scene_node_set_position(&lockrect->node, ox, oy);
   2970 	wlr_scene_rect_set_size(lockrect, sw, sh);
   2971 	if (locked)
   2972 		drawlock();
   2973 	for (c = clients; c; c = c->next)
   2974 		if (c->mapped && !c->unmanaged) {
   2975 			if (c->isfull)
   2976 				cconfigure(c);
   2977 			place(c);
   2978 		}
   2979 	placenotifs();
   2980 }
   2981 
   2982 static void
   2983 outframe(struct wl_listener *l, void *data)
   2984 {
   2985 	Output *o = wl_container_of(l, o, frame);
   2986 	struct wlr_scene_output *so = wlr_scene_get_scene_output(scene, o->wlr);
   2987 	struct timespec now;
   2988 
   2989 	/* the typing goes with the screen's refresh: one step a frame, never torn */
   2990 	if (animate())
   2991 		wlr_output_schedule_frame(o->wlr);
   2992 	wlr_scene_output_commit(so, NULL);
   2993 	clock_gettime(CLOCK_MONOTONIC, &now);
   2994 	wlr_scene_output_send_frame_done(so, &now);
   2995 }
   2996 
   2997 static void
   2998 outstate(struct wl_listener *l, void *data)
   2999 {
   3000 	Output *o = wl_container_of(l, o, state);
   3001 	struct wlr_output_event_request_state *e = data;
   3002 
   3003 	wlr_output_commit_state(o->wlr, e->state);
   3004 	arrange();
   3005 }
   3006 
   3007 static void
   3008 outdestroy(struct wl_listener *l, void *data)
   3009 {
   3010 	Output *o = wl_container_of(l, o, destroy), **po;
   3011 
   3012 	wl_list_remove(&o->frame.link);
   3013 	wl_list_remove(&o->state.link);
   3014 	wl_list_remove(&o->destroy.link);
   3015 	for (po = &outputs; *po != o; po = &(*po)->next);
   3016 	*po = o->next;
   3017 	free(o);
   3018 	arrange();
   3019 }
   3020 
   3021 static void
   3022 newoutput(struct wl_listener *l, void *data)
   3023 {
   3024 	struct wlr_output *wo = data;
   3025 	struct wlr_output_state st;
   3026 	struct wlr_output_mode *m;
   3027 	struct wlr_output_layout_output *lo;
   3028 	struct wlr_scene_output *so;
   3029 	Output *o, **po;
   3030 
   3031 	wlr_output_init_render(wo, alloc, renderer);
   3032 	wlr_output_state_init(&st);
   3033 	wlr_output_state_set_enabled(&st, true);
   3034 	if ((m = wlr_output_preferred_mode(wo)))
   3035 		wlr_output_state_set_mode(&st, m);
   3036 	wlr_output_commit_state(wo, &st);
   3037 	wlr_output_state_finish(&st);
   3038 	if (!(o = calloc(1, sizeof *o)))
   3039 		return;
   3040 	o->wlr = wo;
   3041 	LISTEN(&wo->events.frame, &o->frame, outframe);
   3042 	LISTEN(&wo->events.request_state, &o->state, outstate);
   3043 	LISTEN(&wo->events.destroy, &o->destroy, outdestroy);
   3044 	for (po = &outputs; *po; po = &(*po)->next);
   3045 	*po = o;
   3046 	lo = wlr_output_layout_add_auto(layout, wo);
   3047 	so = wlr_scene_output_create(scene, wo);
   3048 	wlr_scene_output_layout_add_output(sol, lo, so);
   3049 	arrange();
   3050 }
   3051 
   3052 /* once a second: the clock, notifications, and the settings file if it changed */
   3053 static int
   3054 tick(void *data)
   3055 {
   3056 	static time_t last, lastvol;
   3057 	time_t now = time(NULL);
   3058 	struct stat st;
   3059 	char lay[64], var[64];
   3060 	Client *c;
   3061 	Kbd *k;
   3062 
   3063 	wl_event_source_timer_update(ticker, 1000);
   3064 	readbus();
   3065 	expirenotifs();
   3066 	if (stat(cfgpath, &st) == 0 && st.st_mtime != cfgmtime) {
   3067 		memcpy(lay, kblayout, sizeof lay);
   3068 		memcpy(var, kbvariant, sizeof var);
   3069 		loadconfig(0);
   3070 		loadcolours();
   3071 		if (strcmp(lay, kblayout) || strcmp(var, kbvariant))
   3072 			for (k = kbds; k; k = k->next)
   3073 				setkeymap(k->wlr);
   3074 		wlr_scene_rect_set_color(bgrect, col[ColBg]);
   3075 		wlr_scene_rect_set_color(lockrect, col[ColBg]);
   3076 		for (c = clients; c; c = c->next) {
   3077 			wlr_scene_rect_set_color(c->back, col[ColBg]);
   3078 			drawframe(c);
   3079 		}
   3080 		drawwallpaper();
   3081 		placenotifs();
   3082 		runbarcmds();
   3083 		last = 0;
   3084 	}
   3085 	if (now - lastvol >= 10) {
   3086 		readvolume();
   3087 		lastvol = now;
   3088 	}
   3089 	if (now / 5 != last / 5) {
   3090 		runbarcmds();
   3091 		drawbar();
   3092 	}
   3093 	last = now;
   3094 	return 0;
   3095 }
   3096 
   3097 int
   3098 main(int argc, char *argv[])
   3099 {
   3100 	const char *sock;
   3101 	char *home, *xdg;
   3102 	int bfd = -1, i;
   3103 
   3104 	if (argc == 2 && !strcmp("-v", argv[1]))
   3105 		die("torrent-" VERSION);
   3106 	else if (argc != 1)
   3107 		die("usage: torrent [-v]");
   3108 	setlocale(LC_CTYPE, "");
   3109 	signal(SIGPIPE, SIG_IGN);
   3110 	wlr_log_init(WLR_ERROR, NULL);
   3111 
   3112 	if ((xdg = getenv("XDG_CONFIG_HOME")) && *xdg)
   3113 		snprintf(cfgpath, sizeof cfgpath, "%s", xdg);
   3114 	else
   3115 		snprintf(cfgpath, sizeof cfgpath, "%s/.config", (home = getenv("HOME")) ? home : ".");
   3116 	mkdir(cfgpath, 0755);
   3117 	strncat(cfgpath, "/torrent", sizeof cfgpath - strlen(cfgpath) - 1);
   3118 	mkdir(cfgpath, 0755);
   3119 	strncat(cfgpath, "/config", sizeof cfgpath - strlen(cfgpath) - 1);
   3120 
   3121 	dpy = wl_display_create();
   3122 	loop = wl_display_get_event_loop(dpy);
   3123 	if (!(backend = wlr_backend_autocreate(loop, &session)))
   3124 		die("cannot start: run it from a login on a console, or inside another desktop");
   3125 	if (!(renderer = wlr_renderer_autocreate(backend)))
   3126 		die("cannot make a renderer");
   3127 	wlr_renderer_init_wl_display(renderer, dpy);
   3128 	if (!(alloc = wlr_allocator_autocreate(backend, renderer)))
   3129 		die("cannot make an allocator");
   3130 	compositor = wlr_compositor_create(dpy, 6, renderer);
   3131 	wlr_subcompositor_create(dpy);
   3132 	wlr_data_device_manager_create(dpy);
   3133 	wlr_primary_selection_v1_device_manager_create(dpy);
   3134 	wlr_data_control_manager_v1_create(dpy);
   3135 	wlr_export_dmabuf_manager_v1_create(dpy);
   3136 	wlr_screencopy_manager_v1_create(dpy);
   3137 	wlr_gamma_control_manager_v1_create(dpy);
   3138 	wlr_viewporter_create(dpy);
   3139 	wlr_single_pixel_buffer_manager_v1_create(dpy);
   3140 	wlr_fractional_scale_manager_v1_create(dpy, 1);
   3141 	wlr_presentation_create(dpy, backend, 2);
   3142 	wlr_relative_pointer_manager_v1_create(dpy);
   3143 	idle = wlr_idle_notifier_v1_create(dpy);
   3144 
   3145 	layout = wlr_output_layout_create(dpy);
   3146 	wlr_xdg_output_manager_v1_create(dpy, layout);
   3147 	LISTEN(&backend->events.new_output, &newoutput_l, newoutput);
   3148 	scene = wlr_scene_create();
   3149 	sol = wlr_scene_attach_output_layout(scene, layout);
   3150 	bgtree = wlr_scene_tree_create(&scene->tree);
   3151 	bgrect = wlr_scene_rect_create(bgtree, 1, 1, (float[4]){ 0, 0, 0, 1 });
   3152 	wallbuf = wlr_scene_buffer_create(bgtree, NULL);
   3153 	for (i = 0; i < 2; i++)
   3154 		layers[i] = wlr_scene_tree_create(&scene->tree);
   3155 	wintree = wlr_scene_tree_create(&scene->tree);
   3156 	bartree = wlr_scene_tree_create(&scene->tree);
   3157 	barbuf = wlr_scene_buffer_create(bartree, NULL);
   3158 	barbuf->node.data = &barkind;
   3159 	fulltree = wlr_scene_tree_create(&scene->tree);
   3160 	ortree = wlr_scene_tree_create(&scene->tree);
   3161 	layers[2] = wlr_scene_tree_create(&scene->tree);
   3162 	notiftree = wlr_scene_tree_create(&scene->tree);
   3163 	layers[3] = wlr_scene_tree_create(&scene->tree);
   3164 	locktree = wlr_scene_tree_create(&scene->tree);
   3165 	lockrect = wlr_scene_rect_create(locktree, 1, 1, (float[4]){ 0, 0, 0, 1 });
   3166 	lockbuf = wlr_scene_buffer_create(locktree, NULL);
   3167 	wlr_scene_node_set_enabled(&locktree->node, false);
   3168 
   3169 	xdgshell = wlr_xdg_shell_create(dpy, 6);
   3170 	LISTEN(&xdgshell->events.new_toplevel, &newtoplevel_l, newtoplevel);
   3171 	LISTEN(&xdgshell->events.new_popup, &newpopup_l, newpopup);
   3172 	layershell = wlr_layer_shell_v1_create(dpy, 4);
   3173 	LISTEN(&layershell->events.new_surface, &newlayer_l, newlayer);
   3174 	decomgr = wlr_xdg_decoration_manager_v1_create(dpy);
   3175 	LISTEN(&decomgr->events.new_toplevel_decoration, &newdeco_l, newdeco);
   3176 	wlr_server_decoration_manager_set_default_mode(wlr_server_decoration_manager_create(dpy),
   3177 	                                               WLR_SERVER_DECORATION_MANAGER_MODE_SERVER);
   3178 	activation = wlr_xdg_activation_v1_create(dpy);
   3179 	LISTEN(&activation->events.request_activate, &activate_l, activate);
   3180 
   3181 	cursor = wlr_cursor_create();
   3182 	wlr_cursor_attach_output_layout(cursor, layout);
   3183 	xcm = wlr_xcursor_manager_create(getenv("XCURSOR_THEME"), getenv("XCURSOR_SIZE") ? atoi(getenv("XCURSOR_SIZE")) : 24);
   3184 	LISTEN(&cursor->events.motion, &motion_l, cmotion);
   3185 	LISTEN(&cursor->events.motion_absolute, &motionabs_l, cmotionabs);
   3186 	LISTEN(&cursor->events.button, &button_l, cbutton);
   3187 	LISTEN(&cursor->events.axis, &axis_l, caxis);
   3188 	LISTEN(&cursor->events.frame, &frame_l, cframe);
   3189 	shapemgr = wlr_cursor_shape_manager_v1_create(dpy, 1);
   3190 	LISTEN(&shapemgr->events.request_set_shape, &shape_l, setshape);
   3191 
   3192 	seat = wlr_seat_create(dpy, "seat0");
   3193 	LISTEN(&backend->events.new_input, &newinput_l, newinput);
   3194 	LISTEN(&seat->events.request_set_cursor, &setcursor_l, setcursor);
   3195 	LISTEN(&seat->events.request_set_selection, &setsel_l, setsel);
   3196 	LISTEN(&seat->events.request_set_primary_selection, &setpsel_l, setpsel);
   3197 
   3198 	if (!(sock = wl_display_add_socket_auto(dpy)))
   3199 		die("cannot make a wayland socket");
   3200 	setenv("WAYLAND_DISPLAY", sock, 1);
   3201 	setenv("XDG_SESSION_TYPE", "wayland", 1);
   3202 	setenv("XDG_CURRENT_DESKTOP", "torrent", 0);
   3203 	/* x11 programs: xwayland starts the first time one connects */
   3204 	if ((xwayland = wlr_xwayland_create(dpy, compositor, true))) {
   3205 		LISTEN(&xwayland->events.ready, &xwready_l, xwready);
   3206 		LISTEN(&xwayland->events.new_surface, &newxw_l, newxw);
   3207 		setenv("DISPLAY", xwayland->display_name, 1);
   3208 	} else
   3209 		unsetenv("DISPLAY");
   3210 
   3211 	loadconfig(1);
   3212 	loadcolours();
   3213 	fontsetup();
   3214 	wlr_scene_rect_set_color(bgrect, col[ColBg]);
   3215 	wlr_scene_rect_set_color(lockrect, col[ColBg]);
   3216 	if (!wlr_backend_start(backend))
   3217 		die("cannot start the backend");
   3218 	wlr_cursor_set_xcursor(cursor, xcm, "default");
   3219 
   3220 	setupbus();
   3221 	if (bus && dbus_connection_get_unix_fd(bus, &bfd))
   3222 		wl_event_loop_add_fd(loop, bfd, WL_EVENT_READABLE, busready, NULL);
   3223 	ticker = wl_event_loop_add_timer(loop, tick, NULL);
   3224 	wl_event_source_timer_update(ticker, 1000);
   3225 	/* portals and the like learn where the screen is */
   3226 	run("dbus-update-activation-environment WAYLAND_DISPLAY DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE 2>/dev/null");
   3227 	readvolume();
   3228 	findbacklight();
   3229 	drawbar();
   3230 
   3231 	wl_display_run(dpy);
   3232 
   3233 	if (xwayland)
   3234 		wlr_xwayland_destroy(xwayland);
   3235 	wl_display_destroy_clients(dpy);
   3236 	wlr_scene_node_destroy(&scene->tree.node);
   3237 	wlr_xcursor_manager_destroy(xcm);
   3238 	wlr_cursor_destroy(cursor);
   3239 	wlr_allocator_destroy(alloc);
   3240 	wlr_renderer_destroy(renderer);
   3241 	wlr_backend_destroy(backend);
   3242 	wl_display_destroy(dpy);
   3243 	return EXIT_SUCCESS;
   3244 }