/*
 * c8-shell: Start, all apps, the charms, flyouts, switcher, launch
 * splash and notifications of the cont8nuum desktop.
 *
 * The compositor (c8) starts this program itself, over a private
 * connection, and only then offers c8_shell_v1. Run by hand it has
 * nothing to talk to and exits.
 */
#define _GNU_SOURCE
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include "shell.h"
#include "shrink.h"
#include "status.h"

struct shell shell;

/* Windows */

static void window_title(void *data, struct c8_shell_window_v1 *proto,
		const char *title) {
	struct window *w = data;
	set_str(&w->title, title);
}

static void window_app_id(void *data, struct c8_shell_window_v1 *proto,
		const char *app_id) {
	struct window *w = data;
	set_str(&w->app_id, app_id);
}

static void window_focused(void *data, struct c8_shell_window_v1 *proto,
		uint32_t focused) {
	struct window *w = data;
	w->focused = focused != 0;
	if (w->focused) {
		wl_list_remove(&w->link);
		wl_list_insert(&shell.windows, &w->link);
	}
}

static void window_pid(void *data, struct c8_shell_window_v1 *proto,
		uint32_t pid) {
	struct window *w = data;
	w->pid = pid;
}

static void window_done(void *data, struct c8_shell_window_v1 *proto) {
	start_windows_changed();
	panels_windows_changed();
}

/* What c8 draws is as big as asked; it is kept at this many times the
 * size it is shown, shrunk here once with a proper filter (c8's is
 * bilinear, fine only for a couple of times smaller) */
#define CAPTURE_W 960
#define CAPTURE_H 600

static int keep_w, keep_h;

void window_capture(struct window *w, int max_w, int max_h) {
	keep_w = max_w;
	keep_h = max_h;
	if (w->capture_fd >= 0) {
		return; // one on its way already
	}
	int fd = memfd_create("c8-shell-capture", MFD_CLOEXEC);
	if (fd < 0) {
		return;
	}
	if (ftruncate(fd, (off_t)CAPTURE_W * CAPTURE_H * 4) < 0) {
		close(fd);
		return;
	}
	w->capture_fd = fd;
	c8_shell_window_v1_capture(w->proto, ++w->capture_serial, fd, CAPTURE_W,
		CAPTURE_H);
}

static void window_captured(void *data, struct c8_shell_window_v1 *proto,
		uint32_t serial, int32_t width, int32_t height) {
	struct window *w = data;
	if (w->capture_fd < 0 || serial != w->capture_serial) {
		return;
	}
	int fd = w->capture_fd;
	w->capture_fd = -1;
	if (width <= 0 || height <= 0 || width > CAPTURE_W ||
			height > CAPTURE_H) {
		close(fd);
		return; // keep what we had, if anything
	}
	size_t size = (size_t)CAPTURE_W * CAPTURE_H * 4;
	void *map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
	close(fd);
	if (map == MAP_FAILED) {
		return;
	}
	/* c8's ARGB8888 is cairo's ARGB32: premultiplied, native words */
	cairo_surface_t *image = cairo_image_surface_create_for_data(map,
		CAIRO_FORMAT_ARGB32, width, height, width * 4);
	cairo_surface_t *small = image_shrunk(image, width, height, keep_w,
		keep_h);
	cairo_surface_destroy(image);
	munmap(map, size);
	if (w->preview) {
		cairo_surface_destroy(w->preview);
	}
	w->preview = small;
	panels_preview_ready(w);
}

static void window_closed(void *data, struct c8_shell_window_v1 *proto) {
	struct window *w = data;
	c8_shell_window_v1_destroy(w->proto);
	if (w->capture_fd >= 0) {
		close(w->capture_fd);
	}
	if (w->preview) {
		cairo_surface_destroy(w->preview);
	}
	wl_list_remove(&w->link);
	free(w->title);
	free(w->app_id);
	c8ui_icon_destroy(w->icon);
	free(w->style_icon);
	free(w);
	start_windows_changed();
	panels_windows_changed();
}

static const struct c8_shell_window_v1_listener window_listener = {
	.title = window_title,
	.app_id = window_app_id,
	.focused = window_focused,
	.done = window_done,
	.closed = window_closed,
	.pid = window_pid,
	.captured = window_captured,
};

/* The compositor */

static void handle_start_visible(void *data, struct c8_shell_v1 *proto,
		uint32_t visible) {
	/* Asked to hide with no app open, the compositor keeps Start up and
	 * says so again: not a reopening, so no entrance animation */
	if (shell.start_visible == (visible != 0)) {
		return;
	}
	shell.start_visible = visible != 0;
	if (shell.start_visible) {
		panels_snap(NULL, 0, 0, 0, 0, 0); // the pick is for apps, not Start
	}
	start_visible_changed();
	live_start_visible();
}

static void handle_action(void *data, struct c8_shell_v1 *proto,
		uint32_t action) {
	start_action(action);
}

static void handle_switcher(void *data, struct c8_shell_v1 *proto,
		int32_t direction, uint32_t modifiers) {
	panels_switcher(direction, modifiers);
}

static void handle_snap(void *data, struct c8_shell_v1 *proto,
		struct c8_shell_window_v1 *window, int32_t side, int32_t x,
		int32_t y, int32_t width, int32_t height) {
	struct window *w = window ? c8_shell_window_v1_get_user_data(window) :
		NULL;
	panels_snap(w, side, x, y, width, height);
}

static bool parse_bool(const char *s) {
	return strcmp(s, "true") == 0;
}

static void handle_appearance(void *data, struct c8_shell_v1 *proto,
		const char *key, const char *value) {
	struct appearance *a = &shell.appearance;
	if (strcmp(key, "accent") == 0) {
		c8ui_parse_color(value, &a->accent);
	} else if (strcmp(key, "background") == 0) {
		c8ui_parse_color(value, &a->background);
	} else if (strcmp(key, "pattern") == 0) {
		set_str(&a->pattern, value);
	} else if (strcmp(key, "more_tiles") == 0) {
		a->more_tiles = parse_bool(value);
	} else if (strcmp(key, "live_tiles") == 0) {
		a->live_tiles = parse_bool(value);
	} else if (strcmp(key, "font") == 0) {
		set_str(&a->font, value);
	} else if (strcmp(key, "icon_theme") == 0) {
		set_str(&a->icon_theme, value);
	} else if (strcmp(key, "notification_corner") == 0) {
		set_str(&a->notification_corner, value);
	} else if (strcmp(key, "clock") == 0) {
		set_str(&a->clock, value);
	} else if (strcmp(key, "xr") == 0) {
		a->xr = parse_bool(value);
	} else if (strcmp(key, "night_light") == 0) {
		a->night_light = strcmp(value, "on") == 0;
	} else if (strcmp(key, "project") == 0) {
		set_str(&a->project, value);
	} else if (strcmp(key, "project_choices") == 0) {
		set_str(&a->project_choices, value);
	}
}

static void handle_appearance_done(void *data, struct c8_shell_v1 *proto) {
	start_appearance_changed();
	panels_appearance_changed();
	project_changed();
	quick_status_changed(); // Night light's tile
	notify_appearance_changed();
}

static void handle_power(void *data, struct c8_shell_v1 *proto,
		uint32_t available) {
	shell.power = available;
	start_power_changed();
}

static void handle_window(void *data, struct c8_shell_v1 *proto,
		struct c8_shell_window_v1 *window) {
	struct window *w = calloc(1, sizeof(*w));
	w->proto = window;
	w->capture_fd = -1;
	/* Announced least recently used first: each new one is the newest */
	wl_list_insert(&shell.windows, &w->link);
	c8_shell_window_v1_add_listener(window, &window_listener, w);
	/* Whatever was launching has its window now */
	splash_end();
}

static void handle_locked(void *data, struct c8_shell_v1 *proto,
		uint32_t locked) {
	shell.locked = locked != 0;
	logind_locked_changed();
	notify_locked_changed();
}

static const struct c8_shell_v1_listener shell_listener = {
	.start_visible = handle_start_visible,
	.action = handle_action,
	.switcher = handle_switcher,
	.appearance = handle_appearance,
	.appearance_done = handle_appearance_done,
	.power = handle_power,
	.window = handle_window,
	.locked = handle_locked,
	.snap = handle_snap,
};

/* Stealth mode on or off: Start's name and picture are drawn from it each
 * time; flyouts, search and toasts take it as they're made */
static void stealth_changed(void *data) {
	(void)data;
	start_redraw();
	quick_status_changed();
}

int main(int argc, char *argv[]) {
	/* Day names and the 12/24-hour choice as the user's language has them */
	setlocale(LC_TIME, "");
	/* c8 passes both: where its config is, and that this is a restart */
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "--config") == 0 && i + 1 < argc) {
			shell.config_dir = g_strdup(argv[++i]);
		} else if (strcmp(argv[i], "--respawn") == 0) {
			shell.respawned = true;
		}
	}
	if (shell.config_dir == NULL) {
		shell.config_dir = g_build_filename(g_get_user_config_dir(),
			"cont8nuum", NULL);
	}
	c8_stealth_config_dir(shell.config_dir);
	wl_list_init(&shell.windows);
	shell.appearance.accent = 0x1ba1e2;
	shell.appearance.background = 0x180052;
	shell.appearance.live_tiles = true;

	shell.app = c8ui_app_new("c8-shell");
	if (shell.app == NULL) {
		fprintf(stderr, "c8-shell: cannot connect to the compositor\n");
		return 1;
	}
	shell.proto = c8ui_app_bind(shell.app, &c8_shell_v1_interface, 1);
	if (shell.proto == NULL) {
		fprintf(stderr, "c8-shell: the compositor didn't offer c8_shell_v1; "
			"c8 starts the shell itself\n");
		c8ui_app_destroy(shell.app);
		return 1;
	}
	c8_shell_v1_add_listener(shell.proto, &shell_listener, NULL);
	c8_stealth_watch(stealth_changed, NULL);
	live_init();
	wake_init();
	start_init();
	panels_init();
	context_init();
	splash_init();
	media_init();
	notify_init();
	tray_init();
	logind_init();
	drives_init();
	status_init();
	profiles_init();
	int ret = c8ui_app_run(shell.app);
	live_flush();
	c8ui_app_destroy(shell.app);
	return ret;
}
