/*
 * c8-weather: Weather, after Windows 8's. A panorama over the sky of the
 * place shown: the place, the temperature now and what it's like, and the
 * next days in columns across the bottom; then the hours ahead, any
 * alerts, the radar around it, and the National Weather Service's own
 * words for each day. The nav bar goes Home, to Places (the favourites as
 * tiles, the default first) and to Maps (the radar, to pan around); the
 * app bar adds, removes and pins places, makes one the default and
 * switches between Fahrenheit and Celsius.
 *
 * The data is weathersnail's (weathersnail.com: the NWS's forecasts,
 * stations, alerts and radars), so it knows the United States. With a
 * snail.zone account in PC settings, the places are the ones saved on it.
 * The live tile is tile.c's job; c8-weather-tile keeps it fresh while
 * this isn't open.
 */
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <c8ui/c8ui.h>
#include <c8ui/c8ui-charms.h>
#include <c8ui/c8ui-wayland.h>
#include "app.h"
#include "stealth.h"
#include "weather.h"

#ifndef WEATHER_GLYPHS
#define WEATHER_GLYPHS "/usr/local/share/c8-weather"
#endif

#define PAGE_LEFT 120 // where content starts, as Metro pages do
#define NARROW_PAD 20
#define DAY_W 150 // a day's column
#define DAYS_H 260
#define HOURLY_W 620
#define ROW_H 48
#define ALERT_H 112
#define SIDE_W 440 // the alerts and maps sections
#define DETAILS_W 540
#define PLACE_W 280 // a tile on Places
#define PLACE_H 150
#define NARROW_NOW_H 420
#define NARROW_DAY_H 64
#define NARROW_MAP_H 320
#define NARROW_HOURS 24

#define BAR 0x0b1e33 // the nav bar
#define BAR_TILE 0x1e6fb8
#define PLACES_BG 0x10273d
#define TILE_COLOR "#1e6fb8"

#define REFRESH_S (10 * 60)
#define TILE_DELAY_S 3
#define FIND_DELAY_MS 250

enum { PLACE_HOME, PLACE_PLACES, PLACE_MAPS };

static struct {
	struct c8ui_app *app;
	struct c8ui_window *win;
	struct c8ui_root *root;
	struct c8ui_widget *sky, *stack, *main;
	struct c8ui_widget *now, *days, *hourly, *details, *alerts, *radar;
	struct c8ui_widget *places, *places_list, *map_page, *map_scroll, *map_view;
	struct c8ui_widget *alert_page, *alert_text;
	struct c8ui_widget *appbar, *navbar;
	struct c8ui_widget *cmd_fav, *cmd_unfav, *cmd_home, *cmd_pin, *cmd_add;
	struct c8ui_widget *cmd_to_c, *cmd_to_f, *cmd_refresh;
	struct c8ui_kept *sky_kept, *now_kept, *days_kept;
	struct c8ui_charms *charms;
	char *place_id; // the place shown on Home; NULL: the default
	char *target_id; // Places: the tile the app bar is for
	char *shape; // what Home was built for (see home_shape)
	char *alert_id; // the alert page's
	bool map_centred;
	double map_zoom; // the radar page's, 1: the map's own size
	double map_pinch_zoom; // at the pinch's start
	bool map_pinching;
	guint timer, tile_timer;
	/* Finding places to add: the add dialog's box, or the welcome's */
	struct c8ui_widget *dialog, *add_entry;
	GPtrArray *found; // struct ws_found, for found_for
	char *found_for;
	guint find_timer;
	bool add_pending; // add the first found as soon as it comes
	int day_hover, day_pressed, day_cursor;
} g = { .day_hover = -1, .day_pressed = -1 };

static void rebuild_main(void);
static void update_home(void);
static void update_bar(void);
static void open_places(bool enter);
static void open_map(bool enter);
static void open_alert(struct ws_alert *a);
static void show_place(struct ws_place *p);
static void cmd_add(struct c8ui_widget *w, void *data);

/* The place being shown */
static struct ws_place *current(void) {
	if (g.place_id) {
		struct ws_place *p = ws_place_find(g.place_id);
		if (p) {
			return p;
		}
		if (ws_preview && strcmp(ws_preview->id, g.place_id) == 0) {
			return ws_preview;
		}
	}
	return ws_home();
}

static bool is_favourite(struct ws_place *p) {
	return p && ws_place_find(p->id) == p;
}

/* Narrow, the window is: what the drawing goes by. The widgets are built
 * once for both; this only picks sizes as they measure and draw. */
static bool narrow(void) {
	return g.root && c8ui_root_is_narrow(g.root);
}

static double side_pad(void) {
	return narrow() ? NARROW_PAD : PAGE_LEFT;
}

static uint32_t hash_str(const char *s) {
	return g_str_hash(s);
}

static uint32_t mix(uint32_t a, uint32_t b, double t) {
	uint32_t out = 0;
	for (int shift = 0; shift <= 16; shift += 8) {
		double ca = (a >> shift) & 255, cb = (b >> shift) & 255;
		out |= (uint32_t)lround(ca + (cb - ca) * t) << shift;
	}
	return out;
}

/* The tile, a moment after things settle */

static gboolean tile_now(gpointer data) {
	g.tile_timer = 0;
	ws_tiles_update();
	return G_SOURCE_REMOVE;
}

static void tile_later(void) {
	if (g.tile_timer == 0) {
		g.tile_timer = g_timeout_add_seconds(TILE_DELAY_S, tile_now, NULL);
	}
}

static void show_message(const char *title, const char *message) {
	c8ui_dialog_message(g.root, title, message);
}

/* The sky */

static void sky_colors(struct ws_place *p, uint32_t *top, uint32_t *bottom,
		const char **glyph) {
	const char *icon = p ? ws_now_icon(p) : NULL;
	const char *gl = icon ? ws_glyph(icon) : "partly";
	*glyph = gl;
	*top = ws_sky_top(gl);
	*bottom = ws_sky_bottom(gl);
	/* Clouds and rain at night: the same sky, darker */
	if (ws_icon_is_night(icon) && strcmp(gl, "night") != 0 &&
			strcmp(gl, "partly-night") != 0) {
		*top = c8ui_shade(*top, 0.45);
		*bottom = c8ui_shade(*bottom, 0.5);
	}
}

static void fill_gradient(cairo_t *cr, struct c8ui_rect r, uint32_t top,
		uint32_t bottom) {
	cairo_pattern_t *p = cairo_pattern_create_linear(0, r.y, 0, r.y + r.height);
	cairo_pattern_add_color_stop_rgb(p, 0, ((top >> 16) & 255) / 255.0,
		((top >> 8) & 255) / 255.0, (top & 255) / 255.0);
	cairo_pattern_add_color_stop_rgb(p, 1, ((bottom >> 16) & 255) / 255.0,
		((bottom >> 8) & 255) / 255.0, (bottom & 255) / 255.0);
	cairo_set_source(cr, p);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	cairo_pattern_destroy(p);
}

/* What the photographs had: a sun's glow, stars, clouds drifting */
static void sky_details(cairo_t *cr, struct c8ui_rect r, const char *glyph) {
	if (strcmp(glyph, "clear") == 0 || strcmp(glyph, "partly") == 0) {
		double cx = r.x + r.width * 0.82, cy = r.y + r.height * 0.12;
		double rad = fmax(r.width, r.height) * 0.45;
		cairo_pattern_t *p = cairo_pattern_create_radial(cx, cy, 0, cx, cy, rad);
		cairo_pattern_add_color_stop_rgba(p, 0, 1, 1, 0.92, 0.45);
		cairo_pattern_add_color_stop_rgba(p, 0.25, 1, 1, 0.9, 0.12);
		cairo_pattern_add_color_stop_rgba(p, 1, 1, 1, 1, 0);
		cairo_set_source(cr, p);
		cairo_paint(cr);
		cairo_pattern_destroy(p);
	}
	if (strcmp(glyph, "night") == 0 || strcmp(glyph, "partly-night") == 0) {
		uint32_t seed = 12345;
		for (int i = 0; i < 140; i++) {
			seed = seed * 1103515245 + 12345;
			double x = r.x + (seed >> 8) % 10000 / 10000.0 * r.width;
			seed = seed * 1103515245 + 12345;
			double y = r.y + (seed >> 8) % 10000 / 10000.0 * r.height * 0.7;
			seed = seed * 1103515245 + 12345;
			double a = 0.25 + (seed >> 8) % 100 / 160.0;
			cairo_set_source_rgba(cr, 1, 1, 1, a);
			cairo_arc(cr, x, y, i % 9 == 0 ? 1.5 : 0.9, 0, 2 * M_PI);
			cairo_fill(cr);
		}
	}
	if (strcmp(glyph, "clear") != 0 && strcmp(glyph, "night") != 0) {
		/* Soft banks of cloud */
		static const double banks[][4] = {
			{ 0.15, 0.22, 0.35, 0.10 }, { 0.55, 0.12, 0.45, 0.09 },
			{ 0.85, 0.35, 0.30, 0.08 }, { 0.35, 0.55, 0.50, 0.07 },
		};
		double alpha = strcmp(glyph, "partly") == 0 ||
			strcmp(glyph, "partly-night") == 0 ? 0.07 : 0.1;
		for (size_t i = 0; i < G_N_ELEMENTS(banks); i++) {
			double cx = r.x + banks[i][0] * r.width;
			double cy = r.y + banks[i][1] * r.height;
			double rw = banks[i][2] * r.width, rh = banks[i][3] * r.height + 40;
			cairo_save(cr);
			cairo_translate(cr, cx, cy);
			cairo_scale(cr, rw, rh);
			cairo_pattern_t *p = cairo_pattern_create_radial(0, 0, 0, 0, 0, 1);
			cairo_pattern_add_color_stop_rgba(p, 0, 1, 1, 1, alpha);
			cairo_pattern_add_color_stop_rgba(p, 1, 1, 1, 1, 0);
			cairo_set_source(cr, p);
			cairo_arc(cr, 0, 0, 1, 0, 2 * M_PI);
			cairo_fill(cr);
			cairo_pattern_destroy(p);
			cairo_restore(cr);
		}
	}
}

static void paint_sky(cairo_t *cr, struct c8ui_rect r, struct ws_place *p) {
	uint32_t top, bottom;
	const char *glyph;
	sky_colors(p, &top, &bottom, &glyph);
	fill_gradient(cr, r, top, bottom);
	sky_details(cr, r, glyph);
}

static bool sky_paint(cairo_t *cr, struct c8ui_rect r, void *data) {
	paint_sky(cr, r, current());
	return true;
}

static void sky_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = 0;
}

static void sky_layout(struct c8ui_widget *w) {
	for (int i = 0; i < w->child_count; i++) {
		c8ui_widget_layout(w->children[i], w->rect);
	}
}

static void sky_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct ws_place *p = current();
	uint32_t top, bottom;
	const char *glyph;
	sky_colors(p, &top, &bottom, &glyph);
	char *key = g_strdup_printf("sky %s %06x %06x", glyph, top, bottom);
	c8ui_kept_draw(&g.sky_kept, cr, w->rect, hash_str(key), sky_paint, NULL);
	g_free(key);
}

static void toggle_bars(void) {
	update_bar();
	if (c8ui_appbar_is_shown(g.appbar)) {
		c8ui_appbar_hide(g.appbar);
		c8ui_navbar_hide(g.navbar);
	} else {
		c8ui_appbar_show(g.appbar);
		c8ui_navbar_show(g.navbar);
	}
}

static bool sky_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	if (ev->type == C8UI_EVENT_PRESS && ev->button == C8UI_BUTTON_RIGHT) {
		g_clear_pointer(&g.target_id, g_free);
		toggle_bars();
		return true;
	}
	return false;
}

static void sky_destroy(struct c8ui_widget *w) {
	c8ui_kept_drop(&g.sky_kept);
}

static const struct c8ui_widget_impl sky_impl = {
	.name = "weather-sky",
	.measure = sky_measure,
	.layout = sky_layout,
	.draw = sky_draw,
	.event = sky_event,
	.destroy = sky_destroy,
};

/* Now: the place, the temperature, what it's like and the details */

struct now_text {
	char *name, *temp, *summary, *feels, *source;
	char *rows[5][2]; // name, value
	int row_count;
	char *alert; // the worst alert in force
	uint32_t alert_color;
	char *status; // instead of it all: loading, or why there's nothing
	const char *glyph;
};

static void now_text_free(struct now_text *t) {
	g_free(t->name);
	g_free(t->temp);
	g_free(t->summary);
	g_free(t->feels);
	g_free(t->source);
	for (int i = 0; i < t->row_count; i++) {
		g_free(t->rows[i][0]);
		g_free(t->rows[i][1]);
	}
	g_free(t->alert);
	g_free(t->status);
}

static char *until_text(int64_t ends) {
	if (ends <= 0) {
		return g_strdup("");
	}
	GDateTime *dt = g_date_time_new_from_unix_local(ends);
	GDateTime *now = g_date_time_new_now_local();
	/* Today's needs no day */
	bool today = g_date_time_get_day_of_year(dt) ==
		g_date_time_get_day_of_year(now) &&
		g_date_time_get_year(dt) == g_date_time_get_year(now);
	char *t = g_date_time_format(dt, today ? (ws_clock_24h() ? "%H:%M" :
		"%l:%M %p") : (ws_clock_24h() ? "%a %H:%M" : "%a %l:%M %p"));
	g_date_time_unref(now);
	g_date_time_unref(dt);
	char *out = g_strdup_printf("until %s", g_strstrip(t));
	g_free(t);
	return out;
}

static void now_row(struct now_text *t, const char *name, char *value) {
	if (t->row_count < 5) {
		t->rows[t->row_count][0] = g_strdup(name);
		t->rows[t->row_count][1] = value;
		t->row_count++;
	} else {
		g_free(value);
	}
}

static void now_text_make(struct now_text *t, struct ws_place *p) {
	memset(t, 0, sizeof(*t));
	t->name = g_strdup(p ? ws_place_label(p) : "");
	if (p == NULL) {
		return;
	}
	struct ws_now *n = p->now;
	if (p->forecast == NULL && n == NULL) {
		t->status = g_strdup(p->error ? p->error : p->loading ?
			"Getting the weather…" : "No weather here yet.");
		return;
	}
	t->glyph = ws_glyph(ws_now_icon(p));
	double temp = n ? n->temp : NAN;
	if (isnan(temp) && p->forecast && p->forecast->hours->len) {
		temp = g_array_index(p->forecast->hours, struct ws_hour, 0).temp;
	}
	t->temp = ws_temp(temp, false);
	const char *summary = ws_now_summary(p);
	t->summary = g_strdup(summary ? summary : "");
	if (n) {
		double feels = ws_feels_like(n);
		char *f = ws_temp(feels, false);
		t->feels = g_strdup_printf("Feels like %s", f);
		g_free(f);
		char *wind = ws_wind(n->wind_kt, n->wind_dir);
		if (!isnan(n->gust_kt) && n->gust_kt > 0) {
			char *gust = ws_wind(n->gust_kt, NAN);
			/* "Variable 20 mph": the speed is what's wanted */
			const char *speed = strchr(gust, ' ');
			char *both = g_strdup_printf("%s, gusts %s", wind,
				speed ? speed + 1 : gust);
			g_free(wind);
			g_free(gust);
			wind = both;
		}
		now_row(t, "Wind", wind);
		if (!isnan(n->humidity)) {
			now_row(t, "Humidity", g_strdup_printf("%.0f%%", n->humidity));
		}
		if (!isnan(n->dewpoint)) {
			now_row(t, "Dew point", ws_temp(n->dewpoint, false));
		}
		if (!isnan(n->pressure)) {
			char *pr = ws_pressure(n->pressure);
			const char *arrow = g_strcmp0(n->trend, "rising") == 0 ? " ↑" :
				g_strcmp0(n->trend, "falling") == 0 ? " ↓" : "";
			now_row(t, "Barometer", g_strdup_printf("%s%s", pr, arrow));
			g_free(pr);
		}
		if (n->precip) {
			now_row(t, "Nearby", n->intensity ? g_strdup_printf("%s %s",
				n->intensity, n->precip) : g_strdup(n->precip));
			/* "light Rain": as a sentence */
			char *v = t->rows[t->row_count - 1][1];
			v[0] = g_ascii_toupper(v[0]);
			for (char *c = v + 1; *c; c++) {
				*c = g_ascii_tolower(*c);
			}
		}
		char *age = ws_age(n->time);
		/* The station's name says where the place is */
		t->source = n->station && !c8_stealth() ? g_strdup_printf("%s · %s",
			age, n->station) : g_strdup(age);
		g_free(age);
	} else if (p->forecast) {
		char *age = ws_age(p->forecast->updated);
		t->source = g_strdup_printf("%s · the forecast", age);
		g_free(age);
	}
	if (p->alerts && p->alerts->len) {
		struct ws_alert *a = p->alerts->pdata[0];
		char *until = until_text(a->ends);
		t->alert = p->alerts->len > 1 ? g_strdup_printf("%s %s, and %u more",
			a->event, until, p->alerts->len - 1) :
			g_strdup_printf("%s %s", a->event, until);
		g_free(until);
		t->alert_color = a->color;
	}
}

static char *now_key(struct now_text *t, struct c8ui_widget *w) {
	GString *s = g_string_new(NULL);
	g_string_append_printf(s, "%d %s|%s|%s|%s|%s|%s|%s|%s|%06x|%s", narrow(),
		c8ui_widget_font(w), t->name, t->temp ? t->temp : "",
		t->summary ? t->summary : "", t->feels ? t->feels : "",
		t->source ? t->source : "", t->alert ? t->alert : "",
		t->status ? t->status : "", t->alert_color, t->glyph ? t->glyph : "");
	for (int i = 0; i < t->row_count; i++) {
		g_string_append_printf(s, "|%s=%s", t->rows[i][0], t->rows[i][1]);
	}
	return g_string_free(s, FALSE);
}

/* Dark text on a light alert colour, white on a dark one */
static uint32_t text_on(uint32_t bg) {
	double l = 0.299 * ((bg >> 16) & 255) + 0.587 * ((bg >> 8) & 255) +
		0.114 * (bg & 255);
	return l > 150 ? 0x1a1a1a : 0xffffff;
}

static void draw_now(cairo_t *cr, struct c8ui_rect r, const char *family,
		struct now_text *t, uint32_t sky) {
	double x = r.x + side_pad();
	double width = r.width - side_pad() - (narrow() ? NARROW_PAD : 40);
	double y = r.y + (narrow() ? 24 : 40);
	struct c8ui_font place = { narrow() ? 30 : 42, C8UI_WEIGHT_LIGHT };
	double tw, th;
	c8ui_set_source(cr, 0xffffff, 1);
	th = c8ui_text_draw(cr, family, place, t->name, x, y, width, 1);
	y += th + 2;
	struct c8ui_font small = { 13, C8UI_WEIGHT_NORMAL };
	if (t->source) {
		c8ui_set_source(cr, 0xffffff, 0.75);
		y += c8ui_text_draw(cr, family, small, t->source, x, y, width, 1);
	}
	if (t->status) {
		struct c8ui_font body = { 20, C8UI_WEIGHT_SEMILIGHT };
		c8ui_set_source(cr, 0xffffff, 0.9);
		c8ui_text_draw(cr, family, body, t->status, x, y + 40, fmin(width, 560),
			4);
		return;
	}
	/* The glyph, and the temperature big beside it */
	double gs = narrow() ? 96 : 150;
	double top = y + (narrow() ? 18 : 36);
	c8ui_weather_glyph(cr, t->glyph, x + gs / 2, top + gs / 2, gs, 1, sky);
	double tx = x + gs + (narrow() ? 16 : 28);
	struct c8ui_font big = { narrow() ? 76 : 112, C8UI_WEIGHT_LIGHT };
	c8ui_set_source(cr, 0xffffff, 1);
	c8ui_text_size(family, big, t->temp, 0, 1, &tw, &th);
	double ty = top + gs / 2 - th / 2 - (narrow() ? 6 : 10);
	c8ui_text_draw(cr, family, big, t->temp, tx, ty, 0, 1);
	struct c8ui_font unit = { narrow() ? 26 : 36, C8UI_WEIGHT_LIGHT };
	c8ui_text_draw(cr, family, unit, ws_settings.units == WS_CELSIUS ? "C" :
		"F", tx + tw + 2, ty + th * 0.16, 0, 1);
	y = top + gs + (narrow() ? 10 : 16);
	struct c8ui_font sum = { narrow() ? 22 : 26, C8UI_WEIGHT_LIGHT };
	y += c8ui_text_draw(cr, family, sum, t->summary, x, y, width, 2);
	if (t->feels) {
		struct c8ui_font body = { 16, C8UI_WEIGHT_NORMAL };
		c8ui_set_source(cr, 0xffffff, 0.85);
		y += c8ui_text_draw(cr, family, body, t->feels, x, y + 2, width, 1) + 12;
	}
	/* The details, a name and its value, in two columns when wide */
	struct c8ui_font name = { 14, C8UI_WEIGHT_NORMAL };
	struct c8ui_font value = { 14, C8UI_WEIGHT_SEMIBOLD };
	int cols = !narrow() && width > 640 ? 2 : 1;
	double col_w = narrow() ? width : 300;
	for (int i = 0; i < t->row_count; i++) {
		double cx = x + (i % cols) * col_w;
		double cy = y + (i / cols) * 24;
		c8ui_set_source(cr, 0xffffff, 0.75);
		c8ui_text_draw(cr, family, name, t->rows[i][0], cx, cy, 100, 1);
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_text_draw(cr, family, value, t->rows[i][1], cx + 100, cy,
			col_w - 110, 1);
	}
	y += ((t->row_count + cols - 1) / cols) * 24 + 14;
	if (t->alert && y + 34 < r.y + r.height) {
		struct c8ui_font a = { 14, C8UI_WEIGHT_SEMIBOLD };
		double aw, ah;
		c8ui_text_size(family, a, t->alert, width - 24, 1, &aw, &ah);
		c8ui_set_source(cr, t->alert_color, 0.95);
		cairo_rectangle(cr, x, y, aw + 24, ah + 12);
		cairo_fill(cr);
		c8ui_set_source(cr, text_on(t->alert_color), 1);
		c8ui_text_draw(cr, family, a, t->alert, x + 12, y + 6, width - 24, 1);
	}
}

static bool now_paint(cairo_t *cr, struct c8ui_rect r, void *data) {
	struct c8ui_widget *w = data;
	struct now_text t;
	now_text_make(&t, current());
	uint32_t top, bottom;
	const char *glyph;
	sky_colors(current(), &top, &bottom, &glyph);
	/* The cut round the cloud is the sky behind, near enough */
	uint32_t sky = top;
	draw_now(cr, r, c8ui_widget_font(w), &t, sky);
	now_text_free(&t);
	return true;
}

static void now_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = narrow() ? NARROW_NOW_H : 0;
}

static void now_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct now_text t;
	now_text_make(&t, current());
	char *key = now_key(&t, w);
	now_text_free(&t);
	/* Kept as pixels with what's under it: the sky, drawn again here */
	c8ui_kept_draw(&g.now_kept, cr, w->rect, hash_str(key), now_paint, w);
	g_free(key);
}

static bool now_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	/* A click on the alert opens it */
	struct ws_place *p = current();
	if (ev->type == C8UI_EVENT_PRESS && ev->button == C8UI_BUTTON_LEFT && p &&
			p->alerts && p->alerts->len) {
		return true;
	}
	if (ev->type == C8UI_EVENT_RELEASE && p && p->alerts && p->alerts->len &&
			c8ui_rect_contains(&w->rect, ev->x, ev->y) &&
			ev->y > w->rect.y + w->rect.height * 0.5) {
		open_alert(p->alerts->pdata[0]);
		return true;
	}
	return false;
}

static void now_destroy(struct c8ui_widget *w) {
	if (g.now == w) {
		g.now = NULL;
	}
	c8ui_kept_drop(&g.now_kept);
}

static const struct c8ui_widget_impl now_impl = {
	.name = "weather-now",
	.measure = now_measure,
	.draw = now_draw,
	.event = now_event,
	.destroy = now_destroy,
};

/* The days: columns across the bottom (a list down, when narrow) */

static GArray *days_of(struct ws_place *p) {
	return p && p->forecast ? p->forecast->days : NULL;
}

static int days_shown(struct c8ui_widget *w) {
	GArray *days = days_of(current());
	if (days == NULL) {
		return 0;
	}
	if (narrow()) {
		return (int)days->len;
	}
	int fit = (int)((w->rect.width - side_pad() - 20) / DAY_W);
	return MAX(0, MIN(fit, (int)days->len));
}

static struct c8ui_rect day_rect(struct c8ui_widget *w, int i) {
	struct c8ui_rect r = w->rect;
	if (narrow()) {
		return (struct c8ui_rect){ r.x, r.y + i * NARROW_DAY_H, r.width,
			NARROW_DAY_H };
	}
	return (struct c8ui_rect){ r.x + side_pad() - 12 + i * DAY_W, r.y, DAY_W,
		r.height - 30 };
}

static int day_at(struct c8ui_widget *w, double x, double y) {
	for (int i = 0; i < days_shown(w); i++) {
		struct c8ui_rect r = day_rect(w, i);
		if (c8ui_rect_contains(&r, x, y)) {
			return i;
		}
	}
	return -1;
}

static void draw_drop(cairo_t *cr, double x, double y, double s) {
	cairo_move_to(cr, x, y);
	cairo_curve_to(cr, x + s * 0.5, y + s * 0.55, x + s * 0.4, y + s,
		x, y + s);
	cairo_curve_to(cr, x - s * 0.4, y + s, x - s * 0.5, y + s * 0.55, x, y);
	cairo_fill(cr);
}

static void draw_day(cairo_t *cr, const char *family, struct ws_day *d,
		int index, struct c8ui_rect r, uint32_t sky) {
	char *label = ws_day_label(d, index);
	char *hi = ws_temp(d->high, false), *lo = ws_temp(d->low, false);
	struct c8ui_font name = { 20, C8UI_WEIGHT_SEMILIGHT };
	struct c8ui_font high = { narrow() ? 22 : 26, C8UI_WEIGHT_LIGHT };
	struct c8ui_font low = { narrow() ? 18 : 20, C8UI_WEIGHT_LIGHT };
	struct c8ui_font small = { 13, C8UI_WEIGHT_NORMAL };
	char *pop = d->pop > 0 ? g_strdup_printf("%d%%", d->pop) : NULL;
	double tw, th;
	if (narrow()) {
		double x = r.x + NARROW_PAD, cy = r.y + r.height / 2;
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_text_size(family, name, label, 0, 1, &tw, &th);
		c8ui_text_draw(cr, family, name, label, x, cy - th / 2, 110, 1);
		c8ui_weather_glyph(cr, ws_glyph(d->icon), x + 140, cy, 40, 1, sky);
		double right = r.x + r.width - NARROW_PAD;
		c8ui_text_size(family, low, lo, 0, 1, &tw, &th);
		c8ui_set_source(cr, 0xffffff, 0.7);
		c8ui_text_draw(cr, family, low, lo, right - tw, cy - th / 2, 0, 1);
		double lw = tw;
		c8ui_text_size(family, high, hi, 0, 1, &tw, &th);
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_text_draw(cr, family, high, hi, right - lw - 14 - tw, cy - th / 2,
			0, 1);
		if (pop) {
			c8ui_set_source(cr, 0xffffff, 0.8);
			draw_drop(cr, x + 182, cy - 6, 12);
			c8ui_text_draw(cr, family, small, pop, x + 192, cy - 8, 60, 1);
		}
	} else {
		double x = r.x + 12, y = r.y + 10, w = r.width - 24;
		c8ui_set_source(cr, 0xffffff, 1);
		y += c8ui_text_draw(cr, family, name, label, x, y, w, 1) + 8;
		c8ui_weather_glyph(cr, ws_glyph(d->icon), x + 30, y + 30, 60, 1, sky);
		y += 70;
		c8ui_text_size(family, high, hi, 0, 1, &tw, &th);
		c8ui_text_draw(cr, family, high, hi, x, y, 0, 1);
		c8ui_set_source(cr, 0xffffff, 0.7);
		c8ui_text_draw(cr, family, low, lo, x + tw + 10, y + 5, 0, 1);
		y += th + 6;
		c8ui_set_source(cr, 0xffffff, 0.9);
		y += c8ui_text_draw(cr, family, small, d->summary ? d->summary : "", x,
			y, w, 2) + 6;
		if (pop) {
			c8ui_set_source(cr, 0xffffff, 0.8);
			draw_drop(cr, x + 5, y + 3, 11);
			c8ui_text_draw(cr, family, small, pop, x + 16, y, w - 16, 1);
		}
	}
	g_free(pop);
	g_free(label);
	g_free(hi);
	g_free(lo);
}

static bool days_paint(cairo_t *cr, struct c8ui_rect r, void *data) {
	struct c8ui_widget *w = data;
	struct ws_place *p = current();
	GArray *days = days_of(p);
	uint32_t top, bottom;
	const char *glyph;
	sky_colors(p, &top, &bottom, &glyph);
	/* r is the widget's at 0, 0: the columns go by that */
	struct c8ui_rect saved = w->rect;
	w->rect = r;
	for (int i = 0; days && i < days_shown(w); i++) {
		struct c8ui_rect dr = day_rect(w, i);
		if (i == g.day_hover || i == g.day_pressed) {
			c8ui_set_source(cr, 0xffffff, i == g.day_pressed ? 0.2 : 0.1);
			cairo_rectangle(cr, dr.x, dr.y, dr.width, dr.height);
			cairo_fill(cr);
		}
		if (narrow() && i > 0) {
			c8ui_set_source(cr, 0xffffff, 0.15);
			cairo_rectangle(cr, dr.x + NARROW_PAD, dr.y, dr.width - 2 *
				NARROW_PAD, 1);
			cairo_fill(cr);
		}
		draw_day(cr, c8ui_widget_font(w), &g_array_index(days, struct ws_day, i),
			i, dr, bottom);
	}
	w->rect = saved;
	return true;
}

static void days_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	GArray *days = days_of(current());
	*width = avail;
	*height = narrow() ? (days ? days->len : 0) * NARROW_DAY_H + 10 : DAYS_H;
}

static void days_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct ws_place *p = current();
	GArray *days = days_of(p);
	GString *k = g_string_new(NULL);
	g_string_append_printf(k, "%d %d %d %d %s %u", narrow(), g.day_hover,
		g.day_pressed, ws_settings.units, c8ui_widget_font(w),
		days ? days->len : 0);
	uint32_t top, bottom;
	const char *glyph;
	sky_colors(p, &top, &bottom, &glyph);
	g_string_append_printf(k, " %06x", bottom);
	for (guint i = 0; days && i < days->len; i++) {
		struct ws_day *d = &g_array_index(days, struct ws_day, i);
		g_string_append_printf(k, "|%s %.1f %.1f %d %s %s", d->date, d->high,
			d->low, d->pop, d->icon ? d->icon : "", d->summary ? d->summary : "");
	}
	c8ui_kept_draw(&g.days_kept, cr, w->rect, hash_str(k->str), days_paint, w);
	g_string_free(k, TRUE);
	if (c8ui_widget_shows_focus(w) && g.day_cursor < days_shown(w)) {
		struct c8ui_rect dr = day_rect(w, g.day_cursor);
		cairo_set_source_rgba(cr, 1, 1, 1, 0.9);
		cairo_set_line_width(cr, 1);
		static const double dash[] = { 1, 1 };
		cairo_set_dash(cr, dash, 2, 0);
		cairo_rectangle(cr, dr.x + 2.5, dr.y + 2.5, dr.width - 5, dr.height - 5);
		cairo_stroke(cr);
		cairo_set_dash(cr, NULL, 0, 0);
	}
}

/* A day's words in a flyout by its column */
static void open_day(struct c8ui_widget *w, int i) {
	GArray *days = days_of(current());
	if (days == NULL || i < 0 || i >= (int)days->len) {
		return;
	}
	struct ws_day *d = &g_array_index(days, struct ws_day, i);
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 10);
	box->fixed_width = 360;
	c8ui_box_set_padding(box, 20, 16, 20, 20);
	char *label = ws_day_label(d, i);
	const char *nws = d->name && i > 0 ? d->name : NULL;
	char *title = nws && !g_str_has_prefix(label, nws) ?
		g_strdup_printf("%s · %s", label, nws) : g_strdup(label);
	c8ui_widget_add(box, c8ui_label_new(title, C8UI_TEXT_TITLE));
	g_free(title);
	g_free(label);
	GString *m = g_string_new(NULL);
	if (d->day_text) {
		char *e = g_markup_escape_text(d->day_text, -1);
		g_string_append(m, e);
		g_free(e);
	}
	if (d->night_text) {
		char *e = g_markup_escape_text(d->night_text, -1);
		g_string_append_printf(m, "%s<b>Night</b>\n%s", m->len ? "\n\n" : "", e);
		g_free(e);
	}
	if (m->len == 0) {
		/* The blend's days have no words of the NWS's: say it in ours */
		char *hi = ws_temp(d->high, true), *lo = ws_temp(d->low, true);
		g_string_append_printf(m, "%s. High %s, low %s.", d->summary ?
			d->summary : "", hi, lo);
		if (d->pop > 0) {
			g_string_append_printf(m, " Chance of precipitation %d%%.", d->pop);
		}
		g_free(hi);
		g_free(lo);
	}
	struct c8ui_widget *text = c8ui_rich_new(m->str);
	text->fill = true;
	c8ui_widget_add(box, text);
	g_string_free(m, TRUE);
	struct c8ui_rect anchor = day_rect(w, i);
	c8ui_flyout_show(g.root, &anchor, box, NULL, NULL);
}

static bool days_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	int i;
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
		i = day_at(w, ev->x, ev->y);
		if (i != g.day_hover) {
			g.day_hover = i;
			c8ui_widget_queue_draw(w);
		}
		w->cursor = i >= 0 ? C8UI_CURSOR_POINTER : C8UI_CURSOR_DEFAULT;
		return false;
	case C8UI_EVENT_LEAVE:
		if (g.day_hover >= 0) {
			g.day_hover = -1;
			c8ui_widget_queue_draw(w);
		}
		return false;
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		g.day_pressed = day_at(w, ev->x, ev->y);
		c8ui_widget_queue_draw(w);
		return g.day_pressed >= 0;
	case C8UI_EVENT_RELEASE:
		i = day_at(w, ev->x, ev->y);
		if (i >= 0 && i == g.day_pressed) {
			g.day_cursor = i;
			open_day(w, i);
		}
		g.day_pressed = -1;
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_KEY: {
		int n = days_shown(w);
		int step = narrow() ? (ev->sym == XKB_KEY_Down ? 1 :
			ev->sym == XKB_KEY_Up ? -1 : 0) : (ev->sym == XKB_KEY_Right ? 1 :
			ev->sym == XKB_KEY_Left ? -1 : 0);
		if (step && g.day_cursor + step >= 0 && g.day_cursor + step < n) {
			g.day_cursor += step;
			c8ui_widget_queue_draw(w);
			struct c8ui_rect dr = day_rect(w, g.day_cursor);
			c8ui_widget_reveal(w, &dr);
			return true;
		}
		if (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_KP_Enter ||
				ev->sym == XKB_KEY_space) {
			open_day(w, g.day_cursor);
			return true;
		}
		return false;
	}
	default:
		return false;
	}
}

static void days_destroy(struct c8ui_widget *w) {
	if (g.days == w) {
		g.days = NULL;
	}
	c8ui_kept_drop(&g.days_kept);
}

static const struct c8ui_widget_impl days_impl = {
	.name = "weather-days",
	.measure = days_measure,
	.draw = days_draw,
	.event = days_event,
	.destroy = days_destroy,
};

/* The hours ahead */

static GArray *hours_of(struct ws_place *p) {
	return p && p->forecast ? p->forecast->hours : NULL;
}

/* A day ahead in one column: two would be a long way down */
static int hours_count(GArray *hours) {
	int n = hours ? (int)hours->len : 0;
	return narrow() ? MIN(n, NARROW_HOURS) : n;
}

static void draw_hour(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	GArray *hours = hours_of(current());
	if (hours == NULL || item->index >= (int)hours->len) {
		return;
	}
	struct ws_hour *h = &g_array_index(hours, struct ws_hour, item->index);
	const char *family = c8ui_widget_font(list);
	struct c8ui_rect r = item->rect;
	double cy = r.y + r.height / 2;
	struct c8ui_font body = { 15, C8UI_WEIGHT_NORMAL };
	struct c8ui_font temp = { 20, C8UI_WEIGHT_SEMILIGHT };
	double tw, th;
	char *when = ws_hour_label(h->time);
	/* Midnight starts a new day: say which */
	if (g_date_time_get_hour(h->time) == 0 || item->index == 0) {
		char *day = item->index == 0 ? g_strdup("Now") :
			g_date_time_format(h->time, "%a");
		char *both = item->index == 0 ? day : g_strdup_printf("%s %s", day, when);
		if (both != day) {
			g_free(day);
		}
		g_free(when);
		when = both;
	}
	c8ui_text_size(family, body, when, 0, 1, &tw, &th);
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, body, when, r.x + 12, cy - th / 2, 84, 1);
	g_free(when);
	/* The cut round a cloud: the sky about there */
	uint32_t top, bottom;
	const char *sky;
	sky_colors(current(), &top, &bottom, &sky);
	c8ui_weather_glyph(cr, ws_glyph(h->icon), r.x + 118, cy, 30, 1,
		mix(top, bottom, 0.5));
	char *t = ws_temp(h->temp, false);
	c8ui_text_size(family, temp, t, 0, 1, &tw, &th);
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, temp, t, r.x + 148, cy - th / 2, 60, 1);
	g_free(t);
	double right = r.x + r.width - 12;
	char *wind = ws_wind_kmh(h->wind_kmh, h->wind_dir);
	char *pop = g_strdup_printf("%d%%", h->pop);
	c8ui_set_source(cr, item->fg, item->secondary);
	c8ui_text_size(family, body, wind, 0, 1, &tw, &th);
	double wind_x = right - 100;
	c8ui_text_draw(cr, family, body, wind, wind_x, cy - th / 2, 100, 1);
	double pop_x = wind_x - 64;
	if (h->pop > 0) {
		c8ui_set_source(cr, item->fg, 0.8);
		draw_drop(cr, pop_x + 4, cy - 6, 11);
		c8ui_text_draw(cr, family, body, pop, pop_x + 14, cy - th / 2, 50, 1);
	}
	if (!narrow() && h->summary) {
		c8ui_set_source(cr, item->fg, item->secondary);
		double sx = r.x + 206;
		c8ui_text_draw(cr, family, body, h->summary, sx, cy - th / 2,
			pop_x - sx - 12, 1);
	}
	g_free(wind);
	g_free(pop);
}

static struct c8ui_widget *hourly_list_new(void) {
	struct c8ui_widget *list = c8ui_list_new(C8UI_LIST_ROWS, 0, ROW_H,
		draw_hour, NULL);
	GArray *hours = hours_of(current());
	c8ui_list_set_count(list, hours_count(hours));
	c8ui_list_set_keep(list, true);
	list->fill = true;
	c8ui_widget_track(list, &g.hourly);
	return list;
}

/* The column names over the hours */
static void hourly_head_draw(struct c8ui_widget *w, cairo_t *cr, void *data) {
	const char *family = c8ui_widget_font(w);
	struct c8ui_font f = { 12, C8UI_WEIGHT_SEMIBOLD };
	struct c8ui_rect r = w->rect;
	double right = r.x + r.width - 12;
	c8ui_set_source(cr, 0xffffff, 0.7);
	c8ui_text_draw(cr, family, f, "TIME", r.x + 12, r.y + 6, 0, 1);
	c8ui_text_draw(cr, family, f, "TEMP", r.x + 148, r.y + 6, 0, 1);
	if (!narrow()) {
		c8ui_text_draw(cr, family, f, "FORECAST", r.x + 206, r.y + 6, 0, 1);
	}
	c8ui_text_draw(cr, family, f, "PRECIP", right - 164, r.y + 6, 0, 1);
	c8ui_text_draw(cr, family, f, "WIND", right - 100, r.y + 6, 0, 1);
}

static struct c8ui_widget *hourly_head_new(void) {
	struct c8ui_widget *head = c8ui_canvas_new(0, 26, hourly_head_draw, NULL,
		NULL);
	head->fill = true;
	return head;
}

/* Alerts */

static GPtrArray *alerts_of(struct ws_place *p) {
	return p ? p->alerts : NULL;
}

static void draw_alert(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	GPtrArray *alerts = alerts_of(current());
	if (alerts == NULL || item->index >= (int)alerts->len) {
		return;
	}
	struct ws_alert *a = alerts->pdata[item->index];
	const char *family = c8ui_widget_font(list);
	struct c8ui_rect r = item->rect;
	c8ui_set_source(cr, a->color, 1);
	cairo_rectangle(cr, r.x, r.y + 8, 8, r.height - 16);
	cairo_fill(cr);
	double x = r.x + 22, w = r.width - 34, y = r.y + 10;
	struct c8ui_font title = { 20, C8UI_WEIGHT_SEMILIGHT };
	struct c8ui_font small = { 13, C8UI_WEIGHT_NORMAL };
	c8ui_set_source(cr, item->fg, 1);
	y += c8ui_text_draw(cr, family, title, a->event, x, y, w, 1) + 2;
	char *until = until_text(a->ends);
	char *line = g_strdup_printf("%s%s%s", a->severity ? a->severity : "",
		a->severity && until[0] ? ", " : "", until);
	c8ui_set_source(cr, item->fg, 0.9);
	y += c8ui_text_draw(cr, family, small, line, x, y, w, 1) + 2;
	g_free(line);
	g_free(until);
	c8ui_set_source(cr, item->fg, item->secondary);
	/* The counties say where the place is */
	c8ui_text_draw(cr, family, small, a->area && !c8_stealth() ? a->area : "",
		x, y, w, 2);
}

static void alert_opened(struct c8ui_widget *list, int index, void *data) {
	GPtrArray *alerts = alerts_of(current());
	if (alerts && index >= 0 && index < (int)alerts->len) {
		open_alert(alerts->pdata[index]);
	}
}

static struct c8ui_widget *alerts_list_new(void) {
	struct c8ui_widget *list = c8ui_list_new(C8UI_LIST_ROWS, 0, ALERT_H,
		draw_alert, NULL);
	GPtrArray *alerts = alerts_of(current());
	c8ui_list_set_count(list, alerts ? (int)alerts->len : 0);
	c8ui_list_set_click_opens(list, true);
	c8ui_list_on_open(list, alert_opened, NULL);
	list->fill = true;
	c8ui_widget_track(list, &g.alerts);
	return list;
}

/* The radar round the place */

static void draw_marker(cairo_t *cr, double x, double y) {
	cairo_arc(cr, x, y, 8, 0, 2 * M_PI);
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_fill_preserve(cr);
	c8ui_set_source(cr, BAR_TILE, 1);
	cairo_set_line_width(cr, 3);
	cairo_stroke(cr);
	cairo_arc(cr, x, y, 3, 0, 2 * M_PI);
	c8ui_set_source(cr, BAR_TILE, 1);
	cairo_fill(cr);
}

/* The map round a place, NULL while it comes. None in stealth mode: its
 * streets and towns would say where the place is. */
static const struct radar_map *map_for(struct ws_place *p) {
	return p && !c8_stealth() ? radar_for(p->lat, p->lon) : NULL;
}

/* What's said where the map would be */
static const char *map_missing(struct ws_place *p) {
	if (c8_stealth()) {
		return "The radar is hidden in stealth mode.";
	}
	return p && radar_failed(p->lat, p->lon) ?
		"There's no radar map of this place." : "Getting the radar…";
}

/* The map at 1:1 with the place at (px, py) of it drawn at (x, y) */
static void blit_map(cairo_t *cr, const struct radar_map *m, double x,
		double y) {
	x = round(x);
	y = round(y);
	cairo_set_source_surface(cr, m->map, x, y);
	cairo_paint(cr);
	if (m->labels) {
		cairo_set_source_surface(cr, m->labels, x, y);
		cairo_paint(cr);
	}
}

static void radar_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct ws_place *p = current();
	struct c8ui_rect r = w->rect;
	const char *family = c8ui_widget_font(w);
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	const struct radar_map *m = map_for(p);
	struct c8ui_font small = { 13, C8UI_WEIGHT_NORMAL };
	if (m == NULL) {
		c8ui_set_source(cr, 0x000000, 0.2);
		cairo_paint(cr);
		c8ui_set_source(cr, 0xffffff, 0.85);
		c8ui_text_draw(cr, family, small, map_missing(p), r.x + 16, r.y + 16,
			r.width - 32, 2);
		cairo_restore(cr);
		return;
	}
	double px, py;
	radar_project(m, p->lat, p->lon, &px, &py);
	/* The place in the middle, unless that leaves the map's edge in view */
	double ox = r.width / 2 - px, oy = r.height / 2 - py;
	ox = fmin(0, fmax(ox, r.width - m->width));
	oy = fmin(0, fmax(oy, r.height - m->height));
	blit_map(cr, m, r.x + ox, r.y + oy);
	draw_marker(cr, r.x + ox + px, r.y + oy + py);
	/* When, along the bottom */
	char *age = ws_age(m->time);
	char *caption = g_strdup_printf("Radar · %s", age[0] ? age + strlen(
		"Updated ") : "");
	g_free(age);
	c8ui_set_source(cr, 0x000000, 0.55);
	cairo_rectangle(cr, r.x, r.y + r.height - 32, r.width, 32);
	cairo_fill(cr);
	c8ui_set_source(cr, 0xffffff, 1);
	c8ui_text_draw(cr, family, small, caption, r.x + 12, r.y + r.height - 24,
		r.width - 24, 1);
	g_free(caption);
	if (w->pressed) {
		c8ui_set_source(cr, 0x000000, 0.15);
		cairo_paint(cr);
	}
	cairo_restore(cr);
	if (c8ui_widget_shows_focus(w)) {
		cairo_set_source_rgba(cr, 1, 1, 1, 0.9);
		cairo_set_line_width(cr, 2);
		cairo_rectangle(cr, r.x + 1, r.y + 1, r.width - 2, r.height - 2);
		cairo_stroke(cr);
	}
}

static bool radar_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		return ev->button == C8UI_BUTTON_LEFT;
	case C8UI_EVENT_RELEASE:
		if (c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			open_map(true);
		}
		return true;
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_KP_Enter ||
				ev->sym == XKB_KEY_space) {
			open_map(true);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void radar_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = narrow() ? NARROW_MAP_H : 0;
}

static void radar_destroy(struct c8ui_widget *w) {
	if (g.radar == w) {
		g.radar = NULL;
	}
}

static const struct c8ui_widget_impl radar_impl = {
	.name = "weather-radar",
	.measure = radar_measure,
	.draw = radar_draw,
	.event = radar_event,
	.destroy = radar_destroy,
};

static struct c8ui_widget *radar_tile_new(void) {
	struct c8ui_widget *w = c8ui_widget_new(&radar_impl, NULL);
	w->focusable = true;
	w->cursor = C8UI_CURSOR_POINTER;
	w->fill = true;
	w->expand = true;
	g.radar = w;
	return w;
}

/* The NWS's words for each day */

static char *details_markup(struct ws_place *p) {
	GArray *days = days_of(p);
	GString *m = g_string_new(NULL);
	for (guint i = 0; days && i < days->len; i++) {
		struct ws_day *d = &g_array_index(days, struct ws_day, i);
		if (d->day_text == NULL && d->night_text == NULL) {
			continue;
		}
		char *label = ws_day_label(d, (int)i);
		char *name = g_markup_escape_text(i == 0 && d->name ? d->name : label, -1);
		g_string_append_printf(m, "%s<span size=\"large\">%s</span>\n",
			m->len ? "\n\n" : "", name);
		g_free(name);
		g_free(label);
		if (d->day_text) {
			char *e = g_markup_escape_text(d->day_text, -1);
			g_string_append(m, e);
			g_free(e);
		}
		if (d->night_text) {
			char *e = g_markup_escape_text(d->night_text, -1);
			g_string_append_printf(m, "%s<span alpha=\"75%%\">Night: %s</span>",
				d->day_text ? "\n" : "", e);
			g_free(e);
		}
	}
	if (m->len && c8_stealth()) {
		/* Its office is named after a town near the place */
		g_string_append(m, "\n\n<span size=\"small\" alpha=\"70%\">From the "
			"National Weather Service, through weathersnail.</span>");
	} else if (m->len && p->forecast && p->forecast->office) {
		g_string_append_printf(m, "\n\n<span size=\"small\" alpha=\"70%%\">From "
			"the National Weather Service's %s office, through weathersnail."
			"</span>", p->forecast->office);
	}
	return g_string_free(m, FALSE);
}

static struct c8ui_widget *details_new(void) {
	char *m = details_markup(current());
	struct c8ui_widget *rich = c8ui_rich_new(m);
	g_free(m);
	c8ui_rich_set_color(rich, 0xffffff);
	c8ui_rich_set_line_spacing(rich, 1.15);
	rich->fill = true;
	c8ui_widget_track(rich, &g.details);
	return rich;
}

/* Home: the panorama */

static struct c8ui_widget *days_new(void) {
	struct c8ui_widget *days = c8ui_widget_new(&days_impl, NULL);
	days->focusable = true;
	days->fill = true;
	g.days = days;
	g.day_cursor = 0;
	return days;
}

static struct c8ui_widget *now_new(void) {
	struct c8ui_widget *now = c8ui_widget_new(&now_impl, NULL);
	now->fill = true;
	now->expand = true; // narrow, as tall as it measures (in a scroll)
	g.now = now;
	return now;
}

static struct c8ui_widget *scrolled(struct c8ui_widget *child) {
	struct c8ui_widget *scroll = c8ui_scroll_new(child);
	scroll->fill = true;
	scroll->expand = true;
	return scroll;
}

/* Narrow, the hub is one column going down (c8ui's): now and the days,
 * then each section under its name, the scrolls in them giving way */
static struct c8ui_widget *home_new(struct ws_place *p) {
	struct c8ui_widget *hub = c8ui_hub_new(NULL);
	c8ui_hub_set_narrow_column(hub, true);
	struct c8ui_widget *first = c8ui_box_new(C8UI_VERTICAL, 0);
	first->fill = true;
	c8ui_widget_add(first, now_new());
	c8ui_widget_add(first, days_new());
	c8ui_hub_add_full(hub, first, 0);
	if (p->forecast == NULL) {
		return hub;
	}
	if (p->alerts && p->alerts->len) {
		c8ui_hub_add(hub, "Alerts", scrolled(alerts_list_new()), SIDE_W);
	}
	struct c8ui_widget *hours = c8ui_box_new(C8UI_VERTICAL, 4);
	hours->fill = true;
	c8ui_widget_add(hours, hourly_head_new());
	c8ui_widget_add(hours, scrolled(hourly_list_new()));
	c8ui_hub_add(hub, "Hourly forecast", hours, HOURLY_W);
	struct c8ui_widget *maps = c8ui_box_new(C8UI_VERTICAL, 0);
	maps->fill = true;
	c8ui_box_set_padding(maps, 0, 0, 0, 40);
	c8ui_widget_add(maps, radar_tile_new());
	c8ui_hub_add(hub, "Maps", maps, SIDE_W);
	struct c8ui_widget *words = c8ui_box_new(C8UI_VERTICAL, 0);
	words->fill = true;
	c8ui_box_set_padding(words, 0, 0, 20, 40);
	c8ui_widget_add(words, details_new());
	c8ui_hub_add(hub, "Forecast details", scrolled(words), DETAILS_W);
	return hub;
}

/* Finding a place: the add dialog's box and the welcome's */

static void found_clear(void) {
	if (g.found) {
		g_ptr_array_unref(g.found);
		g.found = NULL;
	}
	g_clear_pointer(&g.found_for, g_free);
}

static struct ws_found *found_match(const char *text) {
	for (guint i = 0; g.found && i < g.found->len; i++) {
		struct ws_found *f = g.found->pdata[i];
		if (g_ascii_strcasecmp(f->label, text) == 0) {
			return f;
		}
	}
	return NULL;
}

static void add_found(struct ws_found *f) {
	struct ws_place *p = ws_add_place(f->name, f->lat, f->lon);
	if (p == NULL) {
		p = ws_place_near(ws_places, f->lat, f->lon); // already there
	} else {
		ws_load_cached(p);
		ws_refresh(p);
	}
	if (g.dialog) {
		c8ui_dialog_close(g.dialog);
	}
	if (p) {
		show_place(p);
	}
}

static void got_found(GPtrArray *found, void *data) {
	char *query = data;
	if (g.add_entry == NULL || strcmp(query, c8ui_entry_get(g.add_entry)) != 0) {
		g_free(query);
		return; // typed on since
	}
	found_clear();
	g.found_for = query;
	if (found) {
		g.found = g_ptr_array_ref(found);
	}
	if (g.add_pending) {
		g.add_pending = false;
		if (g.found && g.found->len) {
			add_found(g.found->pdata[0]);
		} else {
			show_message("Couldn't find that place", found ?
				"Try a town and its state, or a ZIP code." :
				"Couldn't reach weathersnail. Check your connection.");
		}
		return;
	}
	GPtrArray *labels = g_ptr_array_new();
	for (guint i = 0; g.found && i < g.found->len; i++) {
		struct ws_found *f = g.found->pdata[i];
		g_ptr_array_add(labels, f->label);
	}
	c8ui_entry_set_suggestions(g.add_entry, (const char *const *)labels->pdata,
		(int)labels->len);
	g_ptr_array_unref(labels);
}

static gboolean find_now(gpointer data) {
	g.find_timer = 0;
	if (g.add_entry == NULL) {
		return G_SOURCE_REMOVE;
	}
	const char *text = c8ui_entry_get(g.add_entry);
	if (strlen(text) >= 2) {
		ws_find_places(text, got_found, g_strdup(text));
	}
	return G_SOURCE_REMOVE;
}

static void add_typed(struct c8ui_widget *entry, void *data) {
	if (g.find_timer) {
		g_source_remove(g.find_timer);
	}
	g.add_pending = false;
	const char *text = c8ui_entry_get(entry);
	if (strlen(text) < 2) {
		g.find_timer = 0;
		c8ui_entry_set_suggestions(entry, NULL, 0);
		return;
	}
	g.find_timer = g_timeout_add(FIND_DELAY_MS, find_now, NULL);
}

/* Enter, a suggestion picked, or the dialog's Add */
static void add_chosen(void) {
	if (g.add_entry == NULL) {
		return;
	}
	const char *text = c8ui_entry_get(g.add_entry);
	if (text[0] == '\0') {
		return;
	}
	struct ws_found *f = found_match(text);
	if (f == NULL && g.found && g.found->len &&
			g_strcmp0(g.found_for, text) == 0) {
		f = g.found->pdata[0];
	}
	if (f) {
		add_found(f);
		return;
	}
	/* Not looked up yet: the first it finds */
	g.add_pending = true;
	if (g.find_timer) {
		g_source_remove(g.find_timer);
		g.find_timer = 0;
	}
	ws_find_places(text, got_found, g_strdup(text));
}

static void add_entered(struct c8ui_widget *entry, void *data) {
	add_chosen();
}

static void add_entry_gone(struct c8ui_widget *w, void *data) {
	if (g.add_entry == w) {
		g.add_entry = NULL;
		g.add_pending = false;
		if (g.find_timer) {
			g_source_remove(g.find_timer);
			g.find_timer = 0;
		}
	}
}

static struct c8ui_widget *add_entry_new(void) {
	struct c8ui_widget *e = c8ui_entry_new(NULL, "", add_entered, NULL);
	/* Only Enter (or a pick) adds, not leaving the box */
	c8ui_entry_set_enter_only(e, true);
	c8ui_entry_set_placeholder(e, "A town, or a ZIP code");
	c8ui_entry_on_change(e, add_typed, NULL);
	c8ui_entry_set_search(e, true);
	e->fill = true;
	e->on_destroy = add_entry_gone;
	found_clear();
	g.add_entry = e;
	return e;
}

static void add_dialog_done(int choice, void *data) {
	g.dialog = NULL;
	if (choice == 0) {
		add_chosen();
	}
}

static void cmd_add(struct c8ui_widget *w, void *data) {
	static const char *const buttons[] = { "Add", "Cancel" };
	g.dialog = c8ui_dialog_show(g.root, "Add a place", "Weather knows the "
		"places the US National Weather Service forecasts for.", buttons, 2,
		add_dialog_done, NULL);
	struct c8ui_widget *e = add_entry_new();
	c8ui_dialog_add(g.dialog, e);
	c8ui_widget_grab_focus(e);
}

/* Nothing yet: where are you? */
static struct c8ui_widget *welcome_new(void) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 12);
	box->fill = true;
	box->expand = true;
	c8ui_box_set_padding(box, PAGE_LEFT, 90, PAGE_LEFT, 40);
	c8ui_box_set_narrow_padding(box, NARROW_PAD, 40, NARROW_PAD, 40);
	c8ui_widget_add(box, c8ui_label_new("Weather", C8UI_TEXT_HEADER));
	struct c8ui_widget *ask = c8ui_label_new("Where are you? Type the name of a "
		"town or a ZIP code, and pick it from the list.", C8UI_TEXT_BODY);
	c8ui_label_set_max_lines(ask, 3);
	ask->max_width = 520;
	c8ui_widget_add(box, ask);
	struct c8ui_widget *e = add_entry_new();
	e->fill = false;
	e->fixed_width = 420; // gives way when narrower
	c8ui_widget_add(box, e);
	struct c8ui_widget *note = c8ui_label_new("Forecasts, radar and alerts "
		"come from the US National Weather Service, through weathersnail.com.",
		C8UI_TEXT_CAPTION);
	c8ui_label_set_color(note, C8UI_COLOR_SECONDARY);
	c8ui_label_set_max_lines(note, 3);
	note->max_width = 520;
	c8ui_widget_add(box, note);
	return box;
}

/* The pages over main: main is first in the stack, then they are, the
 * last one showing */
static int page_count(void) {
	if (g.stack == NULL) {
		return 0;
	}
	return g.stack->child_count - (g.main && g.main->parent == g.stack);
}

static struct c8ui_widget *top_page(void) {
	return page_count() > 0 ? g.stack->children[g.stack->child_count - 1] :
		NULL;
}

/* What Home is built for: a change in it builds it again, anything else
 * is drawn again in place (so a refresh doesn't throw the panorama back
 * to its start) */
static char *home_shape(void) {
	struct ws_place *p = current();
	if (p == NULL) {
		return g_strdup("welcome");
	}
	GString *s = g_string_new(NULL);
	g_string_append_printf(s, "%s %d", p->id, p->forecast != NULL);
	for (guint i = 0; p->alerts && i < p->alerts->len; i++) {
		g_string_append_printf(s, " %s", ((struct ws_alert *)p->alerts->pdata[i])->id);
	}
	return g_string_free(s, FALSE);
}

static void rebuild_main(void) {
	if (g.stack == NULL) {
		return;
	}
	struct ws_place *p = current();
	struct c8ui_widget *old = g.main;
	g_free(g.shape);
	g.shape = home_shape();
	if (p == NULL) {
		g.main = welcome_new();
	} else {
		g.main = home_new(p);
	}
	c8ui_widget_insert(g.stack, 0, g.main);
	if (old) {
		c8ui_widget_destroy(old);
	}
	c8ui_stack_set(g.stack, page_count(), false);
	if (page_count() == 0) {
		if (p == NULL && g.add_entry) {
			c8ui_widget_grab_focus(g.add_entry);
		} else if (g.days) {
			c8ui_widget_grab_focus(g.days);
		}
	}
	update_bar();
	c8ui_widget_queue_draw(g.sky);
}

static void update_home(void) {
	if (g.stack == NULL) {
		return;
	}
	char *shape = home_shape();
	bool same = g.shape && strcmp(shape, g.shape) == 0;
	g_free(shape);
	if (!same) {
		rebuild_main();
		return;
	}
	struct ws_place *p = current();
	if (g.now) {
		c8ui_widget_queue_draw(g.now);
	}
	if (g.days) {
		c8ui_widget_queue_layout(g.days);
	}
	if (g.hourly) {
		GArray *hours = hours_of(p);
		c8ui_list_set_count(g.hourly, hours_count(hours));
		c8ui_list_redraw(g.hourly);
	}
	if (g.alerts) {
		c8ui_list_redraw(g.alerts);
	}
	if (g.details) {
		char *m = details_markup(p);
		c8ui_rich_set_markup(g.details, m);
		g_free(m);
	}
	if (g.radar) {
		c8ui_widget_queue_draw(g.radar);
	}
	c8ui_widget_queue_draw(g.sky);
}

/* Pages over Home */

static void push_page(struct c8ui_widget *page, bool enter) {
	c8ui_stack_push(g.stack, page, enter);
	update_bar();
}

static void pop_page(void) {
	if (page_count() == 0) {
		return;
	}
	c8ui_stack_pop(g.stack, true);
	update_bar();
}

static void pop_all(void) {
	struct c8ui_widget *top;
	while ((top = top_page())) {
		c8ui_widget_destroy(top);
	}
	if (g.stack) {
		c8ui_stack_set(g.stack, 0, false);
	}
}

static void go_back(struct c8ui_widget *w, void *data) {
	pop_page();
}

static struct c8ui_widget *page_top(const char *title) {
	struct c8ui_widget *top = c8ui_box_new(C8UI_HORIZONTAL, 24);
	top->fill = true;
	c8ui_box_set_narrow_spacing(top, 12);
	c8ui_box_set_padding(top, 40, 36, 40, 20);
	c8ui_box_set_narrow_padding(top, 12, 20, NARROW_PAD, 10);
	struct c8ui_widget *back = c8ui_back_button_new(go_back, NULL);
	back->align = C8UI_ALIGN_CENTER;
	c8ui_widget_add(top, back);
	struct c8ui_widget *head = c8ui_label_new(title, C8UI_TEXT_HEADER);
	c8ui_label_set_narrow_style(head, C8UI_TEXT_SUBHEADER);
	head->expand = true;
	c8ui_label_set_max_lines(head, 1);
	c8ui_widget_add(top, head);
	return top;
}

static void show_place(struct ws_place *p) {
	g_free(g.place_id);
	g.place_id = g_strdup(p->id);
	if (p != ws_preview && ws_preview) {
		ws_place_free(ws_preview);
		ws_preview = NULL;
	}
	if (p->forecast == NULL && !p->loading) {
		ws_load_cached(p);
	}
	if (p->fetched == 0 && !p->loading) {
		ws_refresh(p);
	}
	pop_all();
	rebuild_main();
}

/* Places */

static int places_count(void) {
	return (int)ws_places->len + 1; // and Add
}

static void draw_place(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	const char *family = c8ui_widget_font(list);
	struct c8ui_rect r = item->rect;
	double inset = 4;
	r.x += inset;
	r.y += inset;
	r.width -= 2 * inset;
	r.height -= 2 * inset;
	if (item->index >= (int)ws_places->len) {
		c8ui_set_source(cr, 0xffffff, item->hovered ? 0.2 : 0.12);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		struct c8ui_font plus = { 44, C8UI_WEIGHT_LIGHT };
		struct c8ui_font f = { 15, C8UI_WEIGHT_NORMAL };
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_text_draw(cr, family, plus, "+", r.x + 16, r.y + 14, 0, 1);
		c8ui_text_draw(cr, family, f, "Add a place", r.x + 16,
			r.y + r.height - 34, r.width - 32, 1);
		return;
	}
	struct ws_place *p = ws_places->pdata[item->index];
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	paint_sky(cr, r, p);
	cairo_restore(cr);
	uint32_t top, bottom;
	const char *glyph;
	sky_colors(p, &top, &bottom, &glyph);
	struct c8ui_font name = { 20, C8UI_WEIGHT_SEMILIGHT };
	struct c8ui_font big = { 44, C8UI_WEIGHT_LIGHT };
	struct c8ui_font small = { 13, C8UI_WEIGHT_NORMAL };
	double x = r.x + 14, w = r.width - 28;
	c8ui_set_source(cr, 0xffffff, 1);
	const char *label = ws_place_label(p);
	double nh = c8ui_text_draw(cr, family, name, label, x, r.y + 10, w - 120, 1);
	if (p == ws_home()) {
		c8ui_set_source(cr, 0xffffff, 0.8);
		if (r.height < 140) {
			/* Short tiles (narrow): beside the name, not under it */
			double tw, th;
			c8ui_text_size(family, name, label, w - 120, 1, &tw, &th);
			c8ui_text_draw(cr, family, small, "Default", x + tw + 10,
				r.y + 10 + nh - 18, 80, 1);
		} else {
			c8ui_text_draw(cr, family, small, "Default", x, r.y + 12 + nh, w, 1);
		}
	}
	if (p->forecast || p->now) {
		c8ui_weather_glyph(cr, glyph, r.x + r.width - 44, r.y + 44, 56, 1, top);
		double temp = p->now ? p->now->temp : NAN;
		if (isnan(temp) && p->forecast && p->forecast->hours->len) {
			temp = g_array_index(p->forecast->hours, struct ws_hour, 0).temp;
		}
		char *t = ws_temp(temp, false);
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_text_draw(cr, family, big, t, x, r.y + r.height - 82, 0, 1);
		g_free(t);
		GString *line = g_string_new(NULL);
		if (p->forecast && p->forecast->days->len) {
			struct ws_day *d = &g_array_index(p->forecast->days, struct ws_day, 0);
			char *hi = ws_temp(d->high, false), *lo = ws_temp(d->low, false);
			g_string_append_printf(line, "%s / %s", hi, lo);
			g_free(hi);
			g_free(lo);
		}
		const char *sum = ws_now_summary(p);
		if (sum) {
			g_string_append_printf(line, "%s%s", line->len ? "  " : "", sum);
		}
		c8ui_set_source(cr, 0xffffff, 0.9);
		c8ui_text_draw(cr, family, small, line->str, x, r.y + r.height - 26, w, 1);
		g_string_free(line, TRUE);
	} else {
		c8ui_set_source(cr, 0xffffff, 0.8);
		c8ui_text_draw(cr, family, small, p->error ? p->error : "…", x,
			r.y + r.height - 44, w, 2);
	}
	if (p->alerts && p->alerts->len) {
		struct ws_alert *a = p->alerts->pdata[0];
		c8ui_set_source(cr, a->color, 1);
		cairo_rectangle(cr, r.x, r.y, 6, r.height);
		cairo_fill(cr);
	}
	if (item->selected || item->cursor) {
		cairo_set_source_rgba(cr, 1, 1, 1, 1);
		cairo_set_line_width(cr, item->selected ? 3 : 1);
		cairo_rectangle(cr, r.x + 1.5, r.y + 1.5, r.width - 3, r.height - 3);
		cairo_stroke(cr);
	}
}

static void place_opened(struct c8ui_widget *list, int index, void *data) {
	if (index >= (int)ws_places->len) {
		cmd_add(NULL, NULL);
		return;
	}
	if (index >= 0) {
		show_place(ws_places->pdata[index]);
	}
}

static void place_context(struct c8ui_widget *list, int index, double x,
		double y, void *data) {
	g_clear_pointer(&g.target_id, g_free);
	if (index >= 0 && index < (int)ws_places->len) {
		c8ui_list_select(list, index);
		g.target_id = g_strdup(((struct ws_place *)ws_places->pdata[index])->id);
	} else {
		c8ui_list_select(list, -1);
	}
	update_bar();
	c8ui_appbar_show(g.appbar);
	c8ui_navbar_show(g.navbar);
}

static void places_gone(struct c8ui_widget *w, void *data) {
	if (g.places == w) {
		g.places = NULL;
		g.places_list = NULL;
		g_clear_pointer(&g.target_id, g_free);
	}
}

static void places_cells(void) {
	if (g.places_list == NULL) {
		return;
	}
	double w = PLACE_W, h = PLACE_H;
	if (narrow() && g.root) {
		w = c8ui_root_width(g.root) - 2 * NARROW_PAD;
		h = 120;
	}
	c8ui_list_set_mode(g.places_list, C8UI_LIST_GRID, w, h);
}

static void open_places(bool enter) {
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 0);
	page->fill = true;
	page->expand = true;
	c8ui_widget_set_background(page, PLACES_BG);
	page->on_destroy = places_gone;
	c8ui_widget_add(page, page_top("Places"));
	struct c8ui_widget *list = c8ui_list_new(C8UI_LIST_GRID, PLACE_W, PLACE_H,
		draw_place, NULL);
	g.places = page;
	g.places_list = list;
	places_cells();
	c8ui_list_set_count(list, places_count());
	c8ui_list_set_click_opens(list, true);
	c8ui_list_set_keep(list, true);
	c8ui_list_on_open(list, place_opened, NULL);
	c8ui_list_on_context(list, place_context, NULL);
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 0);
	box->fill = true;
	c8ui_box_set_padding(box, PAGE_LEFT - 4, 0, 40, 40);
	c8ui_box_set_narrow_padding(box, NARROW_PAD - 4, 0, NARROW_PAD - 4, 40);
	list->fill = true;
	c8ui_widget_add(box, list);
	c8ui_widget_add(page, scrolled(box));
	push_page(page, enter);
	c8ui_widget_grab_focus(list);
}

static void places_changed(void) {
	if (g.places_list) {
		c8ui_list_set_count(g.places_list, places_count());
		c8ui_list_redraw(g.places_list);
	}
}

/* Maps: the radar to pan around and zoom (a pinch, Ctrl+wheel or
 * Ctrl+plus/minus, Ctrl+0 back to the map's own size) */

#define MAP_ZOOM_MAX 4.0
#define MAP_ZOOM_STEP 1.25 // a wheel click or Ctrl+plus

static double map_zoom(void) {
	return g.map_zoom > 0 ? g.map_zoom : 1;
}

static void mapview_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct ws_place *p = current();
	const struct radar_map *m = map_for(p);
	*width = m ? m->width * map_zoom() : avail;
	*height = m ? m->height * map_zoom() : 200;
}

/* Out until the map just covers the page (or its own size, if smaller) */
static double map_zoom_min(const struct radar_map *m) {
	if (g.map_scroll == NULL) {
		return 1;
	}
	struct c8ui_rect r = g.map_scroll->rect;
	return fmin(1, fmax(r.width / m->width, r.height / m->height));
}

/* Zoom to z keeping the map's point at (cx, cy) of the window where it
 * is, then move it by (dx, dy): the fingers carry the map */
static void map_zoom_at(double z, double cx, double cy, double dx,
		double dy) {
	struct ws_place *p = current();
	const struct radar_map *m = map_for(p);
	if (m == NULL || g.map_scroll == NULL) {
		return;
	}
	z = fmax(map_zoom_min(m), fmin(MAP_ZOOM_MAX, z));
	struct c8ui_rect r = g.map_scroll->rect;
	double ox, oy;
	c8ui_scroll_get_offset(g.map_scroll, &ox, &oy);
	double z0 = map_zoom();
	double mx = (ox + cx - r.x) / z0, my = (oy + cy - r.y) / z0;
	g.map_zoom = z;
	/* Laid out again now, so the scroll takes the new size's offsets */
	c8ui_widget_layout(g.map_scroll, r);
	c8ui_scroll_to_x(g.map_scroll, mx * z - (cx - r.x) - dx);
	c8ui_scroll_to(g.map_scroll, my * z - (cy - r.y) - dy);
	c8ui_widget_queue_draw(g.map_scroll);
}

/* Around the middle of the page, for the keyboard */
static void map_zoom_step(double factor) {
	if (g.map_scroll) {
		struct c8ui_rect r = g.map_scroll->rect;
		map_zoom_at(factor ? map_zoom() * factor : 1, r.x + r.width / 2,
			r.y + r.height / 2, 0, 0);
	}
}

static bool mapview_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	switch (ev->type) {
	case C8UI_EVENT_PINCH_BEGIN:
		g.map_pinching = true;
		g.map_pinch_zoom = map_zoom();
		return true;
	case C8UI_EVENT_PINCH_UPDATE:
		if (g.map_pinching) {
			map_zoom_at(g.map_pinch_zoom * ev->scale, ev->x, ev->y,
				ev->dx, ev->dy);
		}
		return true;
	case C8UI_EVENT_PINCH_END:
		g.map_pinching = false;
		c8ui_widget_queue_draw(w); // smoothly now it's still
		return true;
	case C8UI_EVENT_SCROLL:
		if (!(ev->mods & C8UI_MOD_CTRL) || ev->dy == 0) {
			return false;
		}
		map_zoom_at(map_zoom() * (ev->precise ? exp(-ev->dy / 200) :
			ev->dy < 0 ? MAP_ZOOM_STEP : 1 / MAP_ZOOM_STEP), ev->x, ev->y,
			0, 0);
		return true;
	case C8UI_EVENT_KEY:
		if (!(ev->mods & C8UI_MOD_CTRL)) {
			return false;
		}
		switch (ev->sym) {
		case XKB_KEY_plus:
		case XKB_KEY_equal:
		case XKB_KEY_KP_Add:
			map_zoom_step(MAP_ZOOM_STEP);
			return true;
		case XKB_KEY_minus:
		case XKB_KEY_KP_Subtract:
			map_zoom_step(1 / MAP_ZOOM_STEP);
			return true;
		case XKB_KEY_0:
		case XKB_KEY_KP_0:
			map_zoom_step(0);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void mapview_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct ws_place *p = current();
	const struct radar_map *m = map_for(p);
	struct c8ui_rect r = w->rect;
	if (m == NULL) {
		struct c8ui_font f = { 15, C8UI_WEIGHT_NORMAL };
		c8ui_set_source(cr, 0xffffff, 0.85);
		c8ui_text_draw(cr, c8ui_widget_font(w), f, map_missing(p),
			r.x + side_pad(), r.y + 20, fmin(400, r.width - 2 * side_pad()), 2);
		return;
	}
	double z = map_zoom();
	double x = round(r.x), y = round(r.y);
	if (z == 1) {
		blit_map(cr, m, x, y);
	} else if (z < 1 && !g.map_pinching) {
		/* Still and smaller: a kept copy at this size, shrunk well */
		c8ui_draw_surface(cr, m->map, x, y, m->width * z, m->height * z);
		if (m->labels) {
			c8ui_draw_surface(cr, m->labels, x, y, m->width * z,
				m->height * z);
		}
	} else {
		/* Moving, or bigger: only what the page shows is scaled */
		cairo_save(cr);
		cairo_translate(cr, x, y);
		cairo_scale(cr, z, z);
		for (int i = 0; i < 2; i++) {
			cairo_surface_t *s = i ? m->labels : m->map;
			if (s) {
				cairo_set_source_surface(cr, s, 0, 0);
				cairo_pattern_set_filter(cairo_get_source(cr),
					CAIRO_FILTER_BILINEAR);
				cairo_paint(cr);
			}
		}
		cairo_restore(cr);
	}
	double px, py;
	radar_project(m, p->lat, p->lon, &px, &py);
	draw_marker(cr, x + px * z, y + py * z);
}

static void mapview_destroy(struct c8ui_widget *w) {
	if (g.map_view == w) {
		g.map_view = NULL;
	}
}

static const struct c8ui_widget_impl mapview_impl = {
	.name = "weather-map",
	.measure = mapview_measure,
	.draw = mapview_draw,
	.event = mapview_event,
	.destroy = mapview_destroy,
};

/* The place in the middle of the window, once there's a map to show */
static int centre_map(void *data) {
	struct ws_place *p = current();
	const struct radar_map *m = map_for(p);
	if (g.map_scroll == NULL || m == NULL) {
		return 0;
	}
	double px, py;
	radar_project(m, p->lat, p->lon, &px, &py);
	struct c8ui_rect r = g.map_scroll->rect;
	double z = map_zoom();
	c8ui_scroll_to_x(g.map_scroll, fmax(0, px * z - r.width / 2));
	c8ui_scroll_to(g.map_scroll, fmax(0, py * z - r.height / 2));
	g.map_centred = true;
	return 0;
}

/* The legend: each kind's colours, light to heavy */
static void legend_draw(struct c8ui_widget *w, cairo_t *cr, void *data) {
	int count;
	const struct radar_ramp *ramps = radar_ramps(&count);
	struct c8ui_rect r = w->rect;
	const char *family = c8ui_widget_font(w);
	struct c8ui_font f = { 13, C8UI_WEIGHT_NORMAL };
	double x = r.x + (narrow() ? NARROW_PAD : PAGE_LEFT);
	double y = r.y + 4;
	for (int i = 0; i < count; i++) {
		double tw, th;
		c8ui_text_size(family, f, ramps[i].label, 0, 1, &tw, &th);
		if (x + tw + 8 + ramps[i].count * 12 > r.x + r.width - 20) {
			break;
		}
		c8ui_set_source(cr, 0xffffff, 0.9);
		c8ui_text_draw(cr, family, f, ramps[i].label, x, y, 0, 1);
		x += tw + 8;
		for (int k = 0; k < ramps[i].count; k++) {
			c8ui_set_source(cr, ramps[i].stops[k].color, 1);
			cairo_rectangle(cr, x + k * 12, y + 3, 12, 12);
			cairo_fill(cr);
		}
		x += ramps[i].count * 12 + 24;
	}
}

static void open_map(bool enter) {
	struct ws_place *p = current();
	if (p == NULL) {
		return;
	}
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 0);
	page->fill = true;
	page->expand = true;
	c8ui_widget_set_background(page, PLACES_BG);
	char *title = g_strdup_printf("Radar · %s", ws_place_label(p));
	c8ui_widget_add(page, page_top(title));
	g_free(title);
	struct c8ui_widget *legend = c8ui_canvas_new(0, 24, legend_draw, NULL, NULL);
	legend->fill = true;
	c8ui_widget_add(page, legend);
	struct c8ui_widget *view = c8ui_widget_new(&mapview_impl, NULL);
	g.map_view = view;
	struct c8ui_widget *scroll = c8ui_scroll_new(view);
	c8ui_scroll_set_directions(scroll, true, true);
	scroll->fill = true;
	scroll->expand = true;
	c8ui_widget_track(scroll, &g.map_scroll);
	g.map_centred = false;
	c8ui_widget_add(page, scroll);
	c8ui_widget_track(page, &g.map_page);
	push_page(page, enter);
	/* The map takes Ctrl+plus/minus/0; arrows go on to the scroll */
	view->focusable = true;
	c8ui_widget_grab_focus(view);
	/* After the first layout, when the scroll knows its size */
	c8ui_root_timer_add(g.root, 30, centre_map, NULL);
}

/* An alert's page: what it says, and what to do */

static void alert_page_gone(struct c8ui_widget *w, void *data) {
	if (g.alert_page == w) {
		g.alert_page = NULL;
		g.alert_text = NULL;
		g_clear_pointer(&g.alert_id, g_free);
	}
}

/* The NWS breaks its lines at 65 or so: join them, keep the paragraphs */
static char *reflow(const char *text) {
	GString *out = g_string_new(NULL);
	for (const char *c = text; *c; c++) {
		if (*c == '\n' && c[1] != '\n' && c > text && c[-1] != '\n') {
			g_string_append_c(out, ' ');
		} else {
			g_string_append_c(out, *c);
		}
	}
	char *e = g_markup_escape_text(out->str, -1);
	g_string_free(out, TRUE);
	return e;
}

static char *alert_markup(struct ws_alert *a, const char *desc,
		const char *instr, bool loading) {
	GString *m = g_string_new(NULL);
	char *e;
	if (c8_stealth()) {
		/* The headline, counties, text and office all name places */
		g_string_append(m, "<span alpha=\"75%\">What this alert says is "
			"hidden in stealth mode, as it names the places it's for.</span>");
		return g_string_free(m, FALSE);
	}
	if (a->headline) {
		e = g_markup_escape_text(a->headline, -1);
		g_string_append_printf(m, "<span size=\"large\">%s</span>\n\n", e);
		g_free(e);
	}
	if (a->area) {
		e = g_markup_escape_text(a->area, -1);
		g_string_append_printf(m, "<span alpha=\"75%%\">%s</span>\n\n", e);
		g_free(e);
	}
	if (desc) {
		e = reflow(desc);
		g_string_append_printf(m, "%s\n\n", e);
		g_free(e);
	}
	if (instr) {
		e = reflow(instr);
		g_string_append_printf(m, "<b>What to do</b>\n%s\n\n", e);
		g_free(e);
	}
	if (loading) {
		g_string_append(m, "<span alpha=\"75%\">Getting the rest…</span>");
	} else if (!desc && !instr) {
		g_string_append(m, "<span alpha=\"75%\">Couldn't get what it says. "
			"Check your connection.</span>");
	}
	if (a->sender) {
		e = g_markup_escape_text(a->sender, -1);
		g_string_append_printf(m, "\n<span size=\"small\" alpha=\"70%%\">%s</span>",
			e);
		g_free(e);
	}
	return g_string_free(m, FALSE);
}

static struct ws_alert *alert_find(const char *id) {
	GPtrArray *alerts = alerts_of(current());
	for (guint i = 0; id && alerts && i < alerts->len; i++) {
		struct ws_alert *a = alerts->pdata[i];
		if (g_strcmp0(a->id, id) == 0) {
			return a;
		}
	}
	return NULL;
}

static void got_alert_text(const char *desc, const char *instr, void *data) {
	char *id = data;
	struct ws_alert *a = alert_find(id);
	if (g.alert_text && a && g_strcmp0(g.alert_id, id) == 0) {
		char *m = alert_markup(a, desc, instr, false);
		c8ui_rich_set_markup(g.alert_text, m);
		g_free(m);
	}
	g_free(id);
}

static void open_alert(struct ws_alert *a) {
	if (a == NULL || a->id == NULL) {
		return;
	}
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 0);
	page->fill = true;
	page->expand = true;
	c8ui_widget_set_background(page, c8ui_shade(a->color, 0.35));
	page->on_destroy = alert_page_gone;
	c8ui_widget_add(page, page_top(a->event));
	char *m = alert_markup(a, NULL, NULL, true);
	struct c8ui_widget *rich = c8ui_rich_new(m);
	g_free(m);
	c8ui_rich_set_color(rich, 0xffffff);
	c8ui_rich_set_line_spacing(rich, 1.15);
	rich->fill = true;
	rich->max_width = 760;
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 0);
	box->fill = true;
	c8ui_box_set_padding(box, PAGE_LEFT, 0, 40, 40);
	c8ui_box_set_narrow_padding(box, NARROW_PAD, 0, NARROW_PAD, 40);
	c8ui_widget_add(box, rich);
	c8ui_widget_add(page, scrolled(box));
	g.alert_page = page;
	g.alert_text = rich;
	g_free(g.alert_id);
	g.alert_id = g_strdup(a->id);
	push_page(page, true);
	ws_alert_text(a->id, got_alert_text, g_strdup(a->id));
}

/* The bars */

static struct ws_place *bar_place(void) {
	if (g.places && top_page() == g.places) {
		return ws_place_find(g.target_id);
	}
	return g.stack && page_count() == 0 ? current() : NULL;
}

static void update_bar(void) {
	if (g.appbar == NULL) {
		return;
	}
	struct ws_place *p = bar_place();
	bool fav = is_favourite(p);
	c8ui_widget_set_hidden(g.cmd_fav, p == NULL || fav);
	c8ui_widget_set_hidden(g.cmd_unfav, !fav);
	c8ui_widget_set_hidden(g.cmd_home, !fav || p == ws_home());
	c8ui_widget_set_hidden(g.cmd_pin, !fav);
	bool on_places = g.places && top_page() == g.places;
	c8ui_widget_set_hidden(g.cmd_add, !on_places && ws_places->len > 0);
	c8ui_widget_set_hidden(g.cmd_to_c, ws_settings.units == WS_CELSIUS);
	c8ui_widget_set_hidden(g.cmd_to_f, ws_settings.units != WS_CELSIUS);
	int place = PLACE_HOME;
	struct c8ui_widget *top = top_page();
	if (top) {
		place = top == g.places ? PLACE_PLACES : top == g.map_page ?
			PLACE_MAPS : -1;
	}
	c8ui_navbar_set_current(g.navbar, place);
}

static void cmd_fav(struct c8ui_widget *w, void *data) {
	struct ws_place *p = current();
	if (p == NULL || p != ws_preview) {
		return;
	}
	struct ws_place *added = ws_add_place(p->name, p->lat, p->lon);
	if (added == NULL) {
		added = ws_place_near(ws_places, p->lat, p->lon);
	} else {
		ws_load_cached(added);
		ws_refresh(added);
	}
	if (added) {
		show_place(added);
	}
	places_changed();
}

static void remove_chosen(int choice, void *data) {
	char *id = data;
	struct ws_place *p = ws_place_find(id);
	g_free(id);
	if (choice != 0 || p == NULL) {
		return;
	}
	bool shown = p == current();
	if (g_strcmp0(g.place_id, p->id) == 0) {
		g_clear_pointer(&g.place_id, g_free);
	}
	ws_remove_place(p);
	places_changed();
	if (shown) {
		rebuild_main();
	}
	update_bar();
	tile_later();
}

static void cmd_unfav(struct c8ui_widget *w, void *data) {
	struct ws_place *p = bar_place();
	if (!is_favourite(p)) {
		return;
	}
	static const char *const buttons[] = { "Remove", "Cancel" };
	char *msg = g_strdup_printf("%s won't be in Places any more%s.",
		ws_place_label(p),
		p->remote ? ", here or on your weathersnail account" : "");
	c8ui_dialog_show(g.root, "Remove this place?", msg, buttons, 2,
		remove_chosen, g_strdup(p->id));
	g_free(msg);
}

static void cmd_home(struct c8ui_widget *w, void *data) {
	struct ws_place *p = bar_place();
	if (!is_favourite(p)) {
		return;
	}
	ws_set_home(p);
	places_changed();
	update_bar();
	tile_later();
}

static void pinned(GObject *source, GAsyncResult *res, gpointer data) {
	char *id = data;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		NULL);
	gboolean ok = FALSE;
	if (r) {
		g_variant_get(r, "(b)", &ok);
		g_variant_unref(r);
	}
	struct ws_place *p = ws_place_find(id);
	if (ok && p) {
		char *tile = ws_place_tile_id(p);
		ws_tile_update(tile, p);
		g_free(tile);
	}
	g_free(id);
}

static void cmd_pin(struct c8ui_widget *w, void *data) {
	struct ws_place *p = bar_place();
	GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
	/* The id goes into the tile's command */
	if (!is_favourite(p) || bus == NULL || !ws_id_ok(p->id)) {
		return;
	}
	char *tile = ws_place_tile_id(p);
	char *exec = g_strdup_printf("c8-weather weather:place/%s", p->id);
	char *name = g_utf8_substring(p->name, 0, MIN(64, g_utf8_strlen(p->name,
		-1)));
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
	g_variant_builder_add(&b, "{ss}", "name", name);
	g_variant_builder_add(&b, "{ss}", "exec", exec);
	g_variant_builder_add(&b, "{ss}", "icon", APP_ID);
	g_variant_builder_add(&b, "{ss}", "color", TILE_COLOR);
	g_variant_builder_add(&b, "{ss}", "size", "wide");
	/* The question waits for an answer: long enough for one */
	g_dbus_connection_call(bus, "org.cont8nuum.Tiles", "/org/cont8nuum/Tiles",
		"org.cont8nuum.Tiles1", "RequestPin", g_variant_new("(sa{ss})", tile, &b),
		G_VARIANT_TYPE("(b)"), G_DBUS_CALL_FLAGS_NONE, 60000, NULL, pinned,
		g_strdup(p->id));
	g_free(name);
	g_free(exec);
	g_free(tile);
	g_object_unref(bus);
}

static void redraw_all(void) {
	update_home();
	if (g.now) {
		c8ui_widget_queue_draw(g.now);
	}
	if (g.places_list) {
		c8ui_list_redraw(g.places_list);
	}
	if (g.hourly) {
		c8ui_list_redraw(g.hourly);
	}
	if (g.alerts) {
		c8ui_list_redraw(g.alerts);
	}
}

static void set_units(enum ws_units units) {
	if (ws_settings.units == units) {
		return;
	}
	ws_settings.units = units;
	ws_save();
	/* The numbers change at once; the NWS's words come in them next */
	ws_refresh_all();
	redraw_all();
	update_bar();
	tile_later();
	if (g.charms) {
		c8ui_charms_changed(g.charms, "options");
	}
}

static void cmd_to_c(struct c8ui_widget *w, void *data) {
	set_units(WS_CELSIUS);
}

static void cmd_to_f(struct c8ui_widget *w, void *data) {
	set_units(WS_FAHRENHEIT);
}

static void refresh(void) {
	ws_account_sync();
	ws_refresh_all();
	radar_refresh();
}

static void cmd_refresh(struct c8ui_widget *w, void *data) {
	refresh();
}

static void nav_chosen(struct c8ui_widget *bar, int index, void *data) {
	c8ui_appbar_hide(g.appbar);
	pop_all();
	if (index == PLACE_PLACES) {
		open_places(true);
	} else if (index == PLACE_MAPS) {
		open_map(true);
	} else {
		c8ui_stack_set(g.stack, 0, true);
	}
	update_bar();
}

static bool keys(const struct c8ui_event *ev, void *data) {
	if (ev->sym == XKB_KEY_Escape && page_count()) {
		pop_page();
		return true;
	}
	if (ev->sym == XKB_KEY_Menu) {
		g_clear_pointer(&g.target_id, g_free);
		toggle_bars();
		return true;
	}
	if (ev->sym == XKB_KEY_F5 || ((ev->mods & C8UI_MOD_CTRL) &&
			ev->base_sym == XKB_KEY_r)) {
		refresh();
		return true;
	}
	return false;
}

/* Changes */

static void place_changed(struct ws_place *p, void *data) {
	if (g.win) {
		if (p == NULL || p == current()) {
			update_home();
		}
		places_changed();
		if (g.map_view) {
			c8ui_widget_queue_layout(g.map_view);
		}
	}
	tile_later();
}

static void radar_ready(void *data) {
	if (g.radar) {
		c8ui_widget_queue_draw(g.radar);
	}
	if (g.map_view) {
		c8ui_widget_queue_layout(g.map_view);
		c8ui_widget_queue_draw(g.map_view);
		if (!g.map_centred && g.root) {
			c8ui_root_timer_add(g.root, 30, centre_map, NULL);
		}
	}
}

/* The account's places came, went or changed */
static void remote_changed(const char *error, bool loud, void *data) {
	if (error) {
		if (loud) {
			show_message("Your weathersnail places", error);
		}
		return;
	}
	for (guint i = 0; i < ws_places->len; i++) {
		struct ws_place *p = ws_places->pdata[i];
		if (p->forecast == NULL && !p->loading) {
			ws_load_cached(p);
			if (p->fetched == 0) {
				ws_refresh(p);
			}
		}
	}
	if (g.win) {
		/* The one shown may be gone, or another's now */
		if (g.place_id && ws_place_find(g.place_id) == NULL &&
				!(ws_preview && strcmp(ws_preview->id, g.place_id) == 0)) {
			g_clear_pointer(&g.place_id, g_free);
		}
		g_clear_pointer(&g.target_id, g_free);
		update_home();
		places_changed();
		update_bar();
	}
	tile_later();
	if (g.charms) {
		c8ui_charms_changed(g.charms, "options");
	}
}

static gboolean every_while(gpointer data) {
	refresh();
	return G_SOURCE_CONTINUE;
}

/* Charms */

struct search_req {
	struct c8ui_search *search;
};

static void search_found(GPtrArray *found, void *data) {
	struct c8ui_search *s = data;
	for (guint i = 0; found && i < found->len; i++) {
		struct ws_found *f = found->pdata[i];
		if (ws_place_near(ws_places, f->lat, f->lon)) {
			continue; // listed as a favourite already
		}
		char lat[G_ASCII_DTOSTR_BUF_SIZE], lon[G_ASCII_DTOSTR_BUF_SIZE];
		char *id = g_strdup_printf("at:%s,%s,%s",
			g_ascii_formatd(lat, sizeof(lat), "%.5f", f->lat),
			g_ascii_formatd(lon, sizeof(lon), "%.5f", f->lon), f->name);
		c8ui_search_add(s, id, f->label, f->detail, NULL);
		g_free(id);
	}
	c8ui_search_done(s);
}

static void search(struct c8ui_search *s, const char *query, void *data) {
	if (query[0] == '\0') {
		return;
	}
	char *q = g_utf8_casefold(query, -1);
	for (guint i = 0; i < ws_places->len; i++) {
		struct ws_place *p = ws_places->pdata[i];
		/* The name shown is what's searched: the real one isn't shown in
		 * stealth mode */
		char *name = g_utf8_casefold(ws_place_label(p), -1);
		if (strstr(name, q)) {
			char *id = g_strconcat("fav:", p->id, NULL);
			char *t = p->now ? ws_temp(p->now->temp, true) : g_strdup("");
			c8ui_search_add(s, id, ws_place_label(p), t, NULL);
			g_free(t);
			g_free(id);
		}
		g_free(name);
	}
	g_free(q);
	if (strlen(query) >= 2) {
		c8ui_search_hold(s);
		ws_find_places(query, search_found, s);
	}
}

static void ensure_window(void);

static void open_result(const char *id, const char *query, void *data) {
	ensure_window();
	if (g_str_has_prefix(id, "fav:")) {
		struct ws_place *p = ws_place_find(id + 4);
		if (p) {
			show_place(p);
		}
		return;
	}
	if (!g_str_has_prefix(id, "at:")) {
		return;
	}
	char **parts = g_strsplit(id + 3, ",", 3);
	if (g_strv_length(parts) == 3) {
		double lat = g_ascii_strtod(parts[0], NULL);
		double lon = g_ascii_strtod(parts[1], NULL);
		struct ws_place *fav = ws_place_near(ws_places, lat, lon);
		if (fav) {
			show_place(fav);
		} else {
			if (ws_preview) {
				ws_place_free(ws_preview);
			}
			ws_preview = ws_place_new("preview", parts[2], lat, lon);
			ws_refresh(ws_preview);
			show_place(ws_preview);
		}
	}
	g_strfreev(parts);
}

static void option_changed(struct c8ui_setting *s, void *data) {
	const char *id = c8ui_setting_id(s);
	if (strcmp(id, "units") == 0) {
		set_units(c8ui_setting_get_int(s) == 1 ? WS_CELSIUS : WS_FAHRENHEIT);
	} else if (strcmp(id, "accounts") == 0) {
		g_spawn_command_line_async("c8-settings --page accounts", NULL);
	} else if (strcmp(id, "refresh") == 0) {
		refresh();
	}
}

static void options_page(struct c8ui_settings_page *page, void *data) {
	static const char *const units[] = { "Fahrenheit", "Celsius" };
	struct c8ui_setting *s = c8ui_page_choice(page, "units", "Show temperatures in",
		units, 2, ws_settings.units == WS_CELSIUS, option_changed, NULL);
	c8ui_setting_set_description(s, "Wind and pressure follow: mph and inches, "
		"or km/h and hPa");
	c8ui_page_heading(page, "Your places");
	if (ws_synced) {
		const char *who = ws_account_name();
		if (who && c8_stealth()) {
			who = c8_stealth_name(); // the account's nickname may be anything
		}
		char *text = g_strdup_printf("Your places are the ones saved on your "
			"snail.zone account%s%s%s, so they're on weathersnail.com's map "
			"too.", who ? " (" : "", who ? who : "", who ? ")" : "");
		c8ui_page_paragraph(page, text);
		g_free(text);
		if (ws_account_error()) {
			c8ui_page_paragraph(page, ws_account_error());
		}
	} else {
		c8ui_page_paragraph(page, "Sign in to a snail.zone account and your "
			"places follow you to other PCs and to weathersnail.com.");
	}
	c8ui_page_link(page, "accounts", "Online accounts in PC settings",
		option_changed, NULL);
	c8ui_page_button(page, "refresh", "Refresh now", option_changed, NULL);
}

/* The window */

static void window_gone(struct c8ui_widget *w, void *data) {
	g.win = NULL;
	g.root = NULL;
	g.sky = g.stack = g.main = NULL;
	g.now = g.days = g.hourly = g.details = g.alerts = g.radar = NULL;
	g.places = g.places_list = g.map_page = g.map_scroll = g.map_view = NULL;
	g.alert_page = g.alert_text = NULL;
	g.appbar = g.navbar = NULL;
	g.dialog = g.add_entry = NULL;
	g_clear_pointer(&g.shape, g_free);
	g_clear_pointer(&g.target_id, g_free);
	g_clear_pointer(&g.alert_id, g_free);
	found_clear();
}

/* Built again, with the same page open over it (the names in it changed) */
static void relayout(void) {
	int top = PLACE_HOME;
	struct c8ui_widget *p = top_page();
	if (p) {
		top = p == g.places ? PLACE_PLACES : p == g.map_page ? PLACE_MAPS : -1;
	}
	char *alert = g_strdup(g.alert_id);
	pop_all();
	rebuild_main();
	if (top == PLACE_PLACES) {
		open_places(false);
	} else if (top == PLACE_MAPS) {
		open_map(false);
	} else if (alert) {
		struct ws_alert *a = alert_find(alert);
		if (a) {
			open_alert(a);
		}
	}
	g_free(alert);
}

/* Stealth mode on or off: everything drawn again, the pages' titles too */
static void stealth_changed(void *data) {
	if (g.win) {
		relayout();
		if (g.places_list) {
			c8ui_list_redraw(g.places_list);
		}
	}
	tile_later();
}

static void resized(struct c8ui_root *root, double width, double height,
		void *data) {
	/* Sizes only: the widgets reflow by themselves */
	places_cells();
	if (g.hourly) {
		c8ui_list_set_count(g.hourly, hours_count(hours_of(current())));
	}
}

static struct c8ui_widget *command(const char *icon, const char *label,
		bool right, c8ui_action_fn fn) {
	return c8ui_appbar_add(g.appbar, icon, label, right, fn, NULL);
}

static void make_window(void) {
	g.win = c8ui_window_new(g.app, "Weather", 1280, 760);
	g.root = c8ui_window_root(g.win);
	c8ui_window_set_background(g.win, 0x2f6fae, 1);

	g.sky = c8ui_widget_new(&sky_impl, NULL);
	g.sky->fill = true;
	g.sky->on_destroy = window_gone;
	c8ui_widget_set_scheme(g.sky, C8UI_SCHEME_DARK);
	g.stack = c8ui_stack_new();
	g.stack->fill = true;
	c8ui_widget_add(g.sky, g.stack);
	c8ui_root_set_child(g.root, g.sky);
	c8ui_root_set_key_handler(g.root, keys, NULL);
	c8ui_root_on_resize(g.root, resized, NULL);

	g.navbar = c8ui_navbar_new(g.root, nav_chosen, NULL);
	c8ui_navbar_set_colors(g.navbar, BAR, BAR_TILE);
	c8ui_navbar_add(g.navbar, WEATHER_GLYPHS "/home.svg", "Home");
	c8ui_navbar_add(g.navbar, WEATHER_GLYPHS "/places.svg", "Places");
	c8ui_navbar_add(g.navbar, WEATHER_GLYPHS "/maps.svg", "Maps");

	g.appbar = c8ui_appbar_new(g.root);
	g.cmd_fav = command(WEATHER_GLYPHS "/places.svg", "Add to places", false,
		cmd_fav);
	g.cmd_unfav = command("list-remove", "Remove", false, cmd_unfav);
	g.cmd_home = command(WEATHER_GLYPHS "/home.svg", "Set as default", false,
		cmd_home);
	g.cmd_pin = command(WEATHER_GLYPHS "/pin.svg", "Pin to Start", false,
		cmd_pin);
	g.cmd_add = command("list-add", "Add a place", true, cmd_add);
	g.cmd_to_c = command(WEATHER_GLYPHS "/units.svg", "Change to Celsius", true,
		cmd_to_c);
	g.cmd_to_f = command(WEATHER_GLYPHS "/units.svg", "Change to Fahrenheit",
		true, cmd_to_f);
	g.cmd_refresh = command("view-refresh", "Refresh", true, cmd_refresh);

	g.main = NULL;
	rebuild_main();
}

static void ensure_window(void) {
	if (g.win == NULL) {
		make_window();
		refresh();
	}
}

static void startup(struct c8ui_app *app, void *data) {
	g.app = app;
	ws_load();
	ws_account_init(remote_changed, NULL, true);
	for (guint i = 0; i < ws_places->len; i++) {
		ws_load_cached(ws_places->pdata[i]);
	}
	ws_on_change(place_changed, NULL);
	radar_init(radar_ready, NULL, c8ui_app_theme(app)->font);
	c8_stealth_watch(stealth_changed, NULL);
	g.charms = c8ui_charms_new(app);
	if (g.charms) {
		c8ui_charms_on_search(g.charms, search, open_result, NULL, NULL);
		c8ui_charms_add_page(g.charms, "options", "Options", options_page, NULL);
	}
	g.timer = g_timeout_add_seconds(REFRESH_S, every_while, NULL);
	tile_later();
}

/* weather:place/ID (a place's own tile) opens that place */
static const char *place_in_uri(const char *uri) {
	if (!g_str_has_prefix(uri, "weather:")) {
		return NULL;
	}
	const char *p = strstr(uri, "place/");
	return p ? p + strlen("place/") : NULL;
}

static void open(struct c8ui_app *app, char **uris, void *data) {
	const char *wanted = NULL;
	for (int i = 0; uris[i]; i++) {
		const char *id = place_in_uri(uris[i]);
		if (id && ws_place_find(id)) {
			wanted = id;
		}
	}
	bool fresh = g.win == NULL;
	if (wanted && !fresh) {
		show_place(ws_place_find(wanted));
	} else if (wanted) {
		g.place_id = g_strdup(wanted);
	}
	ensure_window();
	c8ui_window_present(g.win);
}

static void shutdown(struct c8ui_app *app, void *data) {
	if (g.timer) {
		g_source_remove(g.timer);
	}
	if (g.tile_timer) {
		g_source_remove(g.tile_timer);
		tile_now(NULL);
	}
	c8ui_charms_destroy(g.charms);
}

int main(int argc, char **argv) {
	static const struct c8ui_app_info info = {
		.id = APP_ID,
		.startup = startup,
		.open = open,
		.shutdown = shutdown,
	};
	return c8ui_app_main(&info, argc, argv);
}
