/*
 * c8-news: a feed reader after Windows 8's News. A panorama that opens on
 * the top story under its picture, edge to edge, then a section per place
 * (Latest, then each feed) of headline tiles: a wide one with its picture,
 * squares in red or black with the headline in capitals, the source and a
 * line of the story. A section's header opens all of its stories; a story
 * opens in columns. The nav bar along the top goes between Top stories and
 * Sources (every feed as its picture, and Add a source); the app bar does
 * things to a story or the feeds. The Search charm looks through every
 * story, the Settings charm has Options and Feeds. The live tile is
 * tile.c's job; c8-news-tile keeps it fresh while this isn't open.
 */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <glib.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <c8ui/c8ui.h>
#include <c8ui/c8ui-charms.h>
#include <c8ui/c8ui-wayland.h>
#include "news.h"

#ifndef NEWS_GLYPHS
#define NEWS_GLYPHS "/usr/local/share/c8-news"
#endif

#define CELL 220 // a square tile; the list puts 10 between them
#define CELL_GAP 10
#define SECTION_W (2 * CELL + CELL_GAP)
#define HEAD_H 64 // a section's two-line header
#define SOURCE_W 132 // a source on the Sources page, and its name under it
#define SOURCE_H 168
#define PAGE_LEFT 120 // where a page's content starts, as Metro pages do
#define LATEST_MAX 30
/* Narrow (snapped to a quarter): one column, as on a phone */
#define NARROW_PAD 20
#define NARROW_FITS 6 // cells a section shows: the big one and four
#define NARROW_HERO_H 400
#define TILE_DELAY_S 3

/* Article text in a serif, as News set it in Cambria */
#define SERIF "Source Serif Pro, Cambria, Georgia, serif"

#define BACKGROUND 0xf2f2f2
#define RED_TOP 0xd2141d
#define RED_BOTTOM 0x8d0a10
#define DARK_TOP 0x3a3a3a
#define DARK_BOTTOM 0x0e0e0e
#define BAR 0x260710 // the nav bar
#define BAR_TILE 0x641526

/* Stories in a hub section or a page of their own */
struct section {
	struct feed *feed; // NULL: Latest
	char *name; // the header it was made with
	GPtrArray *items; // struct story, not owned
	struct c8ui_widget *box, *list, *status;
	bool page; // all of them, else what fits in the hub
	bool wide; // items[0] is drawn big, across two cells, with its picture
	int fits; // hub: how many cells there's room for
};

/* What the app bar acts on: a story, or only a feed */
struct target {
	char *link, *id, *feed_url;
};

static struct {
	struct c8ui_app *app;
	struct c8ui_window *win;
	struct c8ui_root *root;
	struct c8ui_widget *stack, *main, *hero;
	struct c8ui_kept *hero_kept; // the top story as drawn (c8ui_kept_draw)
	struct c8ui_widget *article, *sources, *sources_list;
	struct c8ui_widget *appbar, *navbar;
	struct c8ui_widget *cmd_open, *cmd_copy, *cmd_read, *cmd_unread, *cmd_unfollow;
	struct c8ui_widget *cmd_refresh, *cmd_add, *cmd_all_read;
	struct c8ui_widget *article_image;
	char *article_image_url;
	GPtrArray *sections;
	struct target target;
	struct c8ui_charms *charms;
	struct c8ui_widget *dialog, *add_entry;
	guint timer, tile_timer;
	int64_t last_refresh;
	char *article_feed, *article_id; // the story being read
} g;

enum { PLACE_TOP, PLACE_SOURCES };

static void rebuild_main(void);
static struct story *hero_story(void);
static void refresh_all(void);
static void open_story(struct story *s);
static void open_story_at(struct story *s, bool enter);
static void open_section_page(struct feed *feed, bool enter);
static void open_sources(bool enter);
static void cmd_add(struct c8ui_widget *w, void *data);

/* Finding things again: stories move when a feed is read again */

static struct feed *find_feed(const char *url) {
	for (guint i = 0; url && i < news_feeds->len; i++) {
		struct feed *f = news_feeds->pdata[i];
		if (strcmp(f->url, url) == 0) {
			return f;
		}
	}
	return NULL;
}

static struct story *find_story(const char *feed_url, const char *id) {
	struct feed *f = find_feed(feed_url);
	for (guint i = 0; f && id && i < f->stories->len; i++) {
		struct story *s = f->stories->pdata[i];
		if (strcmp(s->id, id) == 0) {
			return s;
		}
	}
	return NULL;
}

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

static gboolean tile_now(gpointer data) {
	g.tile_timer = 0;
	news_tile_update(APP_ID);
	news_tile_update(TILE_WIDGET_ID);
	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);
	}
}

/* Words */

/* "7 hours ago", as News put it under a headline */
static char *age_words(int64_t date) {
	if (date <= 0) {
		return g_strdup("");
	}
	int64_t d = (int64_t)time(NULL) - date;
	if (d < 60) {
		return g_strdup("just now");
	}
	if (d < 3600) {
		int m = (int)(d / 60);
		return g_strdup_printf(m == 1 ? "%d minute ago" : "%d minutes ago", m);
	}
	if (d < 86400) {
		int h = (int)(d / 3600);
		return g_strdup_printf(h == 1 ? "%d hour ago" : "%d hours ago", h);
	}
	if (d < 2 * 86400) {
		return g_strdup("yesterday");
	}
	if (d < 7 * 86400) {
		return g_strdup_printf("%d days ago", (int)(d / 86400));
	}
	GDateTime *t = g_date_time_new_from_unix_local(date);
	char *s = g_date_time_format(t, "%-d %B");
	g_date_time_unref(t);
	return s;
}

/* The site's name for the small line over a header: "lwn.net" */
static char *host_of(struct feed *f) {
	GUri *uri = g_uri_parse(f->site ? f->site : f->url, G_URI_FLAGS_NONE, NULL);
	const char *host = uri ? g_uri_get_host(uri) : NULL;
	char *s = g_strdup(host ? (g_str_has_prefix(host, "www.") ? host + 4 :
		host) : "");
	if (uri) {
		g_uri_unref(uri);
	}
	return s;
}

/* Some headlines red, the rest black, the same each time it's drawn */
static bool is_red(struct story *s) {
	return g_str_hash(s->id) % 5 < 2;
}

/* A square tile's side: narrow, two of them fill the width */
static double cell_size(void) {
	if (g.root == NULL || !c8ui_root_is_narrow(g.root)) {
		return CELL;
	}
	double c = floor((c8ui_root_width(g.root) - 2 * NARROW_PAD - CELL_GAP) / 2);
	return c > 100 ? c : 100;
}

/* The target and the app bar */

static void clear_target(void) {
	g_free(g.target.link);
	g_free(g.target.id);
	g_free(g.target.feed_url);
	memset(&g.target, 0, sizeof(g.target));
}

/* 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;
}

static bool in_article(void) {
	return g.article && top_page() == g.article;
}

static void update_bar(void) {
	if (g.appbar == NULL) {
		return;
	}
	struct story *s = find_story(g.target.feed_url, g.target.id);
	bool have = s != NULL;
	c8ui_widget_set_hidden(g.cmd_open, !have || !g.target.link);
	c8ui_widget_set_hidden(g.cmd_copy, !have || !g.target.link);
	c8ui_widget_set_hidden(g.cmd_read, !have || s->read);
	c8ui_widget_set_hidden(g.cmd_unread, !have || !s->read);
	c8ui_widget_set_hidden(g.cmd_unfollow, find_feed(g.target.feed_url) == NULL);
	/* Not while reading: there's only the one story */
	c8ui_widget_set_hidden(g.cmd_refresh, in_article());
	c8ui_widget_set_hidden(g.cmd_add, in_article());
	c8ui_widget_set_hidden(g.cmd_all_read, in_article());
	if (g.navbar) {
		c8ui_navbar_set_current(g.navbar, g.sources && page_count() == 1 &&
			top_page() == g.sources ? PLACE_SOURCES :
			page_count() == 0 ? PLACE_TOP : -1);
	}
}

static void set_target(struct story *s) {
	clear_target();
	if (s) {
		g.target.link = g_strdup(s->link);
		g.target.id = g_strdup(s->id);
		g.target.feed_url = g_strdup(s->feed->url);
	}
	update_bar();
}

static void set_target_feed(struct feed *f) {
	clear_target();
	g.target.feed_url = g_strdup(f->url);
	update_bar();
}

/* Right click or hold: both bars, as in Windows 8 */
static void show_bars(void) {
	update_bar();
	c8ui_appbar_show(g.appbar);
	c8ui_navbar_show(g.navbar);
}

static void toggle_bars(void) {
	if (c8ui_navbar_is_shown(g.navbar) || c8ui_appbar_is_shown(g.appbar)) {
		c8ui_navbar_hide(g.navbar);
		c8ui_appbar_hide(g.appbar);
	} else {
		show_bars();
	}
}

/* Drawing */

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) & 0xff) / 255.0,
		((top >> 8) & 0xff) / 255.0, (top & 0xff) / 255.0);
	cairo_pattern_add_color_stop_rgb(p, 1, ((bottom >> 16) & 0xff) / 255.0,
		((bottom >> 8) & 0xff) / 255.0, (bottom & 0xff) / 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);
}

/* Black rising from the bottom of a picture, for the words over it */
static void shade_bottom(cairo_t *cr, struct c8ui_rect r, double from,
		double alpha) {
	cairo_pattern_t *p = cairo_pattern_create_linear(0, r.y + r.height * from,
		0, r.y + r.height);
	cairo_pattern_add_color_stop_rgba(p, 0, 0, 0, 0, 0);
	cairo_pattern_add_color_stop_rgba(p, 1, 0, 0, 0, alpha);
	cairo_set_source(cr, p);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	cairo_pattern_destroy(p);
}

/* The source's picture, then its name and how old the story is, in small
 * capitals: "[■] LWN.NET  7 HOURS AGO". Returns the height. */
static double draw_source_line(cairo_t *cr, const char *family,
		struct story *s, double x, double y, double width, double size,
		uint32_t color) {
	struct c8ui_font bold = { size, C8UI_WEIGHT_BOLD };
	struct c8ui_font plain = { size, C8UI_WEIGHT_SEMIBOLD };
	double logo = size + 5, tw, th;
	const char *url = news_settings.images ? news_feed_logo(s->feed) : NULL;
	cairo_surface_t *img = url ? news_image(url) : NULL;
	if (img) {
		c8ui_set_source(cr, 0xffffff, 1);
		cairo_rectangle(cr, x, y, logo, logo);
		cairo_fill(cr);
		c8ui_draw_surface_fit(cr, img, x + 1, y + 1, logo - 2, logo - 2, 4);
		x += logo + 7;
		width -= logo + 7;
	}
	char *name = g_utf8_strup(s->feed->name, -1);
	char *age = age_words(s->date);
	char *when = g_utf8_strup(age, -1);
	c8ui_text_size(family, bold, name, width * 0.65, 1, &tw, &th);
	double ty = y + (logo - th) / 2;
	c8ui_set_source(cr, color, 1);
	c8ui_text_draw(cr, family, bold, name, x, ty, width * 0.65, 1);
	if (when[0] && width - tw - 8 > 20) {
		c8ui_set_source(cr, color, 0.8);
		c8ui_text_draw(cr, family, plain, when, x + tw + 8, ty, width - tw - 8, 1);
	}
	g_free(when);
	g_free(age);
	g_free(name);
	return img ? logo : th;
}

/* All the top story shows of a story: its drawing is kept until this
 * changes */
static char *story_key(struct story *s) {
	char *age = age_words(s->date);
	char *key = g_strdup_printf("%d %d %s\n%s\n%s\n%s\n%s\n%s\n%s", s->read,
		news_settings.images, age, s->image_url ? s->image_url : "",
		s->feed->name, s->feed->url, s->id, s->title,
		s->summary ? s->summary : "");
	g_free(age);
	return key;
}

/* A story in a tile: its picture with the headline over it, or a red or
 * black square with the headline in capitals and the start of the story.
 * The lists keep what this draws (c8ui_list_set_keep). */
static void draw_tile(cairo_t *cr, const char *family, struct story *s,
		struct c8ui_rect r, bool big, bool hovered, bool pressed) {
	double pad = big ? 20 : 14;
	double x = r.x + pad, width = r.width - 2 * pad;
	double fade = s->read ? 0.72 : 1;
	bool picture = news_settings.images && s->image_url;
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	if (picture) {
		cairo_surface_t *img = news_image(s->image_url);
		if (img) {
			c8ui_draw_surface_cover(cr, img, r.x, r.y, r.width, r.height);
		} else {
			fill_gradient(cr, r, DARK_TOP, DARK_BOTTOM);
		}
		shade_bottom(cr, r, 0.3, 0.85);
		/* From the bottom up: the source, then the headline over it */
		struct c8ui_font head = { big ? 26 : 18, C8UI_WEIGHT_SEMIBOLD };
		double tw, th, lh;
		c8ui_text_size(family, head, s->title, width, big ? 3 : 4, &tw, &th);
		struct c8ui_font small = { 10, C8UI_WEIGHT_BOLD };
		c8ui_text_size(family, small, "AG", 0, 0, &tw, &lh);
		double line = fmax(lh, 15);
		double sy = r.y + r.height - pad - line;
		c8ui_set_source(cr, 0xffffff, fade);
		c8ui_text_draw(cr, family, head, s->title, x, sy - 8 - th, width,
			big ? 3 : 4);
		draw_source_line(cr, family, s, x, sy, width, 10, 0xffffff);
	} else {
		fill_gradient(cr, r, is_red(s) ? RED_TOP : DARK_TOP,
			is_red(s) ? RED_BOTTOM : DARK_BOTTOM);
		struct c8ui_font head = { big ? 28 : 17, C8UI_WEIGHT_BOLD };
		char *caps = g_utf8_strup(s->title, -1);
		double y = r.y + pad;
		c8ui_set_source(cr, 0xffffff, fade);
		y += c8ui_text_draw(cr, family, head, caps, x, y, width, 4) + 10;
		g_free(caps);
		y += draw_source_line(cr, family, s, x, y, width, big ? 11 : 10,
			0xffffff) + 8;
		/* As much of the story as there's room for */
		struct c8ui_font serif = { big ? 15 : 12.5, C8UI_WEIGHT_NORMAL };
		double tw, lh;
		c8ui_text_size(SERIF, serif, "Ag", 0, 0, &tw, &lh);
		int lines = (int)floor((r.y + r.height - pad - y) / lh);
		if (lines > 0 && s->summary && s->summary[0]) {
			c8ui_set_source(cr, 0xffffff, 0.9 * fade);
			c8ui_text_draw(cr, SERIF, serif, s->summary, x, y, width, lines);
		}
	}
	if (pressed || hovered) {
		c8ui_set_source(cr, pressed ? 0x000000 : 0xffffff, pressed ? 0.2 : 0.1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
	}
	cairo_restore(cr);
}

/* The dotted ring round what the keyboard is on */
static void focus_ring(cairo_t *cr, struct c8ui_rect r, uint32_t color) {
	double dash = 1;
	c8ui_set_source(cr, color, 1);
	cairo_set_line_width(cr, 1);
	cairo_set_dash(cr, &dash, 1, 0);
	cairo_rectangle(cr, r.x + 0.5, r.y + 0.5, r.width - 1, r.height - 1);
	cairo_stroke(cr);
	cairo_set_dash(cr, NULL, 0, 0);
}

/* A section's header: the small line, then the place in capitals with an
 * arrow when it opens a page of its own ("NEWS / LATEST ▸") */

struct head {
	char *kicker, *title;
	struct section *sec; // opens its page; NULL: just words
};

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

static void head_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct head *h = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	const char *family = c8ui_widget_font(w);
	struct c8ui_font kicker = { 11, C8UI_WEIGHT_BOLD };
	struct c8ui_font title = { 17, C8UI_WEIGHT_BOLD };
	double tw, th, kh;
	c8ui_text_size(family, kicker, h->kicker, w->rect.width, 1, &tw, &kh);
	c8ui_set_source(cr, c.fg, 0.8);
	c8ui_text_draw(cr, family, kicker, h->kicker, w->rect.x, w->rect.y + 14,
		w->rect.width, 1);
	double y = w->rect.y + 14 + kh;
	double alpha = h->sec && w->pressed ? 0.6 : 1;
	c8ui_text_size(family, title, h->title, w->rect.width - 20, 1, &tw, &th);
	c8ui_set_source(cr, h->sec && w->hovered ? c.accent : c.fg, alpha);
	c8ui_text_draw(cr, family, title, h->title, w->rect.x, y,
		w->rect.width - 20, 1);
	if (h->sec) {
		/* The small triangle after it */
		double ax = w->rect.x + tw + 8, ay = y + th / 2;
		cairo_move_to(cr, ax, ay - 4);
		cairo_line_to(cr, ax + 5, ay);
		cairo_line_to(cr, ax, ay + 4);
		cairo_close_path(cr);
		cairo_fill(cr);
	}
	if (c8ui_widget_shows_focus(w)) {
		focus_ring(cr, (struct c8ui_rect){ w->rect.x - 4, y - 2, tw + 22, th + 4 },
			c.fg);
	}
}

static bool head_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct head *h = w->data;
	if (h->sec == NULL) {
		return false;
	}
	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_section_page(h->sec->feed, 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_section_page(h->sec->feed, true);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void head_destroy(struct c8ui_widget *w) {
	struct head *h = w->data;
	g_free(h->kicker);
	g_free(h->title);
	g_free(h);
}

static const struct c8ui_widget_impl head_impl = {
	.name = "news-head",
	.measure = head_measure,
	.draw = head_draw,
	.event = head_event,
	.destroy = head_destroy,
};

static struct c8ui_widget *head_new(struct feed *feed, struct section *sec) {
	struct head *h = g_new0(struct head, 1);
	char *kicker = feed ? host_of(feed) : g_strdup("News");
	h->kicker = g_utf8_strup(kicker, -1);
	g_free(kicker);
	h->title = g_utf8_strup(feed ? feed->name : "Latest", -1);
	h->sec = sec;
	struct c8ui_widget *w = c8ui_widget_new(&head_impl, h);
	w->fill = true;
	if (sec) {
		w->cursor = C8UI_CURSOR_POINTER;
		w->focusable = true;
	}
	return w;
}

/* The sections */

static void redraw_all(void) {
	for (guint i = 0; g.sections && i < g.sections->len; i++) {
		c8ui_list_redraw(((struct section *)g.sections->pdata[i])->list);
	}
	if (g.hero) {
		c8ui_widget_queue_draw(g.hero);
	}
	if (g.sources_list) {
		c8ui_list_redraw(g.sources_list);
	}
}

/* How many the list shows: in the hub, what fits */
static void section_count(struct section *sec) {
	int n = (int)sec->items->len;
	if (!sec->page && sec->fits > 0) {
		int cells = sec->fits - (sec->wide ? 1 : 0);
		n = n < cells ? n : cells;
	}
	c8ui_list_set_count(sec->list, n);
}

static void section_fill(struct section *sec) {
	g_ptr_array_set_size(sec->items, 0);
	if (sec->feed) {
		for (guint i = 0; i < sec->feed->stories->len; i++) {
			g_ptr_array_add(sec->items, sec->feed->stories->pdata[i]);
		}
	} else {
		GPtrArray *latest = news_latest(sec->page ? 0 : LATEST_MAX);
		/* The top story is right beside it already */
		struct story *top = sec->page ? NULL : hero_story();
		for (guint i = 0; i < latest->len; i++) {
			if (latest->pdata[i] != top) {
				g_ptr_array_add(sec->items, latest->pdata[i]);
			}
		}
		g_ptr_array_unref(latest);
	}
	/* The newest one with a picture leads, big */
	sec->wide = false;
	for (guint i = 0; news_settings.images && i < sec->items->len && i < 6; i++) {
		struct story *s = sec->items->pdata[i];
		if (s->image_url) {
			g_ptr_array_steal_index(sec->items, i);
			g_ptr_array_insert(sec->items, 0, s);
			sec->wide = true;
			break;
		}
	}
	section_count(sec);
	const char *say = NULL;
	if (sec->items->len == 0) {
		if (sec->feed && sec->feed->loading) {
			say = "Loading…";
		} else if (sec->feed && sec->feed->failed) {
			say = sec->feed->error ? sec->feed->error : "Couldn't read it";
		} else if (sec->feed == NULL && news_feeds->len > 0) {
			say = "Loading…";
		} else {
			say = "No stories";
		}
	}
	if (say) {
		c8ui_label_set_text(sec->status, say);
	}
	c8ui_widget_set_hidden(sec->status, say == NULL);
	c8ui_list_redraw(sec->list);
}

static void story_spans(struct c8ui_widget *list, int index, int *cols,
		int *rows, void *data) {
	struct section *sec = data;
	*cols = *rows = 1;
	if (index == 0 && sec->wide) {
		*cols = 2;
		*rows = sec->page ? 2 : 1;
	}
}

static void draw_story(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	struct section *sec = data;
	if (item->index >= (int)sec->items->len) {
		return;
	}
	news_image_missed = false;
	draw_tile(cr, c8ui_widget_font(list), sec->items->pdata[item->index],
		item->rect, item->index == 0 && sec->wide && sec->page, item->hovered,
		item->pressed);
	if (news_image_missed) {
		c8ui_list_not_final(list); // drawn again when it's here
	}
}

static void story_opened(struct c8ui_widget *list, int index, void *data) {
	struct section *sec = data;
	if (index >= 0 && index < (int)sec->items->len) {
		open_story(sec->items->pdata[index]);
	}
}

static void story_selected(struct c8ui_widget *list, void *data) {
	struct section *sec = data;
	int i = c8ui_list_get_selected(list);
	if (i >= 0 && i < (int)sec->items->len) {
		set_target(sec->items->pdata[i]);
	}
}

static void story_context(struct c8ui_widget *list, int index, double x,
		double y, void *data) {
	struct section *sec = data;
	if (index >= 0 && index < (int)sec->items->len) {
		c8ui_list_select(list, index);
		set_target(sec->items->pdata[index]);
	} else {
		clear_target();
	}
	show_bars();
}

static void section_destroyed(struct c8ui_widget *w, void *data) {
	struct section *sec = data;
	if (g.sections) {
		g_ptr_array_remove(g.sections, sec);
	}
	g_ptr_array_unref(sec->items);
	g_free(sec->name);
	g_free(sec);
}

/* Takes the sections inside w out of the refreshing before it goes: it may
 * only be freed after this event */
static void forget_sections(struct c8ui_widget *w) {
	for (guint i = 0; g.sections && i < g.sections->len;) {
		struct section *sec = g.sections->pdata[i];
		bool inside = false;
		for (struct c8ui_widget *p = sec->box; p; p = p->parent) {
			inside |= p == w;
		}
		if (inside) {
			g_ptr_array_remove_index(g.sections, i);
		} else {
			i++;
		}
	}
}

static struct section *section_make(struct feed *feed, bool page) {
	struct section *sec = g_new0(struct section, 1);
	sec->feed = feed;
	sec->name = g_strdup(feed ? feed->name : "");
	sec->items = g_ptr_array_new();
	sec->page = page;
	g_ptr_array_add(g.sections, sec);
	sec->status = c8ui_label_new("", C8UI_TEXT_BODY);
	c8ui_label_set_color(sec->status, C8UI_COLOR_SECONDARY);
	double cell = cell_size();
	sec->list = c8ui_list_new(C8UI_LIST_SPANS, cell, cell, draw_story, sec);
	/* Photos, shades and words: drawn once, copied while the hub pans */
	c8ui_list_set_keep(sec->list, true);
	c8ui_list_set_spans(sec->list, story_spans, sec);
	c8ui_list_set_click_opens(sec->list, true);
	c8ui_list_on_open(sec->list, story_opened, sec);
	c8ui_list_on_select(sec->list, story_selected, sec);
	c8ui_list_on_context(sec->list, story_context, sec);
	return sec;
}

/* A hub section: the header, then two columns of tiles, as many rows as
 * the height has room for; the rest are on its page */

/* Narrow, in the hub's column, it shows a few (its page has the rest)
 * and is as tall as they are */
static double hubsec_status_h(struct section *sec, double width) {
	if (sec->status->hidden) {
		return 0;
	}
	double sw, sh;
	c8ui_widget_measure(sec->status, width, &sw, &sh);
	return sh + 8;
}

static void hubsec_fits(struct section *sec, int fits) {
	if (fits != sec->fits) {
		sec->fits = fits;
		section_count(sec);
	}
}

static void hubsec_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct section *sec = w->data;
	*width = avail;
	*height = 0;
	if (w->narrow) {
		hubsec_fits(sec, NARROW_FITS);
		double lw, lh;
		c8ui_widget_measure(sec->list, avail, &lw, &lh);
		*height = HEAD_H + 6 + hubsec_status_h(sec, avail) + lh;
	}
}

static void hubsec_layout(struct c8ui_widget *w) {
	struct section *sec = w->data;
	struct c8ui_rect r = w->rect;
	struct c8ui_widget *head = w->children[0];
	c8ui_widget_layout(head, (struct c8ui_rect){ r.x, r.y, r.width, HEAD_H });
	double y = r.y + HEAD_H + 6;
	double sh = hubsec_status_h(sec, r.width);
	if (sh > 0) {
		c8ui_widget_layout(sec->status, (struct c8ui_rect){ r.x, y, r.width,
			sh - 8 });
		y += sh;
	}
	if (w->narrow) {
		hubsec_fits(sec, NARROW_FITS);
	} else {
		int rows = (int)floor((r.y + r.height - y + CELL_GAP) /
			(CELL + CELL_GAP));
		hubsec_fits(sec, 2 * (rows > 1 ? rows : 1));
	}
	c8ui_widget_layout(sec->list, (struct c8ui_rect){ r.x, y, r.width,
		r.y + r.height - y });
}

static const struct c8ui_widget_impl hubsec_impl = {
	.name = "news-section",
	.measure = hubsec_measure,
	.layout = hubsec_layout,
};

static struct c8ui_widget *hub_section_new(struct feed *feed) {
	struct section *sec = section_make(feed, false);
	struct c8ui_widget *box = c8ui_widget_new(&hubsec_impl, sec);
	box->user_data = sec;
	box->on_destroy = section_destroyed;
	sec->box = box;
	c8ui_widget_add(box, head_new(feed, sec));
	c8ui_widget_add(box, sec->status);
	c8ui_widget_add(box, sec->list);
	section_fill(sec);
	return box;
}

/* The top story: the picture of the newest one that has one, edge to edge,
 * with its headline across it in big capitals */

struct hero {
	char *feed_url, *id;
};

static struct story *hero_story(void) {
	struct hero *h = g.hero ? g.hero->data : NULL;
	return h ? find_story(h->feed_url, h->id) : NULL;
}

static void hero_pick(void) {
	if (g.hero == NULL) {
		return;
	}
	struct hero *h = g.hero->data;
	GPtrArray *latest = news_latest(LATEST_MAX);
	struct story *best = NULL;
	/* An unread one with a picture, else any with one, else the newest */
	for (int pass = 0; pass < 2 && best == NULL; pass++) {
		for (guint i = 0; i < latest->len && news_settings.images; i++) {
			struct story *s = latest->pdata[i];
			if (s->image_url && (pass == 1 || !s->read)) {
				best = s;
				break;
			}
		}
	}
	if (best == NULL && latest->len) {
		best = latest->pdata[0];
	}
	g_ptr_array_unref(latest);
	/* The same one while it's still there, so it doesn't jump about */
	if (find_story(h->feed_url, h->id) && best) {
		struct story *now = find_story(h->feed_url, h->id);
		if (now->image_url || !best->image_url) {
			c8ui_widget_queue_draw(g.hero);
			return;
		}
	}
	g_free(h->feed_url);
	g_free(h->id);
	h->feed_url = best ? g_strdup(best->feed->url) : NULL;
	h->id = best ? g_strdup(best->id) : NULL;
	c8ui_widget_queue_draw(g.hero);
}

/* Wide, the hub gives it its whole height; narrow, a card on top */
static void hero_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = w->narrow ? NARROW_HERO_H : 0;
}

static bool hero_paint(cairo_t *cr, struct c8ui_rect r, void *data);

static void hero_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct c8ui_rect r = w->rect;
	struct story *s = hero_story();
	char *about = s ? story_key(s) : g_strdup_printf("none %u",
		news_feeds->len);
	char *key = g_strdup_printf("hero %d %s %s", w->narrow, c8ui_widget_font(w),
		about);
	g_free(about);
	c8ui_kept_draw(&g.hero_kept, cr, r, g_str_hash(key), hero_paint, w);
	g_free(key);
	if (w->pressed) {
		c8ui_set_source(cr, 0x000000, 0.15);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
	}
	if (c8ui_widget_shows_focus(w)) {
		focus_ring(cr, (struct c8ui_rect){ r.x + 4, r.y + 4, r.width - 8,
			r.height - 8 }, 0xffffff);
	}
}

/* false: a picture in it is still coming, so it isn't kept */
static bool hero_paint(cairo_t *cr, struct c8ui_rect r, void *data) {
	struct c8ui_widget *w = data;
	const char *family = c8ui_widget_font(w);
	struct story *s = hero_story();
	news_image_missed = false;
	cairo_surface_t *img = s && s->image_url && news_settings.images ?
		news_image_large(s->image_url) : NULL;
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	if (img) {
		c8ui_draw_surface_cover(cr, img, r.x, r.y, r.width, r.height);
		shade_bottom(cr, r, 0.25, 0.9);
		/* And from the left, under the words */
		cairo_pattern_t *p = cairo_pattern_create_linear(r.x, 0,
			r.x + r.width * 0.7, 0);
		cairo_pattern_add_color_stop_rgba(p, 0, 0, 0, 0, 0.45);
		cairo_pattern_add_color_stop_rgba(p, 1, 0, 0, 0, 0);
		cairo_set_source(cr, p);
		cairo_paint(cr);
		cairo_pattern_destroy(p);
	} else {
		fill_gradient(cr, r, RED_TOP, RED_BOTTOM);
	}

	bool narrow = w->narrow;
	double x = narrow ? r.x + NARROW_PAD : r.x + PAGE_LEFT * 0.75;
	double width = narrow ? r.width - 2 * NARROW_PAD :
		fmin(r.width * 0.6, 760);
	struct c8ui_font kicker = { 12, C8UI_WEIGHT_BOLD };
	struct c8ui_font label = { 18, C8UI_WEIGHT_BOLD };
	double tw, kh, lh;
	c8ui_text_size(family, kicker, "NEWS", 0, 0, &tw, &kh);
	c8ui_set_source(cr, 0xffffff, 0.9);
	c8ui_text_draw(cr, family, kicker, "NEWS", x, r.y + 40, 0, 0);
	c8ui_set_source(cr, 0xffffff, 1);
	c8ui_text_size(family, label, "TOP STORY", 0, 0, &tw, &lh);
	c8ui_text_draw(cr, family, label, "TOP STORY", x, r.y + 40 + kh, 0, 0);

	if (s == NULL) {
		struct c8ui_font big = { narrow ? 30 : 44, C8UI_WEIGHT_BOLD };
		c8ui_text_draw(cr, family, big, news_feeds->len ? "LOADING…" :
			"NOTHING YET", x, r.y + r.height - 160, width, 1);
		cairo_restore(cr);
		return true;
	}
	/* From the bottom up: the story's start, the source, the headline and
	 * the white rule over it */
	double big_size = narrow ? 28 : r.height > 700 ? 50 : 40;
	struct c8ui_font head = { big_size, C8UI_WEIGHT_BOLD };
	struct c8ui_font serif = { 15, C8UI_WEIGHT_NORMAL };
	char *caps = g_utf8_strup(s->title, -1);
	double hh, sh = 0;
	c8ui_text_size(family, head, caps, width, 3, &tw, &hh);
	if (s->summary && s->summary[0]) {
		c8ui_text_size(SERIF, serif, s->summary, fmin(width, 460), 3, &tw, &sh);
	}
	double y = r.y + r.height - 70 - sh;
	if (sh > 0) {
		c8ui_set_source(cr, 0xffffff, 0.92);
		c8ui_text_draw(cr, SERIF, serif, s->summary, x, y, fmin(width, 460), 3);
	}
	y -= 15 + 18;
	draw_source_line(cr, family, s, x, y, width, 11, 0xffffff);
	y -= 14 + hh;
	c8ui_set_source(cr, 0xffffff, 1);
	c8ui_text_draw(cr, family, head, caps, x, y, width, 3);
	g_free(caps);
	cairo_rectangle(cr, x, y - 22, 150, 5);
	cairo_fill(cr);
	cairo_restore(cr);
	return !news_image_missed;
}

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

static void hero_destroy(struct c8ui_widget *w) {
	struct hero *h = w->data;
	if (g.hero == w) {
		g.hero = NULL;
	}
	c8ui_kept_drop(&g.hero_kept);
	g_free(h->feed_url);
	g_free(h->id);
	g_free(h);
}

static const struct c8ui_widget_impl hero_impl = {
	.name = "news-hero",
	.measure = hero_measure,
	.draw = hero_draw,
	.event = hero_event,
	.destroy = hero_destroy,
};

/* Starting out: nothing followed yet */

static const struct {
	const char *name, *url;
} suggestions[] = {
	{ "LWN.net", "https://lwn.net/headlines/rss" },
	{ "Hacker News", "https://hnrss.org/frontpage" },
	{ "BBC News", "https://feeds.bbci.co.uk/news/rss.xml" },
	{ "NPR News", "https://feeds.npr.org/1001/rss.xml" },
	{ "Ars Technica", "https://feeds.arstechnica.com/arstechnica/index" },
	{ "Phoronix", "https://www.phoronix.com/rss.php" },
	{ "Slashdot", "http://rss.slashdot.org/Slashdot/slashdotMain" },
};

static void follow(const char *url, const char *name) {
	struct feed *f = news_add_feed(url, name);
	if (f == NULL) {
		return;
	}
	feed_load_cache(f);
	rebuild_main();
	refresh_all();
	if (g.charms) {
		c8ui_charms_changed(g.charms, "feeds");
	}
}

static void suggestion_clicked(struct c8ui_widget *w, void *data) {
	size_t i = (size_t)data;
	follow(suggestions[i].url, suggestions[i].name);
}

static struct c8ui_widget *welcome_new(void) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 20);
	box->fill = true;
	box->expand = true;
	c8ui_box_set_padding(box, PAGE_LEFT, 44, 80, 40);
	c8ui_box_set_narrow_padding(box, NARROW_PAD, 30, NARROW_PAD, 30);
	c8ui_widget_add(box, c8ui_label_new("News", C8UI_TEXT_HEADER));
	struct c8ui_widget *p = c8ui_label_new("Follow the sites you like and "
		"their stories come together here. Pick a few to start, or add your "
		"own from the app bar (right-click, or the Menu key) with the address "
		"of a site or its feed.", C8UI_TEXT_ITEM);
	p->max_width = 640;
	c8ui_widget_add(box, p);
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_box_set_wrap(row, true);
	row->max_width = 760;
	for (size_t i = 0; i < G_N_ELEMENTS(suggestions); i++) {
		c8ui_widget_add(row, c8ui_button_new(suggestions[i].name,
			suggestion_clicked, (void *)i));
	}
	c8ui_widget_add(box, row);
	return box;
}

/* Pages over the panorama */

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

static void pop_page(void) {
	struct c8ui_widget *top = top_page();
	if (top == NULL) {
		return;
	}
	forget_sections(top);
	c8ui_stack_pop(g.stack, true);
	update_bar();
	redraw_all(); // what was read shows as read
}

static void pop_all(void) {
	struct c8ui_widget *top;
	while ((top = top_page())) {
		forget_sections(top);
		c8ui_widget_destroy(top);
	}
}

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

/* The back button and a header beside it */
static struct c8ui_widget *page_top(struct c8ui_widget *head) {
	struct c8ui_widget *top = c8ui_box_new(C8UI_HORIZONTAL, 24);
	c8ui_box_set_narrow_spacing(top, 12);
	c8ui_box_set_padding(top, 40, 30, 40, 0);
	c8ui_box_set_narrow_padding(top, 12, 20, NARROW_PAD, 0);
	struct c8ui_widget *back = c8ui_back_button_new(go_back, NULL);
	back->align = C8UI_ALIGN_END;
	c8ui_widget_add(top, back);
	head->expand = true;
	c8ui_widget_add(top, head);
	return top;
}

/* Every story of a feed (or the latest of all), as tiles */
static void open_section_page(struct feed *feed, bool enter) {
	struct section *sec = section_make(feed, true);
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 8);
	page->fill = true;
	page->expand = true;
	page->user_data = sec;
	page->on_destroy = section_destroyed;
	sec->box = page;
	c8ui_widget_add(page, page_top(head_new(feed, NULL)));
	struct c8ui_widget *body = c8ui_box_new(C8UI_VERTICAL, 8);
	body->fill = true;
	c8ui_box_set_padding(body, PAGE_LEFT, 10, 40, 40);
	c8ui_box_set_narrow_padding(body, NARROW_PAD, 10, NARROW_PAD, 40);
	c8ui_widget_add(body, sec->status);
	sec->list->fill = true;
	c8ui_widget_add(body, sec->list);
	struct c8ui_widget *scroll = c8ui_scroll_new(body);
	scroll->fill = true;
	scroll->expand = true;
	c8ui_widget_add(page, scroll);
	section_fill(sec);
	push_page(page, enter);
}

/* Sources: every feed by its picture, and a tile to add one */

static void draw_source(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	struct c8ui_rect r = item->rect;
	const char *family = c8ui_widget_font(list);
	double side = r.width;
	struct c8ui_rect box = { r.x, r.y, side, side };
	if (item->index >= (int)news_feeds->len) {
		/* Add a source: a grey square and a plus in a ring */
		c8ui_set_source(cr, 0x000000, item->hovered ? 0.16 : 0.1);
		cairo_rectangle(cr, box.x, box.y, side, side);
		cairo_fill(cr);
		double cx = box.x + side / 2, cy = box.y + side / 2;
		c8ui_set_source(cr, item->fg, 0.7);
		cairo_set_line_width(cr, 2);
		cairo_arc(cr, cx, cy, 18, 0, 2 * M_PI);
		cairo_stroke(cr);
		cairo_move_to(cr, cx - 8, cy);
		cairo_line_to(cr, cx + 8, cy);
		cairo_move_to(cr, cx, cy - 8);
		cairo_line_to(cr, cx, cy + 8);
		cairo_stroke(cr);
		c8ui_set_source(cr, item->fg, 1);
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_CAPTION),
			"Add a source", r.x, r.y + side + 8, r.width, 2);
		return;
	}
	struct feed *f = news_feeds->pdata[item->index];
	const char *url = news_settings.images ? news_feed_logo(f) : NULL;
	cairo_surface_t *img = url ? news_image(url) : NULL;
	if (img) {
		c8ui_set_source(cr, 0xffffff, 1);
		cairo_rectangle(cr, box.x, box.y, side, side);
		cairo_fill(cr);
		c8ui_draw_surface_fit(cr, img, box.x + 16, box.y + 16, side - 32, side - 32, 4);
	} else {
		/* No picture: its first letter on red */
		fill_gradient(cr, box, RED_TOP, RED_BOTTOM);
		char first[8] = { 0 };
		const char *end = g_utf8_next_char(f->name);
		memcpy(first, f->name, MIN((size_t)(end - f->name), sizeof(first) - 1));
		char *up = g_utf8_strup(first, -1);
		struct c8ui_font big = { 56, C8UI_WEIGHT_BOLD };
		double tw, th;
		c8ui_text_size(family, big, up, 0, 0, &tw, &th);
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_text_draw(cr, family, big, up, box.x + (side - tw) / 2,
			box.y + (side - th) / 2, 0, 0);
		g_free(up);
	}
	if (item->hovered || item->pressed) {
		c8ui_set_source(cr, 0x000000, item->pressed ? 0.2 : 0.08);
		cairo_rectangle(cr, box.x, box.y, side, side);
		cairo_fill(cr);
	}
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_CAPTION), f->name,
		r.x, r.y + side + 8, r.width, 2);
}

static void source_opened(struct c8ui_widget *list, int index, void *data) {
	if (index >= 0 && index < (int)news_feeds->len) {
		open_section_page(news_feeds->pdata[index], true);
	} else if (index == (int)news_feeds->len) {
		cmd_add(NULL, NULL);
	}
}

static void source_context(struct c8ui_widget *list, int index, double x,
		double y, void *data) {
	if (index >= 0 && index < (int)news_feeds->len) {
		c8ui_list_select(list, index);
		set_target_feed(news_feeds->pdata[index]);
	} else {
		clear_target();
	}
	show_bars();
}

static void open_sources(bool enter) {
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 8);
	page->fill = true;
	page->expand = true;
	c8ui_widget_track(page, &g.sources);
	struct c8ui_widget *head = head_new(NULL, NULL);
	struct head *h = head->data;
	g_free(h->title);
	h->title = g_strdup("SOURCES");
	c8ui_widget_add(page, page_top(head));
	c8ui_widget_track(c8ui_list_new(C8UI_LIST_GRID, SOURCE_W, SOURCE_H,
		draw_source, NULL), &g.sources_list);
	c8ui_list_set_click_opens(g.sources_list, true);
	c8ui_list_on_open(g.sources_list, source_opened, NULL);
	c8ui_list_on_context(g.sources_list, source_context, NULL);
	c8ui_list_set_count(g.sources_list, (int)news_feeds->len + 1);
	struct c8ui_widget *body = c8ui_box_new(C8UI_VERTICAL, 0);
	body->fill = true;
	c8ui_box_set_padding(body, PAGE_LEFT, 10, 40, 40);
	c8ui_box_set_narrow_padding(body, NARROW_PAD, 10, NARROW_PAD, 40);
	g.sources_list->fill = true;
	c8ui_widget_add(body, g.sources_list);
	struct c8ui_widget *scroll = c8ui_scroll_new(body);
	scroll->fill = true;
	scroll->expand = true;
	c8ui_widget_add(page, scroll);
	push_page(page, enter);
}

/* The panorama or the welcome, as the child of the stack that comes first.
 * The pages go with it (their feeds may have); Sources comes back. */

static void rebuild_main(void) {
	if (g.stack == NULL) {
		return;
	}
	bool sources = g.sources != NULL;
	pop_all();
	if (g.main) {
		forget_sections(g.main);
		c8ui_widget_destroy(g.main);
		g.main = NULL;
	}
	g.hero = NULL;
	clear_target();
	if (news_feeds->len == 0) {
		g.main = welcome_new();
	} else {
		g.hero = c8ui_widget_new(&hero_impl, g_new0(struct hero, 1));
		g.hero->cursor = C8UI_CURSOR_POINTER;
		g.hero->focusable = true;
		hero_pick();
	}
	if (g.hero) {
		/* Narrow, the top story over the sections going down */
		g.main = c8ui_hub_new(NULL);
		c8ui_hub_set_narrow_column(g.main, true);
		c8ui_hub_add_full(g.main, g.hero, 0);
		c8ui_hub_add(g.main, NULL, hub_section_new(NULL), SECTION_W);
		for (guint i = 0; i < news_feeds->len; i++) {
			struct feed *f = news_feeds->pdata[i];
			c8ui_hub_add(g.main, NULL, hub_section_new(f), SECTION_W);
		}
	}
	c8ui_widget_insert(g.stack, 0, g.main);
	c8ui_stack_set(g.stack, 0, false);
	if (g.hero) {
		/* The keys page the panorama straight away */
		c8ui_widget_grab_focus(g.hero);
	}
	if (sources) {
		open_sources(false);
	}
	update_bar();
}

static void nav_chosen(struct c8ui_widget *bar, int index, void *data) {
	c8ui_appbar_hide(g.appbar);
	if (index == PLACE_TOP) {
		if (page_count()) {
			pop_all();
			c8ui_stack_set(g.stack, 0, true);
		}
	} else if (index == PLACE_SOURCES) {
		if (!(g.sources && page_count() == 1)) {
			pop_all();
			open_sources(true);
		}
	}
	update_bar();
}

/* Reading */

static void article_gone(struct c8ui_widget *w, void *data) {
	if (g.article != w) {
		return;
	}
	g.article = NULL;
	g_clear_pointer(&g.article_feed, g_free);
	g_clear_pointer(&g.article_id, g_free);
	g.article_image = NULL;
	g_clear_pointer(&g.article_image_url, g_free);
}

static void read_original(struct c8ui_widget *w, void *data) {
	c8ui_window_open_uri(g.win, data);
}

static double body_size(void) {
	static const double sizes[] = { 15, 17, 20 };
	return sizes[news_settings.text_size];
}

/* The top of an article: headline, byline, date and picture (height 0:
 * its own shape, else cropped to fill) */
static void article_lead(struct c8ui_widget *box, struct story *s,
		double headline_size, double img_w, double img_h) {
	char *title = g_markup_printf_escaped("<span font_weight=\"bold\">%s</span>",
		s->title);
	struct c8ui_widget *headline = c8ui_rich_new(title);
	c8ui_rich_set_font(headline, NULL, headline_size);
	g_free(title);
	c8ui_widget_add(box, headline);
	char *by = s->author && s->author[0] ?
		g_strdup_printf("By %s, %s", s->author, s->feed->name) :
		g_strdup(s->feed->name);
	c8ui_widget_add(box, c8ui_label_new(by, C8UI_TEXT_BODY_STRONG));
	g_free(by);
	if (s->date > 0) {
		GDateTime *t = g_date_time_new_from_unix_local(s->date);
		char *when = g_date_time_format(t, "%A, %-d %B %Y, %H:%M");
		struct c8ui_widget *date = c8ui_label_new(when, C8UI_TEXT_CAPTION);
		c8ui_label_set_color(date, C8UI_COLOR_SECONDARY);
		c8ui_widget_add(box, date);
		g_free(when);
		g_date_time_unref(t);
	}
	if (news_settings.images && s->image_url) {
		g.article_image = c8ui_image_new(NULL, img_w, img_h);
		if (img_h > 0) {
			c8ui_image_set_fit(g.article_image, C8UI_FIT_COVER);
		}
		g.article_image_url = g_strdup(s->image_url);
		cairo_surface_t *img = news_image_large(s->image_url);
		if (img) {
			c8ui_image_set(g.article_image, img);
		} else {
			/* Comes when downloaded: nothing to show until then */
			c8ui_widget_set_hidden(g.article_image, true);
		}
		c8ui_widget_add(box, g.article_image);
	}
}

static void open_story(struct story *s) {
	open_story_at(s, true);
}

static void open_story_at(struct story *s, bool enter) {
	news_set_read(s, true);
	set_target(s);
	tile_later();
	if (g.article) {
		/* One story at a time: reading another replaces it */
		c8ui_widget_destroy(g.article);
		g.article = NULL;
	}
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 8);
	page->fill = true;
	page->expand = true;
	page->on_destroy = article_gone;
	g.article = page;
	g.article_feed = g_strdup(s->feed->url);
	g.article_id = g_strdup(s->id);

	struct c8ui_widget *where = head_new(s->feed, NULL);
	c8ui_widget_add(page, page_top(where));
	g.article_image = NULL;
	g_clear_pointer(&g.article_image_url, g_free);

	/* A lead column (headline, byline, date, picture), then the text in
	 * columns across, in a serif; narrow, all of it one under another,
	 * the text one column, scrolled down */
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 56);
	row->fill = true;
	c8ui_box_set_padding(row, PAGE_LEFT, 16, 80, 40);
	c8ui_box_set_narrow_orientation(row, C8UI_VERTICAL);
	c8ui_box_set_narrow_spacing(row, 10);
	c8ui_box_set_narrow_padding(row, NARROW_PAD, 12, NARROW_PAD, 40);
	struct c8ui_widget *lead = c8ui_box_new(C8UI_VERTICAL, 10);
	lead->fixed_width = 440;
	article_lead(lead, s, 30, 440, 280);
	if (s->link) {
		c8ui_widget_add(lead, c8ui_link_new("Read it on the site", read_original,
			g_strdup(s->link)));
	}
	c8ui_widget_add(row, lead);

	const char *markup = news_story_markup(s);
	char *fallback = markup ? NULL : g_markup_escape_text(s->summary, -1);
	struct c8ui_widget *body = c8ui_rich_columns_new(markup ? markup :
		fallback, 380, 48);
	g_free(fallback);
	c8ui_rich_set_font(body, SERIF, body_size());
	c8ui_rich_set_line_spacing(body, 1.25);
	body->fill = true;
	c8ui_widget_add(row, body);

	struct c8ui_widget *scroll = c8ui_scroll_new(row);
	c8ui_scroll_set_directions(scroll, true, false);
	c8ui_scroll_set_narrow_directions(scroll, false, true);
	scroll->fill = true;
	scroll->expand = true;
	c8ui_widget_add(page, scroll);
	push_page(page, enter);
}

/* App bar commands */

static void cmd_open(struct c8ui_widget *w, void *data) {
	if (g.target.link) {
		c8ui_window_open_uri(g.win, g.target.link);
	}
}

static void cmd_copy(struct c8ui_widget *w, void *data) {
	if (g.target.link) {
		c8ui_root_set_clipboard(g.root, g.target.link);
	}
}

static void mark(bool read) {
	struct story *s = find_story(g.target.feed_url, g.target.id);
	if (s) {
		news_set_read(s, read);
		update_bar();
		redraw_all();
		tile_later();
	}
}

static void cmd_read(struct c8ui_widget *w, void *data) {
	mark(true);
}

static void cmd_unread(struct c8ui_widget *w, void *data) {
	mark(false);
}

static void unfollow(struct feed *f) {
	news_remove_feed(f);
	rebuild_main();
	if (g.charms) {
		c8ui_charms_changed(g.charms, "feeds");
	}
	tile_later();
}

static void cmd_unfollow(struct c8ui_widget *w, void *data) {
	struct feed *f = find_feed(g.target.feed_url);
	if (f) {
		unfollow(f);
	}
}

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

static void cmd_all_read(struct c8ui_widget *w, void *data) {
	news_mark_all_read();
	update_bar();
	redraw_all();
	tile_later();
}

/* "example.org/feed" → https://example.org/feed; feed:// links too */
static char *normalise_url(const char *text) {
	char *t = g_strstrip(g_strdup(text));
	char *url;
	if (g_str_has_prefix(t, "feed://")) {
		url = g_strconcat("https://", t + 7, NULL);
	} else if (g_str_has_prefix(t, "feed:")) {
		url = g_strdup(t + 5);
	} else if (strstr(t, "://") == NULL && t[0]) {
		url = g_strconcat("https://", t, NULL);
	} else {
		url = g_strdup(t);
	}
	g_free(t);
	return url;
}

/* Enter in the box adds */
static void add_entered(struct c8ui_widget *entry, void *data) {
	if (g.dialog) {
		c8ui_dialog_choose(g.dialog, 0);
	}
}

static void add_dialog_done(int choice, void *data) {
	const char *text = g.add_entry ? c8ui_entry_get(g.add_entry) : "";
	if (choice == 0 && text[0]) {
		char *url = normalise_url(text);
		follow(url, NULL);
		g_free(url);
	}
	g.dialog = g.add_entry = NULL;
}

static void cmd_add(struct c8ui_widget *w, void *data) {
	static const char *const buttons[] = { "Add", "Close" };
	g.dialog = c8ui_dialog_show(g.root, "Add a source",
		"Type the address of a site or of its feed.", buttons, 2,
		add_dialog_done, NULL);
	g.add_entry = c8ui_entry_new(NULL, "", add_entered, NULL);
	/* Leaving it with something typed (to press Cancel) must not add */
	c8ui_entry_set_enter_only(g.add_entry, true);
	c8ui_entry_set_placeholder(g.add_entry, "example.org");
	g.add_entry->fixed_width = 420;
	c8ui_dialog_add(g.dialog, g.add_entry);
	c8ui_widget_grab_focus(g.add_entry);
}

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 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) {
		toggle_bars();
		return true;
	}
	if (ev->sym == XKB_KEY_F5 || ((ev->mods & C8UI_MOD_CTRL) &&
			ev->base_sym == XKB_KEY_r)) {
		refresh_all();
		return true;
	}
	return false;
}

/* Refreshing */

static void feed_refreshed(struct feed *feed, bool changed, void *data) {
	if (g.win == NULL) {
		return;
	}
	for (guint i = 0; i < g.sections->len; i++) {
		struct section *sec = g.sections->pdata[i];
		/* Its own title came with the first read: the header changes */
		if (sec->feed == feed && strcmp(sec->name, feed->name) != 0) {
			rebuild_main();
			return;
		}
	}
	hero_pick(); // first: Latest leaves it out
	for (guint i = 0; i < g.sections->len; i++) {
		struct section *sec = g.sections->pdata[i];
		if (sec->feed == feed || sec->feed == NULL) {
			section_fill(sec);
		}
	}
	if (g.sources_list) {
		c8ui_list_redraw(g.sources_list);
	}
	update_bar();
	if (changed) {
		tile_later();
	}
}

static void refresh_all(void) {
	g.last_refresh = g_get_monotonic_time() / G_USEC_PER_SEC;
	rssnail_sync(); // a change of feeds comes back to remote_changed
	for (guint i = 0; i < news_feeds->len; i++) {
		struct feed *f = news_feeds->pdata[i];
		feed_refresh(f, feed_refreshed, NULL);
	}
	/* Loading… where there is nothing yet */
	for (guint i = 0; g.sections && i < g.sections->len; i++) {
		section_fill(g.sections->pdata[i]);
	}
}

/* rssnail's feeds came, went or changed (an account turned on or off in
 * PC settings, a source added), or something went wrong there */
static void remote_changed(const char *error, bool loud, void *data) {
	if (g.charms) {
		c8ui_charms_changed(g.charms, "feeds");
	}
	if (error) {
		if (loud && g.root) {
			c8ui_dialog_message(g.root, "rssnail", error);
		}
		return;
	}
	for (guint i = 0; i < news_feeds->len; i++) {
		struct feed *f = news_feeds->pdata[i];
		if (f->stories->len == 0) {
			feed_load_cache(f);
		}
	}
	rebuild_main();
	for (guint i = 0; i < news_feeds->len; i++) {
		feed_refresh(news_feeds->pdata[i], feed_refreshed, NULL);
	}
	tile_later();
}

static gboolean minute(gpointer data) {
	int64_t now = g_get_monotonic_time() / G_USEC_PER_SEC;
	if (now - g.last_refresh >= (int64_t)news_settings.interval * 60) {
		refresh_all();
	}
	/* The tiles are kept as drawn: "7 minutes ago" is 8 now */
	redraw_all();
	return G_SOURCE_CONTINUE;
}

/* Pictures */

static void image_ready(const char *url, void *data) {
	/* What was drawn while waiting for a picture wasn't kept
	 * (c8ui_list_not_final), so drawing again is enough: the tiles that
	 * were final stay as they are */
	for (guint i = 0; g.sections && i < g.sections->len; i++) {
		c8ui_widget_queue_draw(((struct section *)g.sections->pdata[i])->list);
	}
	if (g.hero) {
		c8ui_widget_queue_draw(g.hero);
	}
	if (g.sources_list) {
		c8ui_widget_queue_draw(g.sources_list);
	}
	if (g.article_image && g.article_image_url &&
			strcmp(url, g.article_image_url) == 0) {
		cairo_surface_t *s = news_image_large(url);
		if (s) {
			c8ui_image_set(g.article_image, s);
			c8ui_widget_set_hidden(g.article_image, false);
		}
	}
	tile_later();
}

/* Charms */

static void search(struct c8ui_search *s, const char *query, void *data) {
	if (query[0] == '\0') {
		return;
	}
	char *q = g_utf8_casefold(query, -1);
	GPtrArray *all = news_latest(0);
	int found = 0;
	for (guint i = 0; i < all->len && found < 20; i++) {
		struct story *st = all->pdata[i];
		char *t = g_utf8_casefold(st->title, -1);
		char *b = g_utf8_casefold(st->summary, -1);
		bool hit = strstr(t, q) || strstr(b, q);
		g_free(t);
		g_free(b);
		if (!hit) {
			continue;
		}
		char *id = g_strconcat(st->feed->url, "\n", st->id, NULL);
		char *age = news_age(st->date);
		char *sub = g_strdup_printf("%s · %s", st->feed->name, age);
		c8ui_search_add(s, id, st->title, sub, NULL);
		g_free(sub);
		g_free(age);
		g_free(id);
		found++;
	}
	g_ptr_array_unref(all);
	g_free(q);
}

static void open_result(const char *id, const char *query, void *data) {
	const char *nl = strchr(id, '\n');
	if (nl == NULL) {
		return;
	}
	char *url = g_strndup(id, nl - id);
	struct story *s = find_story(url, nl + 1);
	g_free(url);
	if (s && g.win) {
		open_story(s);
	}
}

static void option_changed(struct c8ui_setting *s, void *data) {
	const char *id = c8ui_setting_id(s);
	if (strcmp(id, "images") == 0) {
		news_settings.images = c8ui_setting_get_bool(s);
		/* Which tiles are big changes with it */
		for (guint i = 0; g.sections && i < g.sections->len; i++) {
			section_fill(g.sections->pdata[i]);
		}
		hero_pick();
		redraw_all();
		tile_later();
	} else if (strcmp(id, "size") == 0) {
		news_settings.text_size = c8ui_setting_get_int(s);
	} else if (strcmp(id, "interval") == 0) {
		news_settings.interval = (int)c8ui_setting_get_double(s);
	} else if (strcmp(id, "all_read") == 0) {
		cmd_all_read(NULL, NULL);
		return;
	} else if (strcmp(id, "refresh") == 0) {
		refresh_all();
		return;
	}
	news_save_settings();
}

static void options_page(struct c8ui_settings_page *page, void *data) {
	static const char *const sizes[] = { "Small", "Medium", "Large" };
	c8ui_page_heading(page, "Reading");
	c8ui_page_toggle(page, "images", "Show pictures", news_settings.images,
		option_changed, NULL);
	c8ui_page_buttons(page, "size", "Text size in articles", sizes, 3,
		news_settings.text_size, option_changed, NULL);
	c8ui_page_heading(page, "Updating");
	c8ui_page_slider(page, "interval", "Look for new stories every (minutes)",
		10, 180, 10, news_settings.interval, option_changed, NULL);
	c8ui_page_button(page, "refresh", "Refresh now", option_changed, NULL);
	c8ui_page_button(page, "all_read", "Mark everything as read", option_changed,
		NULL);
}

static void feed_option(struct c8ui_setting *s, void *data) {
	const char *id = c8ui_setting_id(s);
	if (strcmp(id, "add") == 0) {
		const char *text = c8ui_setting_get_text(s);
		if (text[0]) {
			char *url = normalise_url(text);
			follow(url, NULL);
			g_free(url);
		}
	} else if (g_str_has_prefix(id, "unfollow:")) {
		struct feed *f = find_feed(id + 9);
		if (f) {
			unfollow(f);
		}
	}
}

static void feeds_page(struct c8ui_settings_page *page, void *data) {
	if (news_synced) {
		c8ui_page_heading(page, "rssnail");
		c8ui_page_paragraph(page, "These are the feeds you follow on "
			"rssnail, from your account in PC settings (Online accounts). "
			"What you add, unfollow and read here changes there too.");
		if (rssnail_error()) {
			c8ui_page_paragraph(page, rssnail_error());
		}
	}
	c8ui_page_heading(page, "Following");
	if (news_feeds->len == 0) {
		c8ui_page_paragraph(page, "You follow nothing yet.");
	}
	for (guint i = 0; i < news_feeds->len; i++) {
		struct feed *f = news_feeds->pdata[i];
		char *id = g_strconcat("unfollow:", f->url, NULL);
		char *label = g_strdup_printf("Unfollow %s", f->name);
		c8ui_page_button(page, id, label, feed_option, NULL);
		g_free(label);
		g_free(id);
	}
	c8ui_page_heading(page, "Add a feed");
	struct c8ui_setting *add = c8ui_page_text(page, "add", "Address of a site "
		"or feed", "", feed_option, NULL);
	c8ui_setting_set_placeholder(add, "example.org");
}

/* The app */

static void window_gone(struct c8ui_widget *w, void *data) {
	g.win = NULL;
	g.root = NULL;
	g.stack = g.main = g.hero = g.article = g.article_image = NULL;
	g.sources = g.sources_list = NULL;
	g.appbar = g.navbar = NULL;
	g.dialog = g.add_entry = NULL;
	if (g.sections) {
		g_ptr_array_unref(g.sections);
		g.sections = NULL;
	}
	if (g.tile_timer) {
		g_source_remove(g.tile_timer);
		g.tile_timer = 0;
	}
	clear_target();
	g_clear_pointer(&g.article_image_url, g_free);
	g_clear_pointer(&g.article_feed, g_free);
	g_clear_pointer(&g.article_id, g_free);
}

static void resized(struct c8ui_root *root, double width, double height,
		void *data) {
	/* Narrow, the tiles follow the width (only their size: the
	 * widgets reflow by themselves) */
	double cell = cell_size();
	for (guint i = 0; g.sections && i < g.sections->len; i++) {
		struct section *sec = g.sections->pdata[i];
		c8ui_list_set_mode(sec->list, C8UI_LIST_SPANS, cell, cell);
	}
}

static void make_window(void) {
	g.win = c8ui_window_new(g.app, "News", 1180, 720);
	g.root = c8ui_window_root(g.win);
	g.sections = g_ptr_array_new();
	c8ui_window_set_background(g.win, BACKGROUND, 1);

	/* News was dark text on light grey, its pictures and tiles aside */
	g.stack = c8ui_stack_new();
	g.stack->fill = true;
	g.stack->on_destroy = window_gone;
	c8ui_widget_set_scheme(g.stack, C8UI_SCHEME_LIGHT);
	c8ui_widget_set_background(g.stack, BACKGROUND);
	c8ui_root_set_child(g.root, g.stack);
	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, NEWS_GLYPHS "/top-stories.svg", "Top stories");
	c8ui_navbar_add(g.navbar, NEWS_GLYPHS "/sources.svg", "Sources");

	g.appbar = c8ui_appbar_new(g.root);
	g.cmd_open = command("web-browser", "Open in browser", false,
		cmd_open);
	g.cmd_copy = command("edit-copy", "Copy link", false, cmd_copy);
	g.cmd_read = command("mail-mark-read", "Mark as read", false, cmd_read);
	g.cmd_unread = command("mail-mark-unread", "Mark as unread", false,
		cmd_unread);
	g.cmd_unfollow = command("list-remove", "Unfollow", false, cmd_unfollow);
	g.cmd_refresh = command("view-refresh", "Refresh", true, cmd_refresh);
	g.cmd_add = command("list-add", "Add a source", true, cmd_add);
	g.cmd_all_read = command("object-select", "Mark all as read", true,
		cmd_all_read);

	g.main = NULL;
	rebuild_main();
}

static void startup(struct c8ui_app *app, void *data) {
	g.app = app;
	news_load();
	rssnail_init(remote_changed, NULL, true);
	for (guint i = 0; i < news_feeds->len; i++) {
		feed_load_cache(news_feeds->pdata[i]);
	}
	news_image_on_ready(image_ready, 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);
		c8ui_charms_add_page(g.charms, "feeds", "Feeds", feeds_page, NULL);
	}
	g.timer = g_timeout_add_seconds(60, minute, NULL);
	tile_later();
}

/* Every launch: the first, and each one handed over later (a feed: link) */
static void open(struct c8ui_app *app, char **uris, void *data) {
	bool fresh = g.win == NULL;
	if (fresh) {
		make_window();
	}
	for (int i = 0; uris[i]; i++) {
		if (g_str_has_prefix(uris[i], "feed:") ||
				g_str_has_prefix(uris[i], "http://") ||
				g_str_has_prefix(uris[i], "https://")) {
			char *url = normalise_url(uris[i]);
			follow(url, NULL);
			g_free(url);
		}
	}
	if (fresh) {
		refresh_all();
	}
	c8ui_window_present(g.win);
}

static void shutdown(struct c8ui_app *app, void *data) {
	if (g.timer) {
		g_source_remove(g.timer);
	}
	news_flush();
	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);
}
