/*
 * Windows and widgets for Lua.
 *
 * A widget in Lua is a userdata that knows its c8ui widget until that is
 * destroyed; after, every method does nothing and returns nothing, so a
 * late answer (a download, a timer) touching a page that was left is
 * harmless. While the widget lives the registry holds the userdata, so
 * the functions and fields a script hangs on it stay.
 */
#include <string.h>
#include <c8ui/c8ui-files.h>
#include "c8lua.h"

#define WIDGET_META "c8.widget"
#define WINDOW_META "c8.window"
#define LIVE "c8.live" // userdata by its address, while the widget lives
#define METHODS "c8.methods" // a table of methods per kind

enum kind {
	K_PLAIN, // made by the toolkit: only what every widget has
	K_BOX, K_SCROLL, K_SPACER, K_LABEL, K_BUTTON, K_LINK, K_TOGGLE, K_SLIDER,
	K_ENTRY, K_COMBO, K_CHOICE, K_RADIO, K_CHECKBOX, K_RING, K_PROGRESS,
	K_SEPARATOR, K_IMAGE, K_TEXT, K_RICH, K_LIST, K_CANVAS, K_PAGES, K_STACK,
	K_GRID, K_EXPANDER, K_INFOBAR, K_HUB, K_PIVOT, K_APPBAR, K_COMMAND,
	K_ICON_BUTTON, K_FLYOUT, K_NAV, K_NUMBER, K_RATING, K_DATE, K_TIME,
	K_CALENDAR, K_FLIP, K_SPLIT, K_TREE, K_COLUMNS, K_ZOOM, K_TOGGLE_BUTTON,
	K_REPEAT, K_ITEM, K_TRANSPORT, K_NAVBAR,
	K_COUNT,
};

struct handle {
	struct c8ui_widget *w; // NULL: destroyed
	enum kind kind;
};

struct window {
	struct c8ui_window *win; // NULL: closed
	struct c8ui_widget *holder; // the root's child, ours: the app's goes in it
	struct c8ui_widget *appbar, *navbar;
};

/* Handles */

static void widget_gone(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	struct handle *h = data;
	lua_getfield(L, LUA_REGISTRYINDEX, LIVE);
	if (lua_rawgetp(L, -1, h) == LUA_TUSERDATA) {
		lua_getiuservalue(L, -1, 1);
		lua_getfield(L, -1, "on_destroy");
		if (lua_isfunction(L, -1)) {
			lua_pushvalue(L, -3);
			c8l_call(L, 1, 0);
		} else {
			lua_pop(L, 1);
		}
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
	h->w = NULL;
	lua_pushnil(L);
	lua_rawsetp(L, -2, h);
	lua_pop(L, 1);
}

static struct handle *handle_of(struct c8ui_widget *w) {
	return w && w->on_destroy == widget_gone ? w->user_data : NULL;
}

/* Pushes the userdata of a widget, making one for a widget of the
 * toolkit's own that Lua hasn't seen */
static void push_widget(lua_State *L, struct c8ui_widget *w, enum kind kind) {
	if (w == NULL) {
		lua_pushnil(L);
		return;
	}
	struct handle *h = handle_of(w);
	lua_getfield(L, LUA_REGISTRYINDEX, LIVE);
	if (h) {
		lua_rawgetp(L, -1, h);
		lua_remove(L, -2);
		return;
	}
	h = lua_newuserdatauv(L, sizeof(*h), 1);
	h->w = w;
	h->kind = kind;
	luaL_setmetatable(L, WIDGET_META);
	lua_newtable(L);
	lua_setiuservalue(L, -2, 1);
	lua_pushvalue(L, -1);
	lua_rawsetp(L, -3, h);
	lua_remove(L, -2);
	w->user_data = h;
	w->on_destroy = widget_gone;
}

struct c8ui_widget *c8l_widget(lua_State *L, int index) {
	struct handle *h = luaL_checkudata(L, index, WIDGET_META);
	return h->w;
}

/* The widget at index if it is of this kind and still there */
static struct c8ui_widget *widget_of(lua_State *L, int index, enum kind kind) {
	struct handle *h = luaL_checkudata(L, index, WIDGET_META);
	if (h->kind != kind) {
		luaL_error(L, "not that kind of widget");
	}
	return h->w;
}

/* Pushes what the script keeps on the widget as `name` (nil when it is
 * gone) */
static void push_field(lua_State *L, struct c8ui_widget *w, const char *name) {
	struct handle *h = handle_of(w);
	if (h == NULL) {
		lua_pushnil(L);
		return;
	}
	lua_getfield(L, LUA_REGISTRYINDEX, LIVE);
	lua_rawgetp(L, -1, h);
	lua_getiuservalue(L, -1, 1);
	lua_getfield(L, -1, name);
	lua_replace(L, -4);
	lua_pop(L, 2);
}

/* Pushes the function `name` of the widget and the widget; false (and
 * nothing pushed) when it has none */
static bool push_fn(lua_State *L, struct c8ui_widget *w, const char *name) {
	struct handle *h = handle_of(w);
	if (h == NULL) {
		return false;
	}
	lua_getfield(L, LUA_REGISTRYINDEX, LIVE);
	lua_rawgetp(L, -1, h);
	lua_remove(L, -2);
	lua_getiuservalue(L, -1, 1);
	lua_getfield(L, -1, name);
	if (!lua_isfunction(L, -1)) {
		lua_pop(L, 3);
		return false;
	}
	lua_remove(L, -2); // the uservalue
	lua_insert(L, -2); // fn, widget
	return true;
}

/* What every widget has */

static const char *const aligns[] = { "start", "center", "end", NULL };
static const char *const schemes[] = { "inherit", "light", "dark", NULL };

static int option(lua_State *L, int index, const char *const *names,
		int fallback) {
	const char *s = lua_tostring(L, index);
	for (int i = 0; s && names[i]; i++) {
		if (strcmp(s, names[i]) == 0) {
			return i;
		}
	}
	return fallback;
}

static int field_option(lua_State *L, int index, const char *key,
		const char *const *names, int fallback) {
	lua_getfield(L, index, key);
	int o = option(L, -1, names, fallback);
	lua_pop(L, 1);
	return o;
}

/* Sets a property every widget has from the value at index; false when
 * key isn't one */
static bool set_prop(lua_State *L, struct c8ui_widget *w, const char *key,
		int index) {
	if (strcmp(key, "hidden") == 0) {
		c8ui_widget_set_hidden(w, lua_toboolean(L, index));
	} else if (strcmp(key, "narrow_hidden") == 0) {
		c8ui_widget_set_narrow_hidden(w, lua_toboolean(L, index));
	} else if (strcmp(key, "disabled") == 0) {
		c8ui_widget_set_disabled(w, lua_toboolean(L, index));
	} else if (strcmp(key, "fill") == 0) {
		w->fill = lua_toboolean(L, index);
	} else if (strcmp(key, "expand") == 0) {
		w->expand = lua_toboolean(L, index);
	} else if (strcmp(key, "align") == 0) {
		w->align = option(L, index, aligns, C8UI_ALIGN_START);
	} else if (strcmp(key, "width") == 0) {
		w->fixed_width = lua_tonumber(L, index);
	} else if (strcmp(key, "height") == 0) {
		w->fixed_height = lua_tonumber(L, index);
	} else if (strcmp(key, "min_width") == 0) {
		w->min_width = lua_tonumber(L, index);
	} else if (strcmp(key, "max_width") == 0) {
		w->max_width = lua_tonumber(L, index);
	} else if (strcmp(key, "tooltip") == 0) {
		c8ui_widget_set_tooltip(w, lua_tostring(L, index));
		return true;
	} else if (strcmp(key, "scheme") == 0) {
		c8ui_widget_set_scheme(w, option(L, index, schemes,
			C8UI_SCHEME_INHERIT));
		return true;
	} else if (strcmp(key, "tilts") == 0) {
		w->tilts = lua_toboolean(L, index);
		return true;
	} else if (strcmp(key, "background") == 0) {
		/* A hub's is a picture (nil: none), panning behind it */
		struct handle *h = handle_of(w);
		if (h && h->kind == K_HUB && (lua_isnil(L, index) ||
				c8l_image(L, index))) {
			c8ui_hub_set_background(w, c8l_image(L, index));
		} else {
			c8ui_widget_set_background(w, c8l_color(L, index, 0xffffff));
		}
		return true;
	} else {
		return false;
	}
	if (w->root) {
		c8ui_widget_queue_layout(w);
	}
	return true;
}

static bool get_prop(lua_State *L, struct c8ui_widget *w, const char *key) {
	if (strcmp(key, "hidden") == 0) {
		lua_pushboolean(L, w->hidden);
	} else if (strcmp(key, "narrow_hidden") == 0) {
		lua_pushboolean(L, w->narrow_hides);
	} else if (strcmp(key, "disabled") == 0) {
		lua_pushboolean(L, w->disabled);
	} else if (strcmp(key, "fill") == 0) {
		lua_pushboolean(L, w->fill);
	} else if (strcmp(key, "expand") == 0) {
		lua_pushboolean(L, w->expand);
	} else if (strcmp(key, "width") == 0) {
		lua_pushnumber(L, w->rect.width);
	} else if (strcmp(key, "height") == 0) {
		lua_pushnumber(L, w->rect.height);
	} else if (strcmp(key, "x") == 0) {
		lua_pushnumber(L, w->rect.x);
	} else if (strcmp(key, "y") == 0) {
		lua_pushnumber(L, w->rect.y);
	} else if (strcmp(key, "tilts") == 0) {
		lua_pushboolean(L, w->tilts);
	} else if (strcmp(key, "alive") == 0) {
		lua_pushboolean(L, true);
	} else {
		return false;
	}
	return true;
}

static int widget_index(lua_State *L) {
	struct handle *h = luaL_checkudata(L, 1, WIDGET_META);
	const char *key = lua_tostring(L, 2);
	if (key) {
		lua_getfield(L, LUA_REGISTRYINDEX, METHODS);
		lua_rawgeti(L, -1, h->kind);
		if (lua_getfield(L, -1, key) != LUA_TNIL) {
			return 1;
		}
		lua_pop(L, 2);
		lua_rawgeti(L, -1, K_PLAIN);
		if (lua_getfield(L, -1, key) != LUA_TNIL) {
			return 1;
		}
		lua_pop(L, 3);
		if (h->w == NULL) {
			if (strcmp(key, "alive") == 0) {
				lua_pushboolean(L, false);
				return 1;
			}
		} else if (get_prop(L, h->w, key)) {
			return 1;
		}
	}
	lua_getiuservalue(L, 1, 1);
	lua_pushvalue(L, 2);
	lua_gettable(L, -2);
	return 1;
}

static int widget_newindex(lua_State *L) {
	struct handle *h = luaL_checkudata(L, 1, WIDGET_META);
	const char *key = lua_type(L, 2) == LUA_TSTRING ? lua_tostring(L, 2) : NULL;
	if (key && h->w && set_prop(L, h->w, key, 3)) {
		return 0;
	}
	lua_getiuservalue(L, 1, 1);
	lua_pushvalue(L, 2);
	lua_pushvalue(L, 3);
	lua_settable(L, -3);
	return 0;
}

static void add_child(lua_State *L, struct c8ui_widget *parent, int index) {
	struct c8ui_widget *child = c8l_widget(L, index);
	if (child == NULL) {
		return;
	}
	if (child->parent || child == parent) {
		luaL_error(L, "that widget is already in something: a widget goes "
			"in one place");
	}
	c8ui_widget_add(parent, child);
}

/* A new widget's userdata, with what the table at opts (0: none) says
 * every widget can have, the functions it gives, and for a container its
 * children (the table's list) */
static void finish(lua_State *L, struct c8ui_widget *w, enum kind kind,
		int opts, bool container) {
	push_widget(L, w, kind);
	if (opts == 0 || !lua_istable(L, opts)) {
		return;
	}
	int self = lua_gettop(L);
	lua_getiuservalue(L, self, 1);
	lua_pushnil(L);
	while (lua_next(L, opts)) {
		if (lua_type(L, -2) == LUA_TSTRING) {
			const char *key = lua_tostring(L, -2);
			if (!set_prop(L, w, key, lua_gettop(L)) && lua_isfunction(L, -1)) {
				lua_pushvalue(L, -1);
				lua_setfield(L, self + 1, key);
			}
		}
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
	if (container) {
		lua_Integer n = luaL_len(L, opts);
		for (lua_Integer i = 1; i <= n; i++) {
			if (lua_geti(L, opts, i) == LUA_TUSERDATA) {
				add_child(L, w, lua_gettop(L));
			}
			lua_pop(L, 1);
		}
	}
}

/* Methods every widget has */

#define ALIVE(w) if ((w) == NULL) { return 0; }

static int w_add(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	int top = lua_gettop(L);
	for (int i = 2; i <= top; i++) {
		add_child(L, w, i);
	}
	lua_settop(L, 1);
	return 1;
}

static int w_clear(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	c8ui_widget_clear(w);
	return 0;
}

static int w_destroy(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	c8ui_widget_destroy(w);
	return 0;
}

static int w_focus(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	c8ui_widget_grab_focus(w);
	return 0;
}

/* w:colors(): the colours where it is drawn (its scheme's), for an app
 * that writes them into markup */
static int w_colors(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	struct c8ui_colors c = c8ui_widget_colors(w);
	lua_createtable(L, 0, 5);
	lua_pushinteger(L, c.fg);
	lua_setfield(L, -2, "fg");
	lua_pushinteger(L, c.bg);
	lua_setfield(L, -2, "bg");
	lua_pushinteger(L, c.accent);
	lua_setfield(L, -2, "accent");
	lua_pushnumber(L, c.fg_secondary);
	lua_setfield(L, -2, "secondary");
	lua_pushboolean(L, c.dark);
	lua_setfield(L, -2, "dark");
	return 1;
}

/* w:rect(): x, y, width, height where it was last laid out, in the
 * window (what a scroll scrolled is in there too, moved with it) */
static int w_rect(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	lua_pushnumber(L, w->rect.x);
	lua_pushnumber(L, w->rect.y);
	lua_pushnumber(L, w->rect.width);
	lua_pushnumber(L, w->rect.height);
	return 4;
}

static int w_enter(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	c8ui_widget_enter(w);
	return 0;
}

static int w_redraw(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	struct handle *h = handle_of(w);
	if (h && h->kind == K_LIST) {
		if (lua_isnumber(L, 2)) {
			c8ui_list_redraw_item(w, (int)lua_tointeger(L, 2) - 1);
		} else {
			c8ui_list_redraw(w);
		}
	}
	c8ui_widget_queue_draw(w);
	return 0;
}

static int w_children(lua_State *L) {
	struct c8ui_widget *w = c8l_widget(L, 1);
	ALIVE(w);
	lua_pushinteger(L, w->child_count);
	return 1;
}

/* The value a control holds: what on_change is given, w:get() returns
 * and w:set() takes */
static int push_value(lua_State *L, struct c8ui_widget *w, enum kind kind) {
	switch (kind) {
	case K_TOGGLE:
		lua_pushboolean(L, c8ui_toggle_get(w));
		return 1;
	case K_CHECKBOX:
		lua_pushboolean(L, c8ui_checkbox_get(w));
		return 1;
	case K_SLIDER:
		lua_pushnumber(L, c8ui_slider_get(w));
		lua_pushboolean(L, c8ui_slider_is_live(w));
		return 2;
	case K_ENTRY:
		lua_pushstring(L, c8ui_entry_get(w));
		return 1;
	case K_TEXT:
		lua_pushstring(L, c8ui_textview_get(w));
		return 1;
	case K_COMBO:
		lua_pushinteger(L, c8ui_combo_get(w) + 1);
		return 1;
	case K_CHOICE:
		lua_pushinteger(L, c8ui_choice_get(w) + 1);
		return 1;
	case K_RADIO:
		lua_pushinteger(L, c8ui_radio_get(w) + 1);
		return 1;
	case K_PIVOT:
		lua_pushinteger(L, c8ui_pivot_get(w) + 1);
		return 1;
	case K_STACK:
		lua_pushinteger(L, c8ui_stack_get(w) + 1);
		return 1;
	case K_PAGES:
		lua_pushinteger(L, c8ui_pages_get(w) + 1);
		return 1;
	case K_EXPANDER:
		lua_pushboolean(L, c8ui_expander_get(w));
		return 1;
	case K_PROGRESS:
		lua_pushnumber(L, c8ui_progress_get(w));
		return 1;
	case K_COMMAND:
		lua_pushboolean(L, c8ui_appbar_command_get_toggle(w));
		return 1;
	case K_ICON_BUTTON:
		lua_pushboolean(L, c8ui_icon_button_get_toggle(w));
		return 1;
	case K_LIST: {
		int i = c8ui_list_get_selected(w);
		if (i < 0) {
			lua_pushnil(L);
		} else {
			lua_pushinteger(L, i + 1);
		}
		return 1;
	}
	case K_NAV:
		lua_pushinteger(L, c8ui_nav_get(w) + 1);
		return 1;
	case K_NUMBER:
		lua_pushnumber(L, c8ui_number_get(w));
		return 1;
	case K_RATING:
		lua_pushnumber(L, c8ui_rating_get(w));
		return 1;
	case K_DATE:
	case K_CALENDAR: {
		int y, m, d;
		if (kind == K_DATE) {
			c8ui_date_get(w, &y, &m, &d);
		} else {
			c8ui_calendar_get(w, &y, &m, &d);
		}
		lua_pushinteger(L, y);
		lua_pushinteger(L, m);
		lua_pushinteger(L, d);
		return 3;
	}
	case K_TIME: {
		int h, m;
		c8ui_time_get(w, &h, &m);
		lua_pushinteger(L, h);
		lua_pushinteger(L, m);
		return 2;
	}
	case K_FLIP:
		lua_pushinteger(L, c8ui_flip_get(w) + 1);
		return 1;
	case K_SPLIT:
		lua_pushnumber(L, c8ui_split_get_position(w));
		return 1;
	case K_TREE: {
		int item = c8ui_tree_get_selected(w);
		if (item == 0) {
			lua_pushnil(L);
		} else {
			lua_pushinteger(L, item);
		}
		return 1;
	}
	case K_COLUMNS: {
		bool down = false;
		int column = c8ui_columns_get_sort(w, &down);
		if (column < 0) {
			lua_pushnil(L);
		} else {
			lua_pushinteger(L, column + 1);
		}
		lua_pushboolean(L, down);
		return 2;
	}
	case K_ZOOM:
		lua_pushboolean(L, c8ui_zoom_get(w));
		return 1;
	case K_TOGGLE_BUTTON:
		lua_pushboolean(L, c8ui_togglebutton_get(w));
		return 1;
	case K_ITEM:
		lua_pushboolean(L, c8ui_item_container_get_selected(w));
		return 1;
	case K_NAVBAR: {
		int i = c8ui_navbar_get_current(w);
		if (i < 0) {
			lua_pushnil(L);
		} else {
			lua_pushinteger(L, i + 1);
		}
		return 1;
	}
	default:
		return 0;
	}
}

static int w_get(lua_State *L) {
	struct handle *h = luaL_checkudata(L, 1, WIDGET_META);
	ALIVE(h->w);
	return push_value(L, h->w, h->kind);
}

static int w_set(lua_State *L) {
	struct handle *h = luaL_checkudata(L, 1, WIDGET_META);
	struct c8ui_widget *w = h->w;
	ALIVE(w);
	switch (h->kind) {
	case K_LABEL:
		c8ui_label_set_text(w, luaL_tolstring(L, 2, NULL));
		break;
	case K_BUTTON:
		c8ui_button_set_label(w, luaL_checkstring(L, 2));
		break;
	case K_TOGGLE:
		c8ui_toggle_set(w, lua_toboolean(L, 2));
		break;
	case K_CHECKBOX:
		c8ui_checkbox_set(w, lua_toboolean(L, 2));
		break;
	case K_SLIDER:
		c8ui_slider_set(w, luaL_checknumber(L, 2));
		break;
	case K_ENTRY:
		c8ui_entry_set(w, luaL_optstring(L, 2, ""));
		break;
	case K_TEXT:
		c8ui_textview_set(w, luaL_optstring(L, 2, ""));
		break;
	case K_RICH:
		c8ui_rich_set_markup(w, luaL_optstring(L, 2, ""));
		break;
	case K_COMBO:
		c8ui_combo_set(w, (int)luaL_checkinteger(L, 2) - 1);
		break;
	case K_CHOICE:
		c8ui_choice_set(w, (int)luaL_checkinteger(L, 2) - 1);
		break;
	case K_RADIO:
		c8ui_radio_set(w, (int)luaL_checkinteger(L, 2) - 1);
		break;
	case K_PIVOT:
		c8ui_pivot_set(w, (int)luaL_checkinteger(L, 2) - 1);
		break;
	case K_STACK:
		c8ui_stack_set(w, (int)luaL_checkinteger(L, 2) - 1,
			lua_toboolean(L, 3));
		break;
	case K_PAGES:
		c8ui_pages_open(w, (int)luaL_checkinteger(L, 2) - 1);
		break;
	case K_EXPANDER:
		c8ui_expander_set(w, lua_toboolean(L, 2));
		break;
	case K_PROGRESS:
		c8ui_progress_set(w, luaL_checknumber(L, 2));
		break;
	case K_RING:
		c8ui_ring_set_active(w, lua_toboolean(L, 2));
		break;
	case K_IMAGE:
		c8ui_image_set(w, c8l_image(L, 2));
		break;
	case K_COMMAND:
		c8ui_appbar_command_set_toggle(w, lua_toboolean(L, 2));
		break;
	case K_ICON_BUTTON:
		c8ui_icon_button_set_toggle(w, lua_toboolean(L, 2));
		break;
	case K_LIST:
		c8ui_list_select(w, lua_isnil(L, 2) ? -1 :
			(int)luaL_checkinteger(L, 2) - 1);
		break;
	case K_NAV:
		c8ui_nav_set(w, (int)luaL_checkinteger(L, 2) - 1);
		break;
	case K_NUMBER:
		c8ui_number_set(w, luaL_checknumber(L, 2));
		break;
	case K_RATING:
		c8ui_rating_set(w, luaL_checknumber(L, 2));
		break;
	case K_DATE:
		c8ui_date_set(w, (int)luaL_checkinteger(L, 2),
			(int)luaL_checkinteger(L, 3), (int)luaL_checkinteger(L, 4));
		break;
	case K_CALENDAR:
		c8ui_calendar_set(w, (int)luaL_checkinteger(L, 2),
			(int)luaL_checkinteger(L, 3), (int)luaL_checkinteger(L, 4));
		break;
	case K_TIME:
		c8ui_time_set(w, (int)luaL_checkinteger(L, 2),
			(int)luaL_checkinteger(L, 3));
		break;
	case K_FLIP:
		c8ui_flip_set(w, (int)luaL_checkinteger(L, 2) - 1);
		break;
	case K_SPLIT:
		c8ui_split_set_position(w, luaL_checknumber(L, 2));
		break;
	case K_TREE:
		c8ui_tree_select(w, (int)luaL_optinteger(L, 2, 0));
		break;
	case K_COLUMNS:
		c8ui_columns_set_sort(w, lua_isnil(L, 2) ? -1 :
			(int)luaL_checkinteger(L, 2) - 1, lua_toboolean(L, 3));
		break;
	case K_ZOOM:
		c8ui_zoom_set(w, lua_toboolean(L, 2));
		break;
	case K_TOGGLE_BUTTON:
		c8ui_togglebutton_set(w, lua_toboolean(L, 2));
		break;
	case K_REPEAT:
		c8ui_repeat_button_set_label(w, luaL_checkstring(L, 2));
		break;
	case K_ITEM:
		c8ui_item_container_set_selected(w, lua_toboolean(L, 2));
		break;
	case K_NAVBAR:
		c8ui_navbar_set_current(w, lua_isnil(L, 2) ? -1 :
			(int)luaL_checkinteger(L, 2) - 1);
		break;
	default:
		break;
	}
	return 0;
}

static const luaL_Reg plain_methods[] = {
	{ "add", w_add },
	{ "clear", w_clear },
	{ "destroy", w_destroy },
	{ "focus", w_focus },
	{ "enter", w_enter },
	{ "colors", w_colors },
	{ "rect", w_rect },
	{ "redraw", w_redraw },
	{ "count_children", w_children },
	{ "get", w_get },
	{ "set", w_set },
	{ NULL, NULL },
};

/* What controls call: on_click(w), or on_change(w, value) */

static void clicked(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_click")) {
		c8l_call(L, 1, 0);
	}
}

static void changed(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	struct handle *h = handle_of(w);
	if (h && push_fn(L, w, "on_change")) {
		c8l_call(L, 1 + push_value(L, w, h->kind), 0);
	}
}

static void entered(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_enter")) {
		lua_pushstring(L, c8ui_entry_get(w));
		c8l_call(L, 2, 0);
	}
}

/* Constructors. Each takes one table (or, where it says, just the text). */

/* The options table of a constructor: a table at 1, or nothing */
static int opts_of(lua_State *L) {
	if (lua_isnoneornil(L, 1)) {
		lua_settop(L, 0);
		lua_newtable(L);
	} else if (lua_type(L, 1) == LUA_TSTRING) {
		/* c8.label("Words"): the text alone */
		lua_newtable(L);
		lua_pushvalue(L, 1);
		lua_setfield(L, -2, "text");
		lua_replace(L, 1);
	}
	luaL_checktype(L, 1, LUA_TTABLE);
	return 1;
}

/* padding = 8 or { left, top, right, bottom }; narrow_padding the same,
 * for when the window is narrow */
static void padding(lua_State *L, int opts, struct c8ui_widget *box,
		const char *key, bool narrow) {
	lua_getfield(L, opts, key);
	double v[4] = { 0 };
	bool given = true;
	if (lua_isnumber(L, -1)) {
		v[0] = v[1] = v[2] = v[3] = lua_tonumber(L, -1);
	} else if (lua_istable(L, -1)) {
		for (int i = 0; i < 4; i++) {
			lua_geti(L, -1, i + 1);
			v[i] = lua_tonumber(L, -1);
			lua_pop(L, 1);
		}
	} else {
		given = false;
	}
	lua_pop(L, 1);
	if (given && narrow) {
		c8ui_box_set_narrow_padding(box, v[0], v[1], v[2], v[3]);
	} else if (given) {
		c8ui_box_set_padding(box, v[0], v[1], v[2], v[3]);
	}
}

static int new_box(lua_State *L, enum c8ui_orientation o) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_box_new(o, c8l_field_num(L, t, "spacing", 0));
	padding(L, t, w, "padding", false);
	padding(L, t, w, "narrow_padding", true);
	if (lua_getfield(L, t, "narrow_spacing") == LUA_TNUMBER) {
		c8ui_box_set_narrow_spacing(w, lua_tonumber(L, -1));
	}
	lua_pop(L, 1);
	if (lua_getfield(L, t, "narrow_vertical") != LUA_TNIL) {
		c8ui_box_set_narrow_orientation(w, lua_toboolean(L, -1) ?
			C8UI_VERTICAL : C8UI_HORIZONTAL);
	}
	lua_pop(L, 1);
	if (c8l_field_bool(L, t, "wrap", false)) {
		c8ui_box_set_wrap(w, true);
	}
	finish(L, w, K_BOX, t, true);
	return 1;
}

static int l_column(lua_State *L) {
	return new_box(L, C8UI_VERTICAL);
}

static int l_row(lua_State *L) {
	return new_box(L, C8UI_HORIZONTAL);
}

static void box_pad(lua_State *L, bool narrow) {
	struct c8ui_widget *w = widget_of(L, 1, K_BOX);
	if (w == NULL) {
		return;
	}
	double v[4];
	if (lua_gettop(L) >= 5) {
		for (int i = 0; i < 4; i++) {
			v[i] = luaL_checknumber(L, i + 2);
		}
	} else {
		v[0] = v[1] = v[2] = v[3] = luaL_checknumber(L, 2);
	}
	if (narrow) {
		c8ui_box_set_narrow_padding(w, v[0], v[1], v[2], v[3]);
	} else {
		c8ui_box_set_padding(w, v[0], v[1], v[2], v[3]);
	}
}

static int box_padding(lua_State *L) {
	box_pad(L, false);
	return 0;
}

static int box_narrow_padding(lua_State *L) {
	box_pad(L, true);
	return 0;
}

static int box_narrow_spacing(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_BOX);
	ALIVE(w);
	c8ui_box_set_narrow_spacing(w, luaL_checknumber(L, 2));
	return 0;
}

static int box_narrow_vertical(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_BOX);
	ALIVE(w);
	c8ui_box_set_narrow_orientation(w, lua_toboolean(L, 2) ?
		C8UI_VERTICAL : C8UI_HORIZONTAL);
	return 0;
}

static int l_scroll(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *child = NULL;
	if (lua_geti(L, t, 1) == LUA_TUSERDATA) {
		child = c8l_widget(L, -1);
	}
	lua_pop(L, 1);
	if (child == NULL || child->parent) {
		return luaL_error(L, "c8.scroll{ widget }: it scrolls one widget, "
			"which isn't in anything yet");
	}
	struct c8ui_widget *w = c8ui_scroll_new(child);
	bool sideways = c8l_field_bool(L, t, "horizontal", false);
	bool down = sideways ? c8l_field_bool(L, t, "vertical", false) : true;
	if (sideways) {
		c8ui_scroll_set_directions(w, true, down);
	}
	/* Other ways when the window is narrow: an article's columns going
	 * across wide, down narrow */
	lua_getfield(L, t, "narrow_horizontal");
	lua_getfield(L, t, "narrow_vertical");
	if (!lua_isnil(L, -1) || !lua_isnil(L, -2)) {
		c8ui_scroll_set_narrow_directions(w,
			lua_isnil(L, -2) ? sideways : lua_toboolean(L, -2),
			lua_isnil(L, -1) ? down : lua_toboolean(L, -1));
	}
	lua_pop(L, 2);
	finish(L, w, K_SCROLL, t, false);
	return 1;
}

static int scroll_to(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_SCROLL);
	ALIVE(w);
	c8ui_scroll_to(w, luaL_checknumber(L, 2));
	return 0;
}

/* Sideways: c8ui_scroll_to only moves down, so a horizontal scroll needs
 * its own */
static int scroll_to_x(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_SCROLL);
	ALIVE(w);
	c8ui_scroll_to_x(w, luaL_checknumber(L, 2));
	return 0;
}

static int scroll_offset(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_SCROLL);
	ALIVE(w);
	double x, y;
	c8ui_scroll_get_offset(w, &x, &y);
	lua_pushnumber(L, x);
	lua_pushnumber(L, y);
	return 2;
}

static int l_spacer(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_spacer_new(c8l_field_num(L, t, "width", 0),
		c8l_field_num(L, t, "height", 0)), K_SPACER, 0, false);
	return 1;
}

static const char *const styles[] = { "header", "subheader", "title", "item",
	"body", "strong", "caption", NULL };
static const char *const text_colors[] = { "primary", "secondary", "accent",
	NULL };

static int l_label(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_label_new(c8l_field_str(L, t, "text", ""),
		field_option(L, t, "style", styles, C8UI_TEXT_BODY));
	c8ui_label_set_color(w, field_option(L, t, "color", text_colors,
		C8UI_COLOR_PRIMARY));
	int lines = (int)c8l_field_num(L, t, "lines", 0);
	if (lines > 0) {
		c8ui_label_set_max_lines(w, lines);
	}
	if (lua_getfield(L, t, "narrow_style") != LUA_TNIL) {
		c8ui_label_set_narrow_style(w, option(L, -1, styles, C8UI_TEXT_BODY));
	}
	lua_pop(L, 1);
	finish(L, w, K_LABEL, t, false);
	return 1;
}

static int label_style(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LABEL);
	ALIVE(w);
	c8ui_label_set_style(w, luaL_checkoption(L, 2, NULL, styles));
	return 0;
}

static int label_narrow_style(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LABEL);
	ALIVE(w);
	c8ui_label_set_narrow_style(w, luaL_checkoption(L, 2, NULL, styles));
	return 0;
}

static int label_color(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LABEL);
	ALIVE(w);
	c8ui_label_set_color(w, luaL_checkoption(L, 2, NULL, text_colors));
	return 0;
}

static int l_button(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_button_new(c8l_field_str(L, t, "label",
		c8l_field_str(L, t, "text", "")), clicked, NULL);
	if (c8l_field_bool(L, t, "primary", false)) {
		c8ui_button_set_primary(w, true);
	}
	finish(L, w, K_BUTTON, t, false);
	return 1;
}

static int l_link(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_link_new(c8l_field_str(L, t, "label",
		c8l_field_str(L, t, "text", "")), clicked, NULL), K_LINK, t, false);
	return 1;
}

static int l_toggle(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_toggle_new(c8l_field_str(L, t, "header", NULL),
		c8l_field_str(L, t, "caption", NULL), c8l_field_bool(L, t, "on", false),
		changed, NULL), K_TOGGLE, t, false);
	return 1;
}

static int l_checkbox(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_checkbox_new(c8l_field_str(L, t, "label", ""),
		c8l_field_bool(L, t, "checked", false), changed, NULL), K_CHECKBOX,
		t, false);
	return 1;
}

static int l_slider(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_slider_new(c8l_field_str(L, t, "header", NULL),
		c8l_field_num(L, t, "min", 0), c8l_field_num(L, t, "max", 100),
		c8l_field_num(L, t, "step", 1), c8l_field_num(L, t, "value", 0),
		changed, NULL);
	const char *low = c8l_field_str(L, t, "low", NULL);
	const char *high = c8l_field_str(L, t, "high", NULL);
	if (low || high) {
		c8ui_slider_set_labels(w, low ? low : "", high ? high : "");
	}
	/* How many digits after the point to show beside the header, and a
	 * unit after: not a printf format a script could get wrong */
	lua_getfield(L, t, "digits");
	if (lua_isnumber(L, -1)) {
		int digits = CLAMP((int)lua_tointeger(L, -1), 0, 6);
		const char *unit = c8l_field_str(L, t, "unit", "");
		GString *fmt = g_string_new(NULL);
		g_string_printf(fmt, "%%.%df", digits);
		for (const char *p = unit; *p; p++) {
			g_string_append_c(fmt, *p);
			if (*p == '%') {
				g_string_append_c(fmt, '%');
			}
		}
		c8ui_slider_set_format(w, fmt->str);
		g_string_free(fmt, TRUE);
	}
	lua_pop(L, 1);
	finish(L, w, K_SLIDER, t, false);
	return 1;
}

static void entry_changed(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_change")) {
		lua_pushstring(L, c8ui_entry_get(w));
		c8l_call(L, 2, 0);
	}
}

static int l_entry(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_entry_new(c8l_field_str(L, t, "header", NULL),
		c8l_field_str(L, t, "text", ""), entered, NULL);
	const char *hint = c8l_field_str(L, t, "placeholder", NULL);
	if (hint) {
		c8ui_entry_set_placeholder(w, hint);
	}
	if (c8l_field_bool(L, t, "password", false)) {
		c8ui_entry_set_password(w, true);
	}
	if (c8l_field_bool(L, t, "search", false)) {
		c8ui_entry_set_search(w, true);
	}
	if (c8l_field_bool(L, t, "enter_only", false)) {
		c8ui_entry_set_enter_only(w, true);
	}
	c8ui_entry_on_change(w, entry_changed, NULL);
	finish(L, w, K_ENTRY, t, false);
	return 1;
}

static int entry_suggest(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_ENTRY);
	ALIVE(w);
	int count = 0;
	char **items = c8l_strings(L, 2, NULL, &count);
	c8ui_entry_set_suggestions(w, (const char *const *)items, count);
	g_strfreev(items);
	return 0;
}

/* Combo, choice and radio: a header, items, the one chosen (from 1) */
static int new_picker(lua_State *L, enum kind kind) {
	int t = opts_of(L);
	int count = 0;
	char **items = c8l_strings(L, t, "items", &count);
	const char *header = c8l_field_str(L, t, "header", NULL);
	int selected = (int)c8l_field_num(L, t, "selected", 1) - 1;
	const char *const *list = (const char *const *)items;
	struct c8ui_widget *w = kind == K_COMBO ?
		c8ui_combo_new(header, list, count, selected, changed, NULL) :
		kind == K_CHOICE ?
		c8ui_choice_new(header, list, count, selected, changed, NULL) :
		c8ui_radio_new(header, list, count, selected, changed, NULL);
	g_strfreev(items);
	finish(L, w, kind, t, false);
	return 1;
}

static int l_combo(lua_State *L) {
	return new_picker(L, K_COMBO);
}

static int l_choice(lua_State *L) {
	return new_picker(L, K_CHOICE);
}

static int l_radio(lua_State *L) {
	return new_picker(L, K_RADIO);
}

static int combo_items(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_COMBO);
	ALIVE(w);
	int count = 0;
	char **items = c8l_strings(L, 2, NULL, &count);
	c8ui_combo_set_items(w, (const char *const *)items, count,
		(int)luaL_optinteger(L, 3, 1) - 1);
	g_strfreev(items);
	return 0;
}

static int l_ring(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_ring_new(c8l_field_num(L, t, "size", 0));
	c8ui_ring_set_active(w, c8l_field_bool(L, t, "active", true));
	finish(L, w, K_RING, t, false);
	return 1;
}

static int l_progress(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_progress_new(c8l_field_num(L, t, "value", -1)),
		K_PROGRESS, t, false);
	return 1;
}

static int l_separator(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_separator_new(c8l_field_bool(L, t, "vertical", false) ?
		C8UI_VERTICAL : C8UI_HORIZONTAL), K_SEPARATOR, t, false);
	return 1;
}

static int l_image(lua_State *L) {
	int t = opts_of(L);
	lua_getfield(L, t, "image");
	cairo_surface_t *surface = c8l_image(L, -1);
	lua_pop(L, 1);
	/* Its size isn't a layout hint here but the picture's box */
	struct c8ui_widget *w = c8ui_image_new(surface,
		c8l_field_num(L, t, "width", 0), c8l_field_num(L, t, "height", 0));
	if (g_strcmp0(c8l_field_str(L, t, "fit", NULL), "cover") == 0) {
		c8ui_image_set_fit(w, C8UI_FIT_COVER);
	}
	lua_pushnil(L);
	lua_setfield(L, t, "width");
	lua_pushnil(L);
	lua_setfield(L, t, "height");
	finish(L, w, K_IMAGE, t, false);
	return 1;
}

/* An edit runs on_change(w): the text is w:get(), not copied for every
 * key */
static void text_changed(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_change")) {
		c8l_call(L, 1, 0);
	}
}

/* The caret or the selection moved: on_move(w) */
static void text_moved(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_move")) {
		c8l_call(L, 1, 0);
	}
}

static int l_text(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_textview_new(c8l_field_str(L, t, "text", ""));
	c8ui_textview_set_editable(w, c8l_field_bool(L, t, "editable", true));
	c8ui_textview_set_wrap(w, c8l_field_bool(L, t, "wrap", true));
	c8ui_textview_set_framed(w, c8l_field_bool(L, t, "framed", false));
	if (c8l_field_bool(L, t, "monospace", false)) {
		c8ui_textview_set_font(w, "monospace", c8l_field_num(L, t, "size", 0));
	} else if (c8l_field_num(L, t, "size", 0) > 0) {
		c8ui_textview_set_font(w, NULL, c8l_field_num(L, t, "size", 0));
	}
	const char *hint = c8l_field_str(L, t, "placeholder", NULL);
	if (hint) {
		c8ui_textview_set_placeholder(w, hint);
	}
	if (!c8l_field_bool(L, t, "accepts_tab", true)) {
		c8ui_textview_set_accepts_tab(w, false);
	}
	if (c8l_field_bool(L, t, "rich", false)) {
		c8ui_textview_set_rich(w, true);
	}
	c8ui_textview_on_change(w, text_changed, NULL);
	c8ui_textview_on_move(w, text_moved, NULL);
	finish(L, w, K_TEXT, t, false);
	return 1;
}

static int text_modified(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	if (lua_gettop(L) >= 2) {
		if (!lua_toboolean(L, 2)) {
			c8ui_textview_set_unmodified(w);
		}
		return 0;
	}
	lua_pushboolean(L, c8ui_textview_is_modified(w));
	return 1;
}

/* text:position(): the cursor's line and column */
static int text_position(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	int line, col;
	c8ui_textview_get_position(w, &line, &col);
	lua_pushinteger(L, line);
	lua_pushinteger(L, col);
	return 2;
}

static int text_insert(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	c8ui_textview_insert(w, luaL_checkstring(L, 2));
	return 0;
}

/* text:selection(): first and last byte as string.sub takes them (from
 * 1; with nothing selected the last is one before the first) */
static int text_selection(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	size_t a, b;
	c8ui_textview_get_selection(w, &a, &b);
	lua_pushinteger(L, (lua_Integer)a + 1);
	lua_pushinteger(L, (lua_Integer)b);
	return 2;
}

/* text:select(first, last): the same way round; the caret goes to last */
static int text_select(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	lua_Integer a = luaL_checkinteger(L, 2) - 1;
	lua_Integer b = luaL_optinteger(L, 3, a);
	c8ui_textview_select(w, a > 0 ? (size_t)a : 0, b > 0 ? (size_t)b : 0);
	return 0;
}

/* text:find(needle, backwards, match_case): selects the next match */
static int text_find(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	lua_pushboolean(L, c8ui_textview_find(w, luaL_checkstring(L, 2),
		lua_toboolean(L, 3), lua_toboolean(L, 4)));
	return 1;
}

/* text:replace_all(needle, with, match_case): how many */
static int text_replace_all(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	lua_pushinteger(L, c8ui_textview_replace_all(w, luaL_checkstring(L, 2),
		luaL_optstring(L, 3, ""), lua_toboolean(L, 4)));
	return 1;
}

static int text_undo(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	lua_pushboolean(L, c8ui_textview_undo(w));
	return 1;
}

static int text_redo(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	lua_pushboolean(L, c8ui_textview_redo(w));
	return 1;
}

static int text_wrap(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	c8ui_textview_set_wrap(w, lua_toboolean(L, 2));
	return 0;
}

/* text:font(family, size): nil and 0 are the theme's */
static int text_font(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	c8ui_textview_set_font(w, luaL_optstring(L, 2, NULL),
		luaL_optnumber(L, 3, 0));
	return 0;
}

/* text:rich(): whether it is; text:rich(bool) makes it so */
static int text_rich(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	if (lua_gettop(L) >= 2) {
		c8ui_textview_set_rich(w, lua_toboolean(L, 2));
		return 0;
	}
	lua_pushboolean(L, c8ui_textview_is_rich(w));
	return 1;
}

static void push_format(lua_State *L, const struct c8ui_text_format *f) {
	lua_createtable(L, 0, 7);
	if (f->family) {
		lua_pushstring(L, f->family);
		lua_setfield(L, -2, "family");
	}
	if (f->size > 0) {
		lua_pushnumber(L, f->size);
		lua_setfield(L, -2, "size");
	}
	if (f->has_color) {
		lua_pushinteger(L, f->color);
		lua_setfield(L, -2, "color");
	}
	static const char *const names[] = { "bold", "italic", "underline",
		"strike" };
	const bool on[] = { f->bold, f->italic, f->underline, f->strike };
	for (int i = 0; i < 4; i++) {
		if (on[i]) {
			lua_pushboolean(L, true);
			lua_setfield(L, -2, names[i]);
		}
	}
}

/* The fields of the format table at index; mask says which were there
 * (false or 0 is there too: it takes a family, size or colour away).
 * family points into the table's string */
static unsigned read_format(lua_State *L, int index,
		struct c8ui_text_format *f) {
	*f = (struct c8ui_text_format){ 0 };
	unsigned mask = 0;
	index = lua_absindex(L, index);
	if (lua_getfield(L, index, "family") != LUA_TNIL) {
		mask |= C8UI_FORMAT_FAMILY;
		f->family = lua_type(L, -1) == LUA_TSTRING ?
			lua_tostring(L, -1) : NULL;
	}
	lua_pop(L, 1);
	if (lua_getfield(L, index, "size") != LUA_TNIL) {
		mask |= C8UI_FORMAT_SIZE;
		f->size = lua_type(L, -1) == LUA_TNUMBER ? lua_tonumber(L, -1) : 0;
	}
	lua_pop(L, 1);
	if (lua_getfield(L, index, "color") != LUA_TNIL) {
		mask |= C8UI_FORMAT_COLOR;
		f->has_color = lua_toboolean(L, -1);
		if (f->has_color) {
			f->color = c8l_color(L, -1, 0);
		}
	}
	lua_pop(L, 1);
	static const char *const names[] = { "bold", "italic", "underline",
		"strike" };
	static const unsigned bits[] = { C8UI_FORMAT_BOLD, C8UI_FORMAT_ITALIC,
		C8UI_FORMAT_UNDERLINE, C8UI_FORMAT_STRIKE };
	bool *on[] = { &f->bold, &f->italic, &f->underline, &f->strike };
	for (int i = 0; i < 4; i++) {
		if (lua_getfield(L, index, names[i]) != LUA_TNIL) {
			mask |= bits[i];
			*on[i] = lua_toboolean(L, -1);
		}
		lua_pop(L, 1);
	}
	return mask;
}

/* text:format(): what typing would get, as a table; text:format{ bold =
 * true, ... }: the fields given, on the selection or on what is typed
 * next */
static int text_format(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	struct c8ui_text_format f;
	if (lua_istable(L, 2)) {
		unsigned mask = read_format(L, 2, &f);
		/* family's string is the table's, still held there */
		c8ui_textview_format(w, &f, mask);
		return 0;
	}
	c8ui_textview_get_format(w, &f);
	push_format(L, &f);
	return 1;
}

static void push_run(const char *text, size_t length,
		const struct c8ui_text_format *f, void *data) {
	lua_State *L = data;
	push_format(L, f);
	lua_pushlstring(L, text, length);
	lua_setfield(L, -2, "text");
	lua_rawseti(L, -2, (lua_Integer)lua_rawlen(L, -2) + 1);
}

/* text:runs(): the text as a list of runs, each its format's fields and
 * its text */
static int text_runs(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	lua_newtable(L);
	c8ui_textview_get_runs(w, push_run, L);
	return 1;
}

/* text:append(text, format): at the end, not to undo; for reading a
 * document in */
static int text_append(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TEXT);
	ALIVE(w);
	const char *s = luaL_checkstring(L, 2);
	struct c8ui_text_format f;
	if (lua_istable(L, 3)) {
		read_format(L, 3, &f);
		c8ui_textview_append(w, s, &f);
	} else {
		c8ui_textview_append(w, s, NULL);
	}
	return 0;
}

/* What every rich text takes; its boxes share them */
static void rich_options(lua_State *L, int t, struct c8ui_widget *w) {
	const char *family = c8l_field_str(L, t, "family", NULL);
	double size = c8l_field_num(L, t, "size", 0);
	if (family || size > 0) {
		c8ui_rich_set_font(w, family, size);
	}
	if (c8l_field_bool(L, t, "justify", false)) {
		c8ui_rich_set_justify(w, true);
	}
	double spacing = c8l_field_num(L, t, "line_spacing", 0);
	if (spacing > 0) {
		c8ui_rich_set_line_spacing(w, spacing);
	}
	lua_getfield(L, t, "color");
	if (!lua_isnil(L, -1)) {
		c8ui_rich_set_color(w, c8l_color(L, -1, 0));
	}
	lua_pop(L, 1);
}

/* on_link(w, uri): a click on an <a href> in its markup */
static void rich_link(struct c8ui_widget *w, const char *uri, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_link")) {
		lua_pushstring(L, uri);
		c8l_call(L, 2, 0);
	}
}

static int l_rich(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_rich_new(c8l_field_str(L, t, "markup",
		c8l_field_str(L, t, "text", "")));
	rich_options(L, t, w);
	/* Only then: a rich text taking clicks takes the hover from its
	 * parent */
	if (lua_getfield(L, t, "on_link") == LUA_TFUNCTION) {
		c8ui_rich_on_link(w, rich_link, NULL);
	}
	lua_pop(L, 1);
	finish(L, w, K_RICH, t, false);
	return 1;
}

/* c8.rich_overflow {}: where a rich text goes on, linked by
 * rich:overflow(box) */
static int l_rich_overflow(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_rich_overflow_new(), K_RICH, t, false);
	return 1;
}

static int l_rich_columns(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_rich_columns_new(c8l_field_str(L, t, "markup",
		c8l_field_str(L, t, "text", "")),
		c8l_field_num(L, t, "column_width", 320), c8l_field_num(L, t, "gap", 40));
	rich_options(L, t, w);
	finish(L, w, K_RICH, t, false);
	return 1;
}

/* rich:overflow(box): what doesn't fit goes on in box */
static int rich_overflow(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_RICH);
	struct c8ui_widget *more = widget_of(L, 2, K_RICH);
	if (w && more) {
		c8ui_rich_set_overflow(w, more);
	}
	return 0;
}

static int l_icon_button(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_icon_button_new(c8l_field_str(L, t, "icon",
		NULL), c8l_field_str(L, t, "label", NULL), clicked, NULL);
	/* toggle = false: one that stays down while on, off for now */
	lua_getfield(L, t, "toggle");
	if (!lua_isnil(L, -1)) {
		c8ui_icon_button_set_toggle(w, lua_toboolean(L, -1));
	}
	lua_pop(L, 1);
	finish(L, w, K_ICON_BUTTON, t, false);
	return 1;
}

static int l_back_button(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_back_button_new(clicked, NULL), K_ICON_BUTTON, t, false);
	return 1;
}

/* Lists: either item(index) returning { title, subtitle, icon } for a
 * plain one, or draw(g, item) to draw it yourself */

static void list_draw(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, list, "item")) {
		lua_pop(L, 1);
		lua_pushinteger(L, item->index + 1);
		if (!c8l_call(L, 1, 1)) {
			return;
		}
		bool cells = false;
		if (lua_istable(L, -1)) {
			cells = lua_getfield(L, -1, "cells") == LUA_TTABLE;
			if (!cells) {
				lua_pop(L, 1);
			}
		}
		if (cells) {
			/* { cells = { "Name", { "Type", secondary = true } } } under
			 * the list's columns */
			push_field(L, list, "columns");
			struct handle *ch = luaL_testudata(L, -1, WIDGET_META);
			struct c8ui_widget *cols = ch && ch->kind == K_COLUMNS ? ch->w : NULL;
			lua_pop(L, 1);
			lua_Integer n = cols ? luaL_len(L, -1) : 0;
			for (lua_Integer i = 1; i <= n; i++) {
				lua_geti(L, -1, i);
				bool dim = false;
				if (lua_istable(L, -1)) {
					dim = c8l_field_bool(L, -1, "secondary", false);
					lua_geti(L, -1, 1);
					lua_replace(L, -2);
				}
				const char *text = lua_tostring(L, -1);
				c8ui_columns_draw_cell(cols, cr, item, (int)i - 1,
					text ? text : "", dim);
				lua_pop(L, 1);
			}
			lua_pop(L, 2);
			return;
		}
		if (lua_istable(L, -1)) {
			const char *icon = c8l_field_str(L, -1, "icon", NULL);
			c8ui_list_draw_text(list, cr, item, icon ? c8l_icon(icon) : NULL,
				c8l_field_str(L, -1, "title", ""),
				c8l_field_str(L, -1, "subtitle", NULL));
		} else if (lua_type(L, -1) == LUA_TSTRING) {
			c8ui_list_draw_text(list, cr, item, NULL, lua_tostring(L, -1),
				NULL);
		}
		lua_pop(L, 1);
		return;
	}
	if (!push_fn(L, list, "draw")) {
		return;
	}
	lua_pop(L, 1);
	c8l_draw_begin(L, cr, list);
	int g = lua_gettop(L);
	lua_createtable(L, 0, 10);
	lua_pushinteger(L, item->index + 1);
	lua_setfield(L, -2, "index");
	lua_pushnumber(L, item->rect.x);
	lua_setfield(L, -2, "x");
	lua_pushnumber(L, item->rect.y);
	lua_setfield(L, -2, "y");
	lua_pushnumber(L, item->rect.width);
	lua_setfield(L, -2, "width");
	lua_pushnumber(L, item->rect.height);
	lua_setfield(L, -2, "height");
	lua_pushboolean(L, item->selected);
	lua_setfield(L, -2, "selected");
	lua_pushboolean(L, item->hovered);
	lua_setfield(L, -2, "hovered");
	lua_pushboolean(L, item->pressed);
	lua_setfield(L, -2, "pressed");
	lua_pushinteger(L, item->fg);
	lua_setfield(L, -2, "fg");
	lua_pushnumber(L, item->secondary);
	lua_setfield(L, -2, "secondary");
	lua_pushvalue(L, g);
	lua_insert(L, -2);
	/* Stack: fn, g, g, item: keep the first g to end it after */
	lua_pushvalue(L, g - 1);
	lua_insert(L, -3);
	c8l_call(L, 2, 0);
	c8l_draw_end(L, g);
	lua_settop(L, g - 2);
}

static void list_opened(struct c8ui_widget *list, int index, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, list, "on_open")) {
		lua_pushinteger(L, index + 1);
		c8l_call(L, 2, 0);
	}
}

static void list_selected(struct c8ui_widget *list, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, list, "on_select")) {
		int i = c8ui_list_get_selected(list);
		if (i < 0) {
			lua_pushnil(L);
		} else {
			lua_pushinteger(L, i + 1);
		}
		c8l_call(L, 2, 0);
	}
}

static void list_context(struct c8ui_widget *list, int index, double x,
		double y, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, list, "on_context")) {
		if (index < 0) {
			lua_pushnil(L);
		} else {
			lua_pushinteger(L, index + 1);
		}
		lua_pushnumber(L, x);
		lua_pushnumber(L, y);
		c8l_call(L, 4, 0);
	}
}

/* spans(i): how many cells across and down item i takes */
static void list_span(struct c8ui_widget *list, int index, int *cols,
		int *rows, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, list, "spans")) {
		lua_pop(L, 1);
		lua_pushinteger(L, index + 1);
		if (c8l_call(L, 1, 2)) {
			*cols = MAX((int)luaL_optinteger(L, -2, 1), 1);
			*rows = MAX((int)luaL_optinteger(L, -1, 1), 1);
			lua_pop(L, 2);
		}
	}
}

static int l_list(lua_State *L) {
	int t = opts_of(L);
	bool grid = c8l_field_bool(L, t, "grid", false);
	lua_getfield(L, t, "spans");
	bool spans = lua_isfunction(L, -1);
	lua_pop(L, 1);
	struct c8ui_widget *w = c8ui_list_new(spans ? C8UI_LIST_SPANS :
		grid ? C8UI_LIST_GRID : C8UI_LIST_ROWS,
		c8l_field_num(L, t, "item_width", grid || spans ? 160 : 0),
		c8l_field_num(L, t, "item_height", grid || spans ? 160 : 56),
		list_draw, NULL);
	c8ui_list_set_click_opens(w, c8l_field_bool(L, t, "click_opens", true));
	if (c8l_field_bool(L, t, "multiple", false)) {
		c8ui_list_set_multiple(w, true);
	}
	if (c8l_field_bool(L, t, "keep", false)) {
		c8ui_list_set_keep(w, true);
	}
	c8ui_list_on_open(w, list_opened, NULL);
	c8ui_list_on_select(w, list_selected, NULL);
	c8ui_list_on_context(w, list_context, NULL);
	/* After finish: the count asks spans, which is the script's by then */
	finish(L, w, K_LIST, t, false);
	lua_getfield(L, t, "columns");
	if (lua_type(L, -1) == LUA_TUSERDATA) {
		lua_getiuservalue(L, -2, 1);
		lua_insert(L, -2);
		lua_setfield(L, -2, "columns");
	}
	lua_pop(L, 1);
	if (spans) {
		c8ui_list_set_spans(w, list_span, NULL);
	}
	c8ui_list_set_count(w, (int)c8l_field_num(L, t, "count", 0));
	return 1;
}

static const char *const list_modes[] = { "rows", "grid", "spans", NULL };

/* list:mode("rows" | "grid" | "spans" [, item_width, item_height]) */
static int list_mode(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LIST);
	ALIVE(w);
	int mode = luaL_checkoption(L, 2, NULL, list_modes);
	c8ui_list_set_mode(w, mode, luaL_optnumber(L, 3, mode ? 160 : 0),
		luaL_optnumber(L, 4, mode ? 160 : 56));
	return 0;
}

static int list_select_all(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LIST);
	ALIVE(w);
	c8ui_list_select_all(w, lua_isnone(L, 2) || lua_toboolean(L, 2));
	return 0;
}

static int list_selected_count(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LIST);
	ALIVE(w);
	lua_pushinteger(L, c8ui_list_selected_count(w));
	return 1;
}

static int list_count(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LIST);
	ALIVE(w);
	if (lua_gettop(L) >= 2) {
		c8ui_list_set_count(w, (int)luaL_checkinteger(L, 2));
		c8ui_list_redraw(w);
		return 0;
	}
	lua_pushinteger(L, c8ui_list_get_count(w));
	return 1;
}

static int list_is_selected(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LIST);
	ALIVE(w);
	lua_pushboolean(L, c8ui_list_is_selected(w,
		(int)luaL_checkinteger(L, 2) - 1));
	return 1;
}

static int list_reveal(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_LIST);
	ALIVE(w);
	c8ui_list_reveal(w, (int)luaL_checkinteger(L, 2) - 1);
	return 0;
}

/* A canvas: draw(g, x, y, width, height) and on_event(event) */

static void canvas_draw(struct c8ui_widget *w, cairo_t *cr, void *data) {
	lua_State *L = c8l;
	if (!push_fn(L, w, "draw")) {
		return;
	}
	lua_pop(L, 1);
	c8l_draw_begin(L, cr, w);
	int g = lua_gettop(L);
	lua_pushvalue(L, g);
	lua_insert(L, g - 1); // g, fn, g
	lua_pushnumber(L, w->rect.x);
	lua_pushnumber(L, w->rect.y);
	lua_pushnumber(L, w->rect.width);
	lua_pushnumber(L, w->rect.height);
	c8l_call(L, 5, 0);
	c8l_draw_end(L, g - 1);
	lua_settop(L, g - 2);
}

static bool canvas_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	lua_State *L = c8l;
	if (ev->type == C8UI_EVENT_MOTION && !w->pressed) {
		return false; // a call per pixel the pointer moves, for nothing
	}
	if (!push_fn(L, w, "on_event")) {
		return false;
	}
	c8l_push_event(L, ev);
	if (!c8l_call(L, 2, 1)) {
		return false;
	}
	bool used = lua_toboolean(L, -1);
	lua_pop(L, 1);
	return used;
}

static int l_canvas(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_canvas_new(c8l_field_num(L, t, "width", 0),
		c8l_field_num(L, t, "height", 0), canvas_draw, canvas_event, NULL);
	if (c8l_field_bool(L, t, "focusable", false)) {
		w->focusable = true;
	}
	lua_pushnil(L);
	lua_setfield(L, t, "width");
	lua_pushnil(L);
	lua_setfield(L, t, "height");
	finish(L, w, K_CANVAS, t, false);
	return 1;
}

/* Pages: PC settings' layout. build(content, index, pages) fills a page */

static void pages_build(struct c8ui_widget *pages, struct c8ui_widget *content,
		void *data) {
	lua_State *L = c8l;
	if (!push_fn(L, pages, "build")) {
		return;
	}
	push_widget(L, content, K_BOX);
	lua_insert(L, -2); // fn, content, pages
	lua_pushinteger(L, c8ui_pages_get(pages) + 1);
	lua_insert(L, -2); // fn, content, index, pages
	c8l_call(L, 3, 0);
}

static void pages_back(struct c8ui_widget *pages, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, pages, "on_back")) {
		c8l_call(L, 1, 0);
	}
}

static int l_pages(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_pages_new(c8l_field_str(L, t, "title", ""),
		c8l_field_num(L, t, "pane_width", 320), pages_build, NULL);
	/* The functions first: adding a page may build it */
	lua_pushnil(L);
	lua_setfield(L, t, "width");
	finish(L, w, K_PAGES, t, false);
	c8ui_pages_on_back(w, pages_back, NULL);
	/* The list's pane in Start's colour, as PC settings has it */
	if (c8l_app) {
		c8ui_widget_set_background(c8ui_pages_pane(w),
			c8ui_app_theme(c8l_app)->background);
	}
	char **names = c8l_strings(L, t, "pages", NULL);
	for (int i = 0; names[i]; i++) {
		c8ui_pages_add(w, names[i]);
	}
	g_strfreev(names);
	return 1;
}

static int pages_rebuild(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_PAGES);
	ALIVE(w);
	c8ui_pages_rebuild(w, lua_toboolean(L, 2));
	return 0;
}

static int pages_go_back(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_PAGES);
	ALIVE(w);
	lua_pushboolean(L, c8ui_pages_back(w));
	return 1;
}

static int pages_sub(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_PAGES);
	ALIVE(w);
	if (lua_gettop(L) >= 2) {
		c8ui_pages_set_sub(w, lua_tostring(L, 2));
		c8ui_pages_rebuild(w, true);
		return 0;
	}
	lua_pushstring(L, c8ui_pages_sub(w));
	return 1;
}

static int pages_narrow(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_PAGES);
	ALIVE(w);
	/* Only asks: the pages fold by themselves */
	lua_pushboolean(L, c8ui_pages_narrow(w));
	return 1;
}

/* Stack, grid, expander, info bar, hub, pivot */

static int l_stack(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_stack_new(), K_STACK, t, true);
	return 1;
}

static int stack_push(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_STACK);
	ALIVE(w);
	struct c8ui_widget *page = c8l_widget(L, 2);
	if (page && page->parent == NULL) {
		c8ui_stack_push(w, page, lua_isnone(L, 3) || lua_toboolean(L, 3));
	}
	return 0;
}

static int stack_pop(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_STACK);
	ALIVE(w);
	bool more = w->child_count > 1;
	if (more) {
		c8ui_stack_pop(w, lua_isnone(L, 2) || lua_toboolean(L, 2));
	}
	lua_pushboolean(L, more);
	return 1;
}

static int l_grid(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_grid_new(
		MAX((int)c8l_field_num(L, t, "columns", 2), 1),
		c8l_field_num(L, t, "column_spacing", 16),
		c8l_field_num(L, t, "row_spacing", 12));
	/* column_widths = { 120, 0 }: a column's width (0: its widest
	 * child's); expand_columns = { 2 }: the columns that take what's
	 * left */
	int columns = MAX((int)c8l_field_num(L, t, "columns", 2), 1);
	double widths[64] = { 0 };
	bool expand[64] = { false };
	lua_getfield(L, t, "column_widths");
	for (lua_Integer i = 1; lua_istable(L, -1) && i <= MIN(columns, 64); i++) {
		lua_geti(L, -1, i);
		widths[i - 1] = lua_tonumber(L, -1);
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
	lua_getfield(L, t, "expand_columns");
	lua_Integer n = lua_istable(L, -1) ? luaL_len(L, -1) : 0;
	for (lua_Integer i = 1; i <= n; i++) {
		lua_geti(L, -1, i);
		lua_Integer c = lua_tointeger(L, -1);
		if (c >= 1 && c <= 64) {
			expand[c - 1] = true;
		}
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
	for (int i = 0; i < MIN(columns, 64); i++) {
		if (widths[i] > 0 || expand[i]) {
			c8ui_grid_set_column(w, i, widths[i], expand[i]);
		}
	}
	finish(L, w, K_GRID, t, true);
	return 1;
}

/* grid:span(child, columns): a child across several columns */
static int grid_span(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_GRID);
	ALIVE(w);
	struct c8ui_widget *child = c8l_widget(L, 2);
	if (child && child->parent == NULL) {
		c8ui_grid_add(w, child, MAX((int)luaL_optinteger(L, 3, 1), 1));
	}
	return 0;
}

static int l_expander(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *content = NULL;
	if (lua_geti(L, t, 1) == LUA_TUSERDATA) {
		content = c8l_widget(L, -1);
	}
	lua_pop(L, 1);
	if (content == NULL || content->parent) {
		return luaL_error(L, "c8.expander{ title = ..., widget }");
	}
	finish(L, c8ui_expander_new(c8l_field_str(L, t, "title", ""), content,
		c8l_field_bool(L, t, "expanded", false), changed, NULL), K_EXPANDER,
		t, false);
	return 1;
}

static const char *const severities[] = { "info", "success", "warning",
	"error", NULL };

static void infobar_closed(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_close")) {
		c8l_call(L, 1, 0);
	}
}

static int l_infobar(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_infobar_new(field_option(L, t, "severity",
		severities, C8UI_SEVERITY_INFO), c8l_field_str(L, t, "title", NULL),
		c8l_field_str(L, t, "message", NULL));
	if (c8l_field_bool(L, t, "closable", false)) {
		c8ui_infobar_set_closable(w, true, infobar_closed, NULL);
	}
	finish(L, w, K_INFOBAR, t, false);
	return 1;
}

static int infobar_action(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_INFOBAR);
	ALIVE(w);
	struct c8ui_widget *button = c8ui_infobar_add_action(w,
		luaL_checkstring(L, 2), clicked, NULL);
	push_widget(L, button, K_PLAIN);
	lua_getiuservalue(L, -1, 1);
	lua_pushvalue(L, 3);
	lua_setfield(L, -2, "on_click");
	lua_pop(L, 1);
	return 1;
}

/* sections = { { header = "Today", width = 400, widget }, ... } */
static int l_hub(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_hub_new(c8l_field_str(L, t, "title", NULL));
	/* Narrow: one column going down, instead of a pivot */
	c8ui_hub_set_narrow_column(w, c8l_field_bool(L, t, "narrow_column", false));
	lua_getfield(L, t, "sections");
	lua_Integer n = lua_istable(L, -1) ? luaL_len(L, -1) : 0;
	int added = 0;
	for (lua_Integer i = 1; i <= n; i++) {
		lua_geti(L, -1, i);
		if (lua_istable(L, -1) && lua_geti(L, -1, 1) == LUA_TUSERDATA) {
			struct c8ui_widget *content = c8l_widget(L, -1);
			if (content && content->parent == NULL) {
				c8ui_hub_add(w, c8l_field_str(L, -2, "header", NULL), content,
					c8l_field_num(L, -2, "width", 0));
				/* What it's called narrow, when it has no header */
				const char *name = c8l_field_str(L, -2, "name", NULL);
				if (name) {
					c8ui_hub_set_name(w, added, name);
				}
				added++;
			}
			lua_pop(L, 1);
		}
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
	finish(L, w, K_HUB, t, false);
	return 1;
}

/* tabs = { { title = "All", widget }, ... } */
static int l_pivot(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_pivot_new(changed, NULL);
	lua_getfield(L, t, "tabs");
	lua_Integer n = lua_istable(L, -1) ? luaL_len(L, -1) : 0;
	for (lua_Integer i = 1; i <= n; i++) {
		lua_geti(L, -1, i);
		if (lua_istable(L, -1)) {
			/* { title = "...", widget } or { title, widget = w } */
			if (lua_getfield(L, -1, "widget") != LUA_TUSERDATA) {
				lua_pop(L, 1);
				lua_geti(L, -1, 1);
			}
			struct c8ui_widget *page = lua_type(L, -1) == LUA_TUSERDATA ?
				c8l_widget(L, -1) : NULL;
			if (page && page->parent == NULL) {
				c8ui_pivot_add(w, c8l_field_str(L, -2, "title", ""), page);
			}
			lua_pop(L, 1);
		}
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
	c8ui_pivot_set_title(w, c8l_field_str(L, t, "title", NULL));
	c8ui_pivot_set_wrap(w, c8l_field_bool(L, t, "wrap", false));
	finish(L, w, K_PIVOT, t, false);
	return 1;
}

static int hub_title(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_HUB);
	ALIVE(w);
	c8ui_hub_set_title(w, luaL_optstring(L, 2, NULL));
	return 0;
}

/* hub:show(n): pans to section n */
static int hub_show(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_HUB);
	ALIVE(w);
	c8ui_hub_show(w, (int)luaL_checkinteger(L, 2) - 1);
	return 0;
}

static int pivot_title(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_PIVOT);
	ALIVE(w);
	c8ui_pivot_set_title(w, luaL_optstring(L, 2, NULL));
	return 0;
}

static int pivot_wrap(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_PIVOT);
	ALIVE(w);
	c8ui_pivot_set_wrap(w, lua_toboolean(L, 2));
	return 0;
}

/* Nav, pickers, flip view, split, tree, columns, semantic zoom, viewbox,
 * toggle and repeat buttons, item containers, media transport */

/* The first two widgets of the options' list, which aren't in anything
 * yet (what a split or zoom is made of) */
static void two_widgets(lua_State *L, int t, const char *usage,
		struct c8ui_widget **first, struct c8ui_widget **second) {
	struct c8ui_widget *w[2] = { NULL, NULL };
	for (int i = 0; i < 2; i++) {
		if (lua_geti(L, t, i + 1) == LUA_TUSERDATA) {
			w[i] = c8l_widget(L, -1);
		}
		lua_pop(L, 1);
		if (w[i] == NULL || w[i]->parent) {
			luaL_error(L, "%s", usage);
		}
	}
	if (w[0] == w[1]) {
		luaL_error(L, "%s", usage);
	}
	*first = w[0];
	*second = w[1];
}

/* The one widget of the options' list, which isn't in anything yet */
static struct c8ui_widget *one_widget(lua_State *L, int t, const char *usage) {
	struct c8ui_widget *w = NULL;
	if (lua_geti(L, t, 1) == LUA_TUSERDATA) {
		w = c8l_widget(L, -1);
	}
	lua_pop(L, 1);
	if (w == NULL || w->parent) {
		luaL_error(L, "%s", usage);
	}
	return w;
}

/* c8.nav { items = { ... }, selected, menu, inset, on_change } */
static int l_nav(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_nav_new(changed, NULL);
	int count = 0;
	char **items = c8l_strings(L, t, "items", &count);
	for (int i = 0; i < count; i++) {
		c8ui_nav_add(w, items[i]);
	}
	g_strfreev(items);
	double inset = c8l_field_num(L, t, "inset", -1);
	if (inset >= 0) {
		c8ui_nav_set_inset(w, inset);
	}
	if (c8l_field_bool(L, t, "menu", false)) {
		c8ui_nav_set_menu(w, true);
	}
	lua_getfield(L, t, "selected");
	if (lua_isnumber(L, -1)) {
		c8ui_nav_set(w, (int)lua_tointeger(L, -1) - 1);
	}
	lua_pop(L, 1);
	finish(L, w, K_NAV, t, false);
	return 1;
}

static int nav_menu(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_NAV);
	ALIVE(w);
	c8ui_nav_set_menu(w, lua_toboolean(L, 2));
	return 0;
}

/* c8.number { header, min, max, step, value, digits, on_change } */
static int l_number(lua_State *L) {
	int t = opts_of(L);
	double min = c8l_field_num(L, t, "min", 0);
	finish(L, c8ui_number_new(c8l_field_str(L, t, "header", NULL), min,
		c8l_field_num(L, t, "max", 100), c8l_field_num(L, t, "step", 1),
		c8l_field_num(L, t, "value", min),
		CLAMP((int)c8l_field_num(L, t, "digits", 0), 0, 6), changed, NULL),
		K_NUMBER, t, false);
	return 1;
}

/* c8.rating { max, value, readonly, on_change } */
static int l_rating(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_rating_new(MAX((int)c8l_field_num(L, t,
		"max", 5), 1), c8l_field_num(L, t, "value", 0), changed, NULL);
	if (c8l_field_bool(L, t, "readonly", false)) {
		c8ui_rating_set_readonly(w, true);
	}
	finish(L, w, K_RATING, t, false);
	return 1;
}

/* Today, for a date or calendar given none */
static void today(int *y, int *m, int *d) {
	GDateTime *now = g_date_time_new_now_local();
	g_date_time_get_ymd(now, y, m, d);
	g_date_time_unref(now);
}

/* c8.date { header, year, month, day, first_year, last_year, on_change } */
static int l_date(lua_State *L) {
	int t = opts_of(L);
	int y, m, d;
	today(&y, &m, &d);
	struct c8ui_widget *w = c8ui_date_new(c8l_field_str(L, t, "header", NULL),
		(int)c8l_field_num(L, t, "year", y), (int)c8l_field_num(L, t, "month", m),
		(int)c8l_field_num(L, t, "day", d), changed, NULL);
	int first = (int)c8l_field_num(L, t, "first_year", 0);
	int last = (int)c8l_field_num(L, t, "last_year", 0);
	if (first > 0 && last >= first) {
		c8ui_date_set_years(w, first, last);
	}
	finish(L, w, K_DATE, t, false);
	return 1;
}

/* c8.time { header, hour, minute, clock24, minute_step, on_change } */
static int l_time(lua_State *L) {
	int t = opts_of(L);
	GDateTime *now = g_date_time_new_now_local();
	struct c8ui_widget *w = c8ui_time_new(c8l_field_str(L, t, "header", NULL),
		(int)c8l_field_num(L, t, "hour", g_date_time_get_hour(now)),
		(int)c8l_field_num(L, t, "minute", g_date_time_get_minute(now)),
		changed, NULL);
	g_date_time_unref(now);
	lua_getfield(L, t, "clock24");
	if (!lua_isnil(L, -1)) {
		c8ui_time_set_24h(w, lua_toboolean(L, -1));
	}
	lua_pop(L, 1);
	int step = (int)c8l_field_num(L, t, "minute_step", 0);
	if (step > 1) {
		c8ui_time_set_minute_step(w, step);
	}
	finish(L, w, K_TIME, t, false);
	return 1;
}

/* marks(year, month, day): true for a dot under the day */
static bool calendar_mark(int year, int month, int day, void *data) {
	lua_State *L = c8l;
	if (!push_fn(L, data, "marks")) {
		return false;
	}
	lua_pop(L, 1);
	lua_pushinteger(L, year);
	lua_pushinteger(L, month);
	lua_pushinteger(L, day);
	if (!c8l_call(L, 3, 1)) {
		return false;
	}
	bool marked = lua_toboolean(L, -1);
	lua_pop(L, 1);
	return marked;
}

static void calendar_month(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_month")) {
		int y, m;
		c8ui_calendar_get_month(w, &y, &m);
		lua_pushinteger(L, y);
		lua_pushinteger(L, m);
		c8l_call(L, 3, 0);
	}
}

/* c8.calendar { year, month, day, marks, on_change, on_month } */
static int l_calendar(lua_State *L) {
	int t = opts_of(L);
	int y, m, d;
	today(&y, &m, &d);
	struct c8ui_widget *w = c8ui_calendar_new((int)c8l_field_num(L, t, "year",
		y), (int)c8l_field_num(L, t, "month", m),
		(int)c8l_field_num(L, t, "day", d), changed, NULL);
	c8ui_calendar_on_month(w, calendar_month, NULL);
	finish(L, w, K_CALENDAR, t, false);
	/* Asked as it draws, so the script's marks are there by then */
	c8ui_calendar_set_marks(w, calendar_mark, w);
	return 1;
}

/* c8.flip { dots, on_change, page, page, ... } */
static int l_flip(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_flip_new(changed, NULL);
	if (c8l_field_bool(L, t, "dots", false)) {
		c8ui_flip_set_dots(w, true);
	}
	finish(L, w, K_FLIP, t, true);
	return 1;
}

/* c8.split { first, second, position, share, vertical, min = { a, b },
 * on_change } */
static int l_split(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *first, *second;
	two_widgets(L, t, "c8.split{ first, second }: two widgets, not in "
		"anything yet", &first, &second);
	struct c8ui_widget *w = c8ui_split_new(c8l_field_bool(L, t, "vertical",
		false) ? C8UI_VERTICAL : C8UI_HORIZONTAL, first, second,
		c8l_field_num(L, t, "position", 300));
	lua_getfield(L, t, "min");
	if (lua_istable(L, -1)) {
		lua_geti(L, -1, 1);
		lua_geti(L, -2, 2);
		c8ui_split_set_min(w, luaL_optnumber(L, -2, 100),
			luaL_optnumber(L, -1, 100));
		lua_pop(L, 2);
	}
	lua_pop(L, 1);
	if (lua_getfield(L, t, "share") == LUA_TNUMBER) {
		c8ui_split_set_share(w, lua_tonumber(L, -1));
	}
	lua_pop(L, 1);
	c8ui_split_on_change(w, changed, NULL);
	finish(L, w, K_SPLIT, t, false);
	return 1;
}

/* split:vertical(bool): one pane over the other, or side by side */
static int split_vertical(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_SPLIT);
	ALIVE(w);
	c8ui_split_set_orientation(w, lua_toboolean(L, 2) ? C8UI_VERTICAL :
		C8UI_HORIZONTAL);
	return 0;
}

/* split:share(n): the first pane's share of the room, kept as it
 * changes (0 goes back to the position); split:share() reads it */
static int split_share(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_SPLIT);
	ALIVE(w);
	if (lua_isnoneornil(L, 2)) {
		lua_pushnumber(L, c8ui_split_get_share(w));
		return 1;
	}
	c8ui_split_set_share(w, luaL_checknumber(L, 2));
	return 0;
}

/* Trees: items are the numbers the tree hands out; 0 is the top */

static void tree_call(struct c8ui_widget *tree, int item, const char *name) {
	lua_State *L = c8l;
	if (push_fn(L, tree, name)) {
		lua_pushinteger(L, item);
		c8l_call(L, 2, 0);
	}
}

static void tree_expanding(struct c8ui_widget *tree, int item, void *data) {
	tree_call(tree, item, "on_expand");
}

static void tree_selected(struct c8ui_widget *tree, int item, void *data) {
	tree_call(tree, item, "on_select");
}

static void tree_opened(struct c8ui_widget *tree, int item, void *data) {
	tree_call(tree, item, "on_open");
}

static void tree_context(struct c8ui_widget *tree, int item, double x,
		double y, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, tree, "on_context")) {
		lua_pushinteger(L, item);
		lua_pushnumber(L, x);
		lua_pushnumber(L, y);
		c8l_call(L, 4, 0);
	}
}

/* c8.tree { on_expand, on_select, on_open, on_context } */
static int l_tree(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_tree_new();
	c8ui_tree_on_expand(w, tree_expanding, NULL);
	c8ui_tree_on_select(w, tree_selected, NULL);
	c8ui_tree_on_open(w, tree_opened, NULL);
	c8ui_tree_on_context(w, tree_context, NULL);
	finish(L, w, K_TREE, t, false);
	return 1;
}

/* tree:add(parent, label [, icon]): the new item */
static int tree_add(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TREE);
	ALIVE(w);
	lua_pushinteger(L, c8ui_tree_add(w, (int)luaL_checkinteger(L, 2),
		luaL_optstring(L, 4, NULL), luaL_checkstring(L, 3), NULL));
	return 1;
}

static int tree_remove(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TREE);
	ALIVE(w);
	c8ui_tree_remove(w, (int)luaL_checkinteger(L, 2));
	return 0;
}

/* tree:clear([item]): takes away what is under it (all of it: 0) */
static int tree_clear(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TREE);
	ALIVE(w);
	c8ui_tree_clear(w, (int)luaL_optinteger(L, 2, 0));
	return 0;
}

/* tree:label(item [, text]) */
static int tree_label(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TREE);
	ALIVE(w);
	int item = (int)luaL_checkinteger(L, 2);
	if (lua_gettop(L) >= 3) {
		c8ui_tree_set_label(w, item, luaL_checkstring(L, 3));
		return 0;
	}
	lua_pushstring(L, c8ui_tree_get_label(w, item));
	return 1;
}

static int tree_parent(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TREE);
	ALIVE(w);
	lua_pushinteger(L, c8ui_tree_get_parent(w, (int)luaL_checkinteger(L, 2)));
	return 1;
}

/* tree:expanded(item [, bool]) */
static int tree_expanded(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TREE);
	ALIVE(w);
	int item = (int)luaL_checkinteger(L, 2);
	if (lua_gettop(L) >= 3) {
		c8ui_tree_set_expanded(w, item, lua_toboolean(L, 3));
		return 0;
	}
	lua_pushboolean(L, c8ui_tree_get_expanded(w, item));
	return 1;
}

/* tree:has_children(item, bool): an arrow before there are any, so they
 * can be added in on_expand */
static int tree_has_children(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TREE);
	ALIVE(w);
	c8ui_tree_set_has_children(w, (int)luaL_checkinteger(L, 2),
		lua_isnone(L, 3) || lua_toboolean(L, 3));
	return 0;
}

/* c8.columns { columns = { { "Name", 220 }, ... }, sort, descending,
 * on_change } */
static int l_columns(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_columns_new(changed, NULL);
	lua_getfield(L, t, "columns");
	lua_Integer n = lua_istable(L, -1) ? luaL_len(L, -1) : 0;
	for (lua_Integer i = 1; i <= n; i++) {
		if (lua_geti(L, -1, i) == LUA_TTABLE) {
			lua_geti(L, -1, 1);
			lua_geti(L, -2, 2);
			c8ui_columns_add(w, luaL_optstring(L, -2, ""),
				luaL_optnumber(L, -1, 0));
			lua_pop(L, 2);
		} else if (lua_type(L, -1) == LUA_TSTRING) {
			c8ui_columns_add(w, lua_tostring(L, -1), 0);
		}
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
	lua_getfield(L, t, "sort");
	if (lua_isnumber(L, -1)) {
		c8ui_columns_set_sort(w, (int)lua_tointeger(L, -1) - 1,
			c8l_field_bool(L, t, "descending", false));
	}
	lua_pop(L, 1);
	finish(L, w, K_COLUMNS, t, false);
	return 1;
}

/* columns:width(column, px) */
static int columns_width(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_COLUMNS);
	ALIVE(w);
	c8ui_columns_set_width(w, (int)luaL_checkinteger(L, 2) - 1,
		luaL_checknumber(L, 3));
	return 0;
}

/* c8.zoom { detail, overview, on_change } */
static int l_zoom(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *in, *out;
	two_widgets(L, t, "c8.zoom{ detail, overview }: two widgets, not in "
		"anything yet", &in, &out);
	finish(L, c8ui_zoom_new(in, out, changed, NULL), K_ZOOM, t, false);
	return 1;
}

/* zoom:show(widget): back to the detail, scrolled to show widget */
static int zoom_show(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_ZOOM);
	ALIVE(w);
	c8ui_zoom_in_to(w, lua_isnoneornil(L, 2) ? NULL : c8l_widget(L, 2));
	return 0;
}

/* c8.viewbox { widget, grow } */
static int l_viewbox(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_viewbox_new(one_widget(L, t,
		"c8.viewbox{ widget }: a widget not in anything yet"));
	if (c8l_field_bool(L, t, "grow", false)) {
		c8ui_viewbox_set_grow(w, true);
	}
	finish(L, w, K_PLAIN, t, false);
	return 1;
}

/* c8.toggle_button { label, on, on_change } */
static int l_toggle_button(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_togglebutton_new(c8l_field_str(L, t, "label", ""),
		c8l_field_bool(L, t, "on", false), changed, NULL), K_TOGGLE_BUTTON, t,
		false);
	return 1;
}

/* c8.repeat_button { label, on_click }: on_click again and again while
 * it is held */
static int l_repeat_button(lua_State *L) {
	int t = opts_of(L);
	finish(L, c8ui_repeat_button_new(c8l_field_str(L, t, "label", ""),
		clicked, NULL), K_REPEAT, t, false);
	return 1;
}

static void item_invoked(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_invoke")) {
		c8l_call(L, 1, 0);
	}
}

static void item_selected(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, w, "on_select")) {
		lua_pushboolean(L, c8ui_item_container_get_selected(w));
		c8l_call(L, 2, 0);
	}
}

static const char *const taps[] = { "select", "invoke", "none", NULL };

/* c8.item { widget, tap, selectable, selected, on_invoke, on_select } */
static int l_item(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_item_container_new(one_widget(L, t,
		"c8.item{ widget }: a widget not in anything yet"));
	c8ui_item_container_set_tap(w, field_option(L, t, "tap", taps,
		C8UI_ITEM_TAP_SELECT));
	if (!c8l_field_bool(L, t, "selectable", true)) {
		c8ui_item_container_set_selectable(w, false);
	}
	if (c8l_field_bool(L, t, "selected", false)) {
		c8ui_item_container_set_selected(w, true);
	}
	c8ui_item_container_on_invoke(w, item_invoked, NULL);
	c8ui_item_container_on_select(w, item_selected, NULL);
	finish(L, w, K_ITEM, t, false);
	return 1;
}

static const char *const transport_actions[] = {
	[C8UI_TRANSPORT_PLAY] = "play", [C8UI_TRANSPORT_PAUSE] = "pause",
	[C8UI_TRANSPORT_PREVIOUS] = "previous", [C8UI_TRANSPORT_NEXT] = "next",
	[C8UI_TRANSPORT_SEEK] = "seek", [C8UI_TRANSPORT_VOLUME] = "volume",
	[C8UI_TRANSPORT_MUTE] = "mute",
	[C8UI_TRANSPORT_FULLSCREEN] = "fullscreen",
};

static void transport_acted(struct c8ui_widget *w,
		enum c8ui_transport_action action, double value, void *data) {
	lua_State *L = c8l;
	if ((size_t)action < G_N_ELEMENTS(transport_actions) &&
			push_fn(L, w, "on_action")) {
		lua_pushstring(L, transport_actions[action]);
		lua_pushnumber(L, value);
		c8l_call(L, 3, 0);
	}
}

/* c8.transport { duration, buffered, skip, fullscreen, on_action }:
 * on_action(w, "play" | "pause" | "previous" | "next" | "seek" |
 * "volume" | "mute" | "fullscreen", value) */
static int l_transport(lua_State *L) {
	int t = opts_of(L);
	struct c8ui_widget *w = c8ui_transport_new(transport_acted, NULL);
	c8ui_transport_set_duration(w, c8l_field_num(L, t, "duration", 0));
	c8ui_transport_set_buffered(w, c8l_field_num(L, t, "buffered", 0));
	c8ui_transport_set_buttons(w, c8l_field_bool(L, t, "skip", false),
		c8l_field_bool(L, t, "fullscreen", true));
	finish(L, w, K_TRANSPORT, t, false);
	return 1;
}

static int transport_playing(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TRANSPORT);
	ALIVE(w);
	c8ui_transport_set_playing(w, lua_toboolean(L, 2));
	return 0;
}

static int transport_position(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TRANSPORT);
	ALIVE(w);
	c8ui_transport_set_position(w, luaL_checknumber(L, 2));
	return 0;
}

static int transport_duration(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TRANSPORT);
	ALIVE(w);
	c8ui_transport_set_duration(w, luaL_checknumber(L, 2));
	return 0;
}

static int transport_buffered(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TRANSPORT);
	ALIVE(w);
	c8ui_transport_set_buffered(w, luaL_checknumber(L, 2));
	return 0;
}

/* transport:volume(0 to 1 [, muted]) */
static int transport_volume(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TRANSPORT);
	ALIVE(w);
	c8ui_transport_set_volume(w, luaL_checknumber(L, 2), lua_toboolean(L, 3));
	return 0;
}

static int transport_fullscreen(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TRANSPORT);
	ALIVE(w);
	c8ui_transport_set_fullscreen(w, lua_toboolean(L, 2));
	return 0;
}

/* transport:live(): the seek bar or volume is being dragged */
static int transport_live(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_TRANSPORT);
	ALIVE(w);
	lua_pushboolean(L, c8ui_transport_is_live(w));
	return 1;
}

/* Windows */

static struct window *window_at(lua_State *L, int index) {
	return luaL_checkudata(L, index, WINDOW_META);
}

#define OPEN(win) if ((win)->win == NULL) { return 0; }

/* Pushes the function `name` of the window and the window */
static bool push_window_fn(lua_State *L, struct window *win,
		const char *name) {
	lua_getfield(L, LUA_REGISTRYINDEX, LIVE);
	if (lua_rawgetp(L, -1, win) != LUA_TUSERDATA) {
		lua_pop(L, 2);
		return false;
	}
	lua_remove(L, -2);
	lua_getiuservalue(L, -1, 1);
	lua_getfield(L, -1, name);
	if (!lua_isfunction(L, -1)) {
		lua_pop(L, 3);
		return false;
	}
	lua_remove(L, -2);
	lua_insert(L, -2);
	return true;
}

static void window_gone(struct c8ui_widget *w, void *data) {
	lua_State *L = c8l;
	struct window *win = data;
	if (push_window_fn(L, win, "on_close")) {
		c8l_call(L, 1, 0);
	}
	win->win = NULL;
	win->holder = NULL;
	win->appbar = NULL;
	win->navbar = NULL;
	lua_getfield(L, LUA_REGISTRYINDEX, LIVE);
	lua_pushnil(L);
	lua_rawsetp(L, -2, win);
	lua_pop(L, 1);
}

/* Closed by the compositor (Alt+F4, its button): can_close(win) returning
 * false keeps the window, for asking first */
static bool window_can_close(struct c8ui_window *cw, void *data) {
	lua_State *L = c8l;
	struct window *win = data;
	if (!push_window_fn(L, win, "can_close")) {
		return true;
	}
	if (!c8l_call(L, 1, 1)) {
		return true;
	}
	bool keep = lua_isboolean(L, -1) && !lua_toboolean(L, -1);
	lua_pop(L, 1);
	return !keep;
}

static void window_resized(struct c8ui_root *root, double width,
		double height, void *data) {
	lua_State *L = c8l;
	if (push_window_fn(L, data, "on_resize")) {
		lua_pushnumber(L, width);
		lua_pushnumber(L, height);
		lua_pushboolean(L, c8ui_root_is_narrow(root));
		c8l_call(L, 4, 0);
	}
}

/* Keys nothing took: the app's on_key first (true: used), then Menu for
 * the app bar */
static bool window_key(const struct c8ui_event *ev, void *data) {
	lua_State *L = c8l;
	struct window *win = data;
	if (push_window_fn(L, win, "on_key")) {
		c8l_push_event(L, ev);
		if (c8l_call(L, 2, 1)) {
			bool used = lua_toboolean(L, -1);
			lua_pop(L, 1);
			if (used) {
				return true;
			}
		}
	}
	if (win->win && win->appbar && ev->sym == 0xff67) { // XKB_KEY_Menu
		c8ui_appbar_toggle(win->appbar);
		return true;
	}
	return false;
}

static void set_child(lua_State *L, struct window *win, int index) {
	struct c8ui_widget *child = c8l_widget(L, index);
	if (child == NULL) {
		return;
	}
	if (child->parent) {
		luaL_error(L, "that widget is already in something");
	}
	c8ui_widget_clear(win->holder);
	child->fill = true;
	child->expand = true;
	c8ui_widget_add(win->holder, child);
}

/* c8.window{ title, width, height, widget, on_resize, on_key, on_close } */
static int l_window(lua_State *L) {
	int t = opts_of(L);
	if (c8l_app == NULL) {
		return luaL_error(L, "windows are made in the app's startup or open "
			"function, not before");
	}
	struct c8ui_window *cw = c8ui_window_new(c8l_app,
		c8l_field_str(L, t, "title", ""), (int)c8l_field_num(L, t, "width", 900),
		(int)c8l_field_num(L, t, "height", 640));
	if (cw == NULL) {
		return luaL_error(L, "the window couldn't be made");
	}
	struct window *win = lua_newuserdatauv(L, sizeof(*win), 1);
	win->win = cw;
	win->appbar = NULL;
	win->navbar = NULL;
	luaL_setmetatable(L, WINDOW_META);
	lua_newtable(L);
	static const char *const fns[] = { "on_resize", "on_key", "on_close",
		"can_close" };
	for (size_t i = 0; i < G_N_ELEMENTS(fns); i++) {
		lua_getfield(L, t, fns[i]);
		lua_setfield(L, -2, fns[i]);
	}
	lua_setiuservalue(L, -2, 1);
	lua_getfield(L, LUA_REGISTRYINDEX, LIVE);
	lua_pushvalue(L, -2);
	lua_rawsetp(L, -2, win);
	lua_pop(L, 1);

	struct c8ui_root *root = c8ui_window_root(cw);
	win->holder = c8ui_box_new(C8UI_VERTICAL, 0);
	win->holder->fill = true;
	win->holder->user_data = win;
	win->holder->on_destroy = window_gone;
	c8ui_root_set_child(root, win->holder);
	c8ui_root_on_resize(root, window_resized, win);
	c8ui_root_set_key_handler(root, window_key, win);
	c8ui_window_on_close_request(cw, window_can_close, win);
	lua_getfield(L, t, "background");
	if (!lua_isnil(L, -1)) {
		c8ui_window_set_background(cw, c8l_color(L, -1, 0xffffff), 1);
	}
	lua_pop(L, 1);
	if (lua_geti(L, t, 1) == LUA_TUSERDATA) {
		set_child(L, win, lua_gettop(L));
	}
	lua_pop(L, 1);
	return 1;
}

static int window_index(lua_State *L) {
	struct window *win = window_at(L, 1);
	const char *key = lua_tostring(L, 2);
	if (key && luaL_getmetafield(L, 1, "methods") == LUA_TTABLE) {
		if (lua_getfield(L, -1, key) != LUA_TNIL) {
			return 1;
		}
		lua_pop(L, 2);
	}
	struct c8ui_root *root = win->win ? c8ui_window_root(win->win) : NULL;
	if (key && strcmp(key, "open") == 0) {
		lua_pushboolean(L, win->win != NULL);
	} else if (key && root && strcmp(key, "width") == 0) {
		lua_pushnumber(L, c8ui_root_width(root));
	} else if (key && root && strcmp(key, "height") == 0) {
		lua_pushnumber(L, c8ui_root_height(root));
	} else if (key && root && strcmp(key, "narrow") == 0) {
		lua_pushboolean(L, c8ui_root_is_narrow(root));
	} else {
		lua_getiuservalue(L, 1, 1);
		lua_pushvalue(L, 2);
		lua_gettable(L, -2);
	}
	return 1;
}

static int window_newindex(lua_State *L) {
	window_at(L, 1);
	lua_getiuservalue(L, 1, 1);
	lua_pushvalue(L, 2);
	lua_pushvalue(L, 3);
	lua_settable(L, -3);
	return 0;
}

static int win_set(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	set_child(L, win, 2);
	return 0;
}

static int win_present(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	c8ui_window_present(win->win);
	return 0;
}

static int win_title(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	c8ui_window_set_title(win->win, luaL_checkstring(L, 2));
	return 0;
}

static int win_close(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	c8ui_window_destroy(win->win);
	/* The last one closed ends the app, as when the user closes it: a
	 * hold let go with no windows left quits */
	c8ui_app_hold(c8l_app);
	c8ui_app_release(c8l_app);
	return 0;
}

static int win_fullscreen(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	if (lua_gettop(L) >= 2) {
		c8ui_window_set_fullscreen(win->win, lua_toboolean(L, 2));
		return 0;
	}
	lua_pushboolean(L, c8ui_window_is_fullscreen(win->win));
	return 1;
}

static int win_open_uri(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	c8ui_window_open_uri(win->win, luaL_checkstring(L, 2));
	return 0;
}

static int win_copy(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	c8ui_root_set_clipboard(c8ui_window_root(win->win),
		luaL_checkstring(L, 2));
	return 0;
}

/* One-shot callbacks that have no widget: a kept function, freed when
 * it has run */
struct once {
	int ref;
};

static struct once *once_new(lua_State *L, int index) {
	struct once *o = g_new0(struct once, 1);
	o->ref = c8l_ref(L, index);
	return o;
}

/* Pushes the function and frees; false when there was none */
static bool once_take(lua_State *L, struct once *o) {
	bool have = c8l_push_ref(L, o->ref);
	c8l_unref(L, o->ref);
	g_free(o);
	return have;
}

static void pasted(void *data, const char *text) {
	lua_State *L = c8l;
	if (once_take(L, data)) {
		lua_pushstring(L, text);
		c8l_call(L, 1, 0);
	}
}

static int win_paste(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	luaL_checktype(L, 2, LUA_TFUNCTION);
	c8ui_root_request_paste(c8ui_window_root(win->win), pasted,
		once_new(L, 2));
	return 0;
}

static void choice_made(int choice, void *data) {
	lua_State *L = c8l;
	if (once_take(L, data)) {
		if (choice < 0) {
			lua_pushnil(L);
		} else {
			lua_pushinteger(L, choice + 1);
		}
		c8l_call(L, 1, 0);
	}
}

/* win:dialog{ title, message, buttons = {...}, done = fn(choice), widget } */
static int win_dialog(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	luaL_checktype(L, 2, LUA_TTABLE);
	int count = 0;
	char **buttons = c8l_strings(L, 2, "buttons", &count);
	if (count == 0) {
		g_strfreev(buttons);
		buttons = g_strsplit("Close", "\n", 0);
		count = 1;
	}
	lua_getfield(L, 2, "done");
	struct once *o = once_new(L, -1);
	lua_pop(L, 1);
	struct c8ui_widget *dialog = c8ui_dialog_show(c8ui_window_root(win->win),
		c8l_field_str(L, 2, "title", ""), c8l_field_str(L, 2, "message", ""),
		(const char *const *)buttons, count, choice_made, o);
	g_strfreev(buttons);
	if (lua_geti(L, 2, 1) == LUA_TUSERDATA) {
		struct c8ui_widget *more = c8l_widget(L, -1);
		if (more && more->parent == NULL) {
			c8ui_dialog_add(dialog, more);
		}
	}
	lua_pop(L, 1);
	push_widget(L, dialog, K_PLAIN);
	return 1;
}

static int win_message(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	c8ui_dialog_message(c8ui_window_root(win->win), luaL_checkstring(L, 2),
		luaL_optstring(L, 3, ""));
	return 0;
}

/* Where a menu or flyout goes: at = widget (under it), or x and y */
static struct c8ui_rect anchor(lua_State *L, int t) {
	struct c8ui_rect r = { c8l_field_num(L, t, "x", 0),
		c8l_field_num(L, t, "y", 0), 0, 0 };
	if (lua_getfield(L, t, "at") == LUA_TUSERDATA) {
		struct c8ui_widget *at = c8l_widget(L, -1);
		if (at) {
			r = at->rect;
		}
	}
	lua_pop(L, 1);
	return r;
}

/* A menu's items from the list at index: "Cut", "-" (a line), or
 * { label, id, check, radio, checked, disabled, shortcut, submenu }. An
 * item without an id is numbered in reading order, submenus' items too,
 * from 1. The arrays go in keep; the strings stay the tables' until the
 * menu is shown (which copies them). */
static struct c8ui_menu_item *menu_items(lua_State *L, int index, int *count,
		int *next, GPtrArray *keep) {
	index = lua_absindex(L, index);
	lua_Integer n = luaL_len(L, index);
	struct c8ui_menu_item *items = g_new0(struct c8ui_menu_item, MAX(n, 1));
	g_ptr_array_add(keep, items);
	for (lua_Integer i = 1; i <= n; i++) {
		struct c8ui_menu_item *it = &items[i - 1];
		int type = lua_geti(L, index, i);
		if (type == LUA_TSTRING && strcmp(lua_tostring(L, -1), "-") == 0) {
			it->kind = C8UI_MENU_SEPARATOR;
		} else if (type == LUA_TSTRING) {
			it->label = lua_tostring(L, -1);
			it->id = (*next)++;
		} else if (type == LUA_TTABLE) {
			int t = lua_gettop(L);
			it->label = c8l_field_str(L, t, "label", NULL);
			if (it->label == NULL) {
				lua_geti(L, t, 1);
				it->label = lua_tostring(L, -1);
				lua_pop(L, 1); // the table still holds the string
			}
			it->id = (int)c8l_field_num(L, t, "id", *next);
			(*next)++;
			it->kind = c8l_field_bool(L, t, "separator", false) ?
				C8UI_MENU_SEPARATOR : c8l_field_bool(L, t, "check", false) ?
				C8UI_MENU_CHECK : c8l_field_bool(L, t, "radio", false) ?
				C8UI_MENU_RADIO : C8UI_MENU_COMMAND;
			it->checked = c8l_field_bool(L, t, "checked", false);
			it->disabled = c8l_field_bool(L, t, "disabled", false);
			it->shortcut = c8l_field_str(L, t, "shortcut", NULL);
			if (lua_getfield(L, t, "submenu") == LUA_TTABLE) {
				it->submenu = menu_items(L, -1, &it->submenu_count, next, keep);
			}
			lua_pop(L, 1);
		}
		lua_pop(L, 1);
	}
	*count = (int)n;
	return items;
}

static void menu_chosen(int id, void *data) {
	lua_State *L = c8l;
	if (once_take(L, data)) {
		if (id < 0) {
			lua_pushnil(L);
		} else {
			lua_pushinteger(L, id);
		}
		c8l_call(L, 1, 0);
	}
}

/* win:menu{ items = {...}, at = widget | x, y, above, done = fn(id) } */
static int win_menu(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	luaL_checktype(L, 2, LUA_TTABLE);
	struct c8ui_rect r = anchor(L, 2);
	GPtrArray *keep = g_ptr_array_new_with_free_func(g_free);
	int count = 0, next = 1;
	struct c8ui_menu_item *items = NULL;
	if (lua_getfield(L, 2, "items") == LUA_TTABLE) {
		items = menu_items(L, -1, &count, &next, keep);
	}
	lua_getfield(L, 2, "done");
	struct once *o = once_new(L, -1);
	lua_pop(L, 1);
	c8ui_menu_show_items(c8ui_window_root(win->win), r.x, r.y + r.height,
		c8l_field_bool(L, 2, "above", false), items, count, menu_chosen, o);
	lua_pop(L, 1); // items: kept on the stack until the menu copied them
	g_ptr_array_free(keep, TRUE);
	return 0;
}

static void flyout_closed(void *data) {
	lua_State *L = c8l;
	if (once_take(L, data)) {
		c8l_call(L, 0, 0);
	}
}

/* win:flyout{ at = widget, widget, closed = fn } */
static int win_flyout(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	luaL_checktype(L, 2, LUA_TTABLE);
	struct c8ui_widget *content = NULL;
	if (lua_geti(L, 2, 1) == LUA_TUSERDATA) {
		content = c8l_widget(L, -1);
	}
	lua_pop(L, 1);
	if (content == NULL || content->parent) {
		return luaL_error(L, "win:flyout{ at = widget, widget }");
	}
	struct c8ui_rect r = anchor(L, 2);
	lua_getfield(L, 2, "closed");
	struct once *o = once_new(L, -1);
	lua_pop(L, 1);
	push_widget(L, c8ui_flyout_show(c8ui_window_root(win->win), &r, content,
		flyout_closed, o), K_FLYOUT);
	return 1;
}

static int flyout_close(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_FLYOUT);
	ALIVE(w);
	c8ui_flyout_close(w);
	return 0;
}

/* win:settings{ title, widget, wide, closed = fn }: the panel of the
 * app's settings, sliding in from the right */
static int win_settings(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	luaL_checktype(L, 2, LUA_TTABLE);
	struct c8ui_widget *content = one_widget(L, 2,
		"win:settings{ title, widget }: a widget not in anything yet");
	lua_getfield(L, 2, "closed");
	struct once *o = once_new(L, -1);
	lua_pop(L, 1);
	push_widget(L, c8ui_settings_flyout_show(c8ui_window_root(win->win),
		c8l_field_str(L, 2, "title", ""), content,
		c8l_field_bool(L, 2, "wide", false), flyout_closed, o), K_PLAIN);
	return 1;
}

/* The nav bar: win:navbar() makes it once; bar:place(label [, icon]),
 * bar.on_choose(bar, n), bar:show([bool]), bar:set(n) */

static void navbar_chosen(struct c8ui_widget *bar, int index, void *data) {
	lua_State *L = c8l;
	if (push_fn(L, bar, "on_choose")) {
		lua_pushinteger(L, index + 1);
		c8l_call(L, 2, 0);
	}
}

static int win_navbar(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	if (win->navbar == NULL) {
		win->navbar = c8ui_navbar_new(c8ui_window_root(win->win),
			navbar_chosen, NULL);
	}
	push_widget(L, win->navbar, K_NAVBAR);
	return 1;
}

static int navbar_place(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_NAVBAR);
	ALIVE(w);
	lua_pushinteger(L, c8ui_navbar_add(w, luaL_optstring(L, 3, NULL),
		luaL_checkstring(L, 2)) + 1);
	return 1;
}

static int navbar_show(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_NAVBAR);
	ALIVE(w);
	if (lua_isnone(L, 2)) {
		c8ui_navbar_toggle(w);
	} else if (lua_toboolean(L, 2)) {
		c8ui_navbar_show(w);
	} else {
		c8ui_navbar_hide(w);
	}
	return 0;
}

/* bar:colors(bar_color, tile_color) */
static int navbar_colors(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_NAVBAR);
	ALIVE(w);
	c8ui_navbar_set_colors(w, c8l_color(L, 2, 0x1d1d1d),
		c8l_color(L, 3, 0x1ba1e2));
	return 0;
}

/* Files through the portal: done(uris), nil when cancelled */

static void files_picked(char **uris, void *data) {
	lua_State *L = c8l;
	if (!once_take(L, data)) {
		return;
	}
	if (uris == NULL) {
		lua_pushnil(L);
	} else {
		lua_newtable(L);
		for (int i = 0; uris[i]; i++) {
			lua_pushstring(L, uris[i]);
			lua_seti(L, -2, i + 1);
		}
	}
	c8l_call(L, 1, 0);
}

static int pick_files(lua_State *L, bool save) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	luaL_checktype(L, 2, LUA_TTABLE);
	struct c8ui_file_filter filters[16];
	int n = 0;
	lua_getfield(L, 2, "filters");
	lua_Integer count = lua_istable(L, -1) ? luaL_len(L, -1) : 0;
	for (lua_Integer i = 1; i <= count && n < 16; i++) {
		lua_geti(L, -1, i);
		if (lua_istable(L, -1)) {
			/* The strings stay the table's until the call below returns */
			filters[n++] = (struct c8ui_file_filter){
				c8l_field_str(L, -1, "name", "Files"),
				c8l_field_str(L, -1, "patterns", NULL),
				c8l_field_str(L, -1, "types", NULL),
			};
		}
		lua_pop(L, 1);
	}
	struct c8ui_file_options options = {
		.title = c8l_field_str(L, 2, "title", NULL),
		.accept = c8l_field_str(L, 2, "accept", NULL),
		.multiple = c8l_field_bool(L, 2, "multiple", false),
		.folder = c8l_field_bool(L, 2, "folder", false),
		.filters = n ? filters : NULL,
		.filter_count = n,
		.folder_path = c8l_field_str(L, 2, "start", NULL),
		.name = c8l_field_str(L, 2, "name", NULL),
	};
	lua_getfield(L, 2, "done");
	struct once *o = once_new(L, -1);
	lua_pop(L, 1);
	struct c8ui_file_dialog *d = save ?
		c8ui_file_save(win->win, &options, files_picked, o) :
		c8ui_file_open(win->win, &options, files_picked, o);
	if (d == NULL) {
		c8l_unref(L, o->ref);
		g_free(o);
	}
	lua_pushboolean(L, d != NULL);
	return 1;
}

static int win_open_file(lua_State *L) {
	return pick_files(L, false);
}

static int win_save_file(lua_State *L) {
	return pick_files(L, true);
}

/* The app bar: win:appbar() makes it once; bar:add{ icon, label, right,
 * on_click } returns the command */

static int win_appbar(lua_State *L) {
	struct window *win = window_at(L, 1);
	OPEN(win);
	if (win->appbar == NULL) {
		win->appbar = c8ui_appbar_new(c8ui_window_root(win->win));
	}
	push_widget(L, win->appbar, K_APPBAR);
	return 1;
}

static int appbar_add(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_APPBAR);
	ALIVE(w);
	luaL_checktype(L, 2, LUA_TTABLE);
	struct c8ui_widget *command = c8ui_appbar_add(w,
		c8l_field_str(L, 2, "icon", NULL), c8l_field_str(L, 2, "label", ""),
		c8l_field_bool(L, 2, "right", false), clicked, NULL);
	lua_getfield(L, 2, "toggle");
	if (!lua_isnil(L, -1)) {
		c8ui_appbar_command_set_toggle(command, lua_toboolean(L, -1));
	}
	lua_pop(L, 1);
	finish(L, command, K_COMMAND, 2, false);
	return 1;
}

static int appbar_show(lua_State *L) {
	struct c8ui_widget *w = widget_of(L, 1, K_APPBAR);
	ALIVE(w);
	if (lua_isnone(L, 2)) {
		c8ui_appbar_toggle(w);
	} else if (lua_toboolean(L, 2)) {
		c8ui_appbar_show(w);
	} else {
		c8ui_appbar_hide(w);
	}
	return 0;
}

static const luaL_Reg window_methods[] = {
	{ "set", win_set },
	{ "present", win_present },
	{ "set_title", win_title },
	{ "close", win_close },
	{ "fullscreen", win_fullscreen },
	{ "open_uri", win_open_uri },
	{ "copy", win_copy },
	{ "paste", win_paste },
	{ "dialog", win_dialog },
	{ "message", win_message },
	{ "menu", win_menu },
	{ "flyout", win_flyout },
	{ "open_file", win_open_file },
	{ "save_file", win_save_file },
	{ "appbar", win_appbar },
	{ "navbar", win_navbar },
	{ "settings", win_settings },
	{ NULL, NULL },
};

/* Setting up */

static void kind_methods(lua_State *L, enum kind kind, const luaL_Reg *fns) {
	/* METHODS is on top */
	lua_newtable(L);
	if (fns) {
		luaL_setfuncs(L, fns, 0);
	}
	lua_rawseti(L, -2, kind);
}

static const luaL_Reg constructors[] = {
	{ "window", l_window },
	{ "column", l_column },
	{ "row", l_row },
	{ "scroll", l_scroll },
	{ "spacer", l_spacer },
	{ "label", l_label },
	{ "button", l_button },
	{ "link", l_link },
	{ "toggle", l_toggle },
	{ "checkbox", l_checkbox },
	{ "slider", l_slider },
	{ "entry", l_entry },
	{ "combo", l_combo },
	{ "choice", l_choice },
	{ "radio", l_radio },
	{ "ring", l_ring },
	{ "progress", l_progress },
	{ "separator", l_separator },
	{ "image", l_image },
	{ "text", l_text },
	{ "rich", l_rich },
	{ "icon_button", l_icon_button },
	{ "back_button", l_back_button },
	{ "list", l_list },
	{ "canvas", l_canvas },
	{ "pages", l_pages },
	{ "stack", l_stack },
	{ "grid", l_grid },
	{ "expander", l_expander },
	{ "infobar", l_infobar },
	{ "hub", l_hub },
	{ "pivot", l_pivot },
	{ "rich_overflow", l_rich_overflow },
	{ "rich_columns", l_rich_columns },
	{ "nav", l_nav },
	{ "number", l_number },
	{ "rating", l_rating },
	{ "date", l_date },
	{ "time", l_time },
	{ "calendar", l_calendar },
	{ "flip", l_flip },
	{ "split", l_split },
	{ "tree", l_tree },
	{ "columns", l_columns },
	{ "zoom", l_zoom },
	{ "viewbox", l_viewbox },
	{ "toggle_button", l_toggle_button },
	{ "repeat_button", l_repeat_button },
	{ "item", l_item },
	{ "transport", l_transport },
	{ NULL, NULL },
};

void c8l_ui_open(lua_State *L) {
	luaL_setfuncs(L, constructors, 0);

	lua_newtable(L);
	lua_setfield(L, LUA_REGISTRYINDEX, LIVE);

	luaL_newmetatable(L, WIDGET_META);
	lua_pushcfunction(L, widget_index);
	lua_setfield(L, -2, "__index");
	lua_pushcfunction(L, widget_newindex);
	lua_setfield(L, -2, "__newindex");
	lua_pop(L, 1);

	luaL_newmetatable(L, WINDOW_META);
	lua_pushcfunction(L, window_index);
	lua_setfield(L, -2, "__index");
	lua_pushcfunction(L, window_newindex);
	lua_setfield(L, -2, "__newindex");
	luaL_newlib(L, window_methods);
	lua_setfield(L, -2, "methods");
	lua_pop(L, 1);

	lua_newtable(L);
	for (int k = 0; k < K_COUNT; k++) {
		kind_methods(L, k, NULL);
	}
	kind_methods(L, K_PLAIN, plain_methods);
	kind_methods(L, K_BOX, (luaL_Reg[]){
		{ "padding", box_padding }, { "narrow_padding", box_narrow_padding },
		{ "narrow_spacing", box_narrow_spacing },
		{ "narrow_vertical", box_narrow_vertical }, { NULL, NULL } });
	kind_methods(L, K_SCROLL, (luaL_Reg[]){
		{ "scroll_to", scroll_to }, { "scroll_to_x", scroll_to_x },
		{ "offset", scroll_offset }, { NULL, NULL } });
	kind_methods(L, K_LABEL, (luaL_Reg[]){
		{ "style", label_style }, { "narrow_style", label_narrow_style },
		{ "color", label_color }, { NULL, NULL } });
	kind_methods(L, K_ENTRY, (luaL_Reg[]){
		{ "suggest", entry_suggest }, { NULL, NULL } });
	kind_methods(L, K_COMBO, (luaL_Reg[]){
		{ "items", combo_items }, { NULL, NULL } });
	kind_methods(L, K_TEXT, (luaL_Reg[]){
		{ "modified", text_modified }, { "insert", text_insert },
		{ "position", text_position }, { "selection", text_selection },
		{ "select", text_select }, { "find", text_find },
		{ "replace_all", text_replace_all }, { "undo", text_undo },
		{ "redo", text_redo }, { "wrap", text_wrap }, { "font", text_font },
		{ "rich", text_rich }, { "format", text_format },
		{ "runs", text_runs }, { "append", text_append }, { NULL, NULL } });
	kind_methods(L, K_LIST, (luaL_Reg[]){
		{ "count", list_count }, { "is_selected", list_is_selected },
		{ "reveal", list_reveal }, { "mode", list_mode },
		{ "select_all", list_select_all },
		{ "selected_count", list_selected_count }, { NULL, NULL } });
	kind_methods(L, K_RICH, (luaL_Reg[]){
		{ "overflow", rich_overflow }, { NULL, NULL } });
	kind_methods(L, K_GRID, (luaL_Reg[]){
		{ "span", grid_span }, { NULL, NULL } });
	kind_methods(L, K_NAV, (luaL_Reg[]){
		{ "menu", nav_menu }, { NULL, NULL } });
	kind_methods(L, K_SPLIT, (luaL_Reg[]){
		{ "vertical", split_vertical }, { "share", split_share },
		{ NULL, NULL } });
	kind_methods(L, K_TREE, (luaL_Reg[]){
		{ "add", tree_add }, { "remove", tree_remove }, { "clear", tree_clear },
		{ "label", tree_label }, { "parent", tree_parent },
		{ "expanded", tree_expanded }, { "has_children", tree_has_children },
		{ NULL, NULL } });
	kind_methods(L, K_COLUMNS, (luaL_Reg[]){
		{ "width", columns_width }, { NULL, NULL } });
	kind_methods(L, K_ZOOM, (luaL_Reg[]){
		{ "show", zoom_show }, { NULL, NULL } });
	kind_methods(L, K_TRANSPORT, (luaL_Reg[]){
		{ "playing", transport_playing }, { "position", transport_position },
		{ "duration", transport_duration }, { "buffered", transport_buffered },
		{ "volume", transport_volume }, { "fullscreen", transport_fullscreen },
		{ "live", transport_live }, { NULL, NULL } });
	kind_methods(L, K_NAVBAR, (luaL_Reg[]){
		{ "place", navbar_place }, { "show", navbar_show },
		{ "colors", navbar_colors }, { NULL, NULL } });
	kind_methods(L, K_PAGES, (luaL_Reg[]){
		{ "rebuild", pages_rebuild }, { "back", pages_go_back },
		{ "sub", pages_sub }, { "narrow", pages_narrow }, { NULL, NULL } });
	kind_methods(L, K_STACK, (luaL_Reg[]){
		{ "push", stack_push }, { "pop", stack_pop }, { NULL, NULL } });
	kind_methods(L, K_INFOBAR, (luaL_Reg[]){
		{ "action", infobar_action }, { NULL, NULL } });
	kind_methods(L, K_APPBAR, (luaL_Reg[]){
		{ "add", appbar_add }, { "show", appbar_show }, { NULL, NULL } });
	kind_methods(L, K_HUB, (luaL_Reg[]){
		{ "title", hub_title }, { "show", hub_show }, { NULL, NULL } });
	kind_methods(L, K_PIVOT, (luaL_Reg[]){
		{ "title", pivot_title }, { "wrap", pivot_wrap }, { NULL, NULL } });
	kind_methods(L, K_FLYOUT, (luaL_Reg[]){
		{ "close", flyout_close }, { NULL, NULL } });
	lua_setfield(L, LUA_REGISTRYINDEX, METHODS);
}
