/*
 * Input methods: text-input-v3 (what apps speak) relayed to and from
 * input-method-v2 (what fcitx5, ibus-wayland or an on-screen keyboard
 * speak). The app with the keyboard has its text inputs entered; when one
 * is enabled the input method is activated and told about it, and what
 * the input method composes or commits goes back to that text input.
 * While it grabs the keyboard, keys go to it instead of the app. Its
 * candidate popups are placed by the text cursor.
 */
#define _GNU_SOURCE
#include <stdlib.h>
#include <wlr/types/wlr_input_method_v2.h>
#include <wlr/types/wlr_text_input_v3.h>
#include <wlr/util/log.h>
#include "server.h"

struct text_input {
	struct wl_list link; // im.text_inputs
	struct c8_server *server;
	struct wlr_text_input_v3 *input;
	struct wl_listener enable, commit, disable, destroy;
};

struct popup {
	struct wl_list link; // im.popups
	struct c8_server *server;
	struct wlr_input_popup_surface_v2 *popup;
	struct wlr_scene_tree *tree;
	struct wl_listener commit, destroy;
};

static struct {
	struct wlr_text_input_manager_v3 *text_inputs_manager;
	struct wlr_input_method_manager_v2 *manager;
	struct wlr_input_method_v2 *method;
	struct wlr_input_method_keyboard_grab_v2 *grab;
	struct wl_list text_inputs, popups;
	struct wl_listener new_text_input, new_method, method_commit,
		method_grab, method_destroy, method_popup, grab_destroy;
} im;

static struct c8_server *im_server;

/* The enabled text input of the app with the keyboard */
static struct text_input *active_input(void) {
	struct text_input *ti;
	wl_list_for_each(ti, &im.text_inputs, link) {
		if (ti->input->focused_surface && ti->input->current_enabled) {
			return ti;
		}
	}
	return NULL;
}

/* Where a surface is on the screens, from the scene */

struct find {
	struct wlr_surface *surface;
	int x, y;
	bool found;
};

static void find_buffer(struct wlr_scene_buffer *buffer, int sx, int sy,
		void *data) {
	struct find *f = data;
	struct wlr_scene_surface *s = wlr_scene_surface_try_from_buffer(buffer);
	if (!f->found && s && s->surface == f->surface) {
		f->found = true;
		f->x = sx;
		f->y = sy;
	}
}

static bool surface_origin(struct c8_server *server,
		struct wlr_surface *surface, int *x, int *y) {
	struct find f = { .surface = surface };
	wlr_scene_node_for_each_buffer(&server->scene->tree.node, find_buffer, &f);
	*x = f.x;
	*y = f.y;
	return f.found;
}

/* Candidate popups go just under the text cursor */
static void place_popup(struct popup *p) {
	struct text_input *ti = active_input();
	struct wlr_box out;
	c8_output_box(p->server, &out);
	int x = out.x + out.width / 2, y = out.y + out.height / 2;
	struct wlr_box cursor = { 0 };
	int ox, oy;
	if (ti && surface_origin(p->server, ti->input->focused_surface, &ox,
			&oy)) {
		cursor = ti->input->current.cursor_rectangle;
		x = ox + cursor.x;
		y = oy + cursor.y + cursor.height;
	}
	/* Kept on screen: above the text if it won't fit below */
	int w = p->popup->surface->current.width;
	int h = p->popup->surface->current.height;
	if (x + w > out.x + out.width) {
		x = out.x + out.width - w;
	}
	if (y + h > out.y + out.height) {
		y -= h + cursor.height;
	}
	x = x < out.x ? out.x : x;
	y = y < out.y ? out.y : y;
	wlr_scene_node_set_position(&p->tree->node, x, y);
	if (ti) {
		struct wlr_box rect = { cursor.x + ox - x, cursor.y + oy - y,
			cursor.width, cursor.height };
		wlr_input_popup_surface_v2_send_text_input_rectangle(p->popup, &rect);
	}
}

static void place_popups(void) {
	struct popup *p;
	wl_list_for_each(p, &im.popups, link) {
		place_popup(p);
	}
}

static void popup_commit(struct wl_listener *listener, void *data) {
	struct popup *p = wl_container_of(listener, p, commit);
	place_popup(p);
}

static void popup_destroy(struct wl_listener *listener, void *data) {
	struct popup *p = wl_container_of(listener, p, destroy);
	wl_list_remove(&p->commit.link);
	wl_list_remove(&p->destroy.link);
	wl_list_remove(&p->link);
	wlr_scene_node_destroy(&p->tree->node);
	free(p);
}

/* State to the input method */

static void send_state(struct text_input *ti) {
	struct wlr_input_method_v2 *m = im.method;
	struct wlr_text_input_v3 *in = ti->input;
	if (in->active_features & WLR_TEXT_INPUT_V3_FEATURE_SURROUNDING_TEXT) {
		wlr_input_method_v2_send_surrounding_text(m,
			in->current.surrounding.text ? in->current.surrounding.text : "",
			in->current.surrounding.cursor, in->current.surrounding.anchor);
	}
	wlr_input_method_v2_send_text_change_cause(m,
		in->current.text_change_cause);
	if (in->active_features & WLR_TEXT_INPUT_V3_FEATURE_CONTENT_TYPE) {
		wlr_input_method_v2_send_content_type(m,
			in->current.content_type.hint, in->current.content_type.purpose);
	}
	wlr_input_method_v2_send_done(m);
}

static void input_enable(struct wl_listener *listener, void *data) {
	struct text_input *ti = wl_container_of(listener, ti, enable);
	if (im.method) {
		wlr_input_method_v2_send_activate(im.method);
		send_state(ti);
	}
}

static void input_commit(struct wl_listener *listener, void *data) {
	struct text_input *ti = wl_container_of(listener, ti, commit);
	if (im.method && ti->input->current_enabled) {
		send_state(ti);
		place_popups();
	}
}

static void input_disable(struct wl_listener *listener, void *data) {
	if (im.method) {
		wlr_input_method_v2_send_deactivate(im.method);
		wlr_input_method_v2_send_done(im.method);
	}
}

static void input_destroy(struct wl_listener *listener, void *data) {
	struct text_input *ti = wl_container_of(listener, ti, destroy);
	if (ti->input->current_enabled && im.method) {
		wlr_input_method_v2_send_deactivate(im.method);
		wlr_input_method_v2_send_done(im.method);
	}
	wl_list_remove(&ti->enable.link);
	wl_list_remove(&ti->commit.link);
	wl_list_remove(&ti->disable.link);
	wl_list_remove(&ti->destroy.link);
	wl_list_remove(&ti->link);
	free(ti);
}

static struct wl_client *client_of(struct wlr_surface *surface) {
	return surface ? wl_resource_get_client(surface->resource) : NULL;
}

static void new_text_input(struct wl_listener *listener, void *data) {
	struct wlr_text_input_v3 *input = data;
	struct text_input *ti = calloc(1, sizeof(*ti));
	ti->input = input;
	c8_listen(&ti->enable, &input->events.enable, input_enable);
	c8_listen(&ti->commit, &input->events.commit, input_commit);
	c8_listen(&ti->disable, &input->events.disable, input_disable);
	c8_listen(&ti->destroy, &input->events.destroy, input_destroy);
	wl_list_insert(&im.text_inputs, &ti->link);
	/* For an app that has the keyboard already */
	struct wlr_surface *focus = input->seat ?
		input->seat->keyboard_state.focused_surface : NULL;
	if (focus && client_of(focus) == wl_resource_get_client(input->resource)) {
		wlr_text_input_v3_send_enter(input, focus);
	}
}

/* The keyboard moved to surface (NULL for none) */
void c8_im_focus(struct c8_server *server, struct wlr_surface *surface) {
	struct text_input *ti;
	wl_list_for_each(ti, &im.text_inputs, link) {
		struct wlr_text_input_v3 *in = ti->input;
		if (in->focused_surface == surface) {
			continue;
		}
		if (in->focused_surface) {
			if (in->current_enabled && im.method) {
				wlr_input_method_v2_send_deactivate(im.method);
				wlr_input_method_v2_send_done(im.method);
			}
			wlr_text_input_v3_send_leave(in);
		}
		if (surface && client_of(surface) ==
				wl_resource_get_client(in->resource)) {
			wlr_text_input_v3_send_enter(in, surface);
		}
	}
}

/* From the input method */

static void method_commit(struct wl_listener *listener, void *data) {
	struct text_input *ti = active_input();
	struct wlr_input_method_v2 *m = im.method;
	if (ti == NULL || m == NULL) {
		return;
	}
	struct wlr_text_input_v3 *in = ti->input;
	if (m->current.preedit.text) {
		wlr_text_input_v3_send_preedit_string(in, m->current.preedit.text,
			m->current.preedit.cursor_begin, m->current.preedit.cursor_end);
	}
	if (m->current.commit_text) {
		wlr_text_input_v3_send_commit_string(in, m->current.commit_text);
	}
	if (m->current.delete.before_length || m->current.delete.after_length) {
		wlr_text_input_v3_send_delete_surrounding_text(in,
			m->current.delete.before_length, m->current.delete.after_length);
	}
	wlr_text_input_v3_send_done(in);
}

static void grab_destroy(struct wl_listener *listener, void *data) {
	struct wlr_input_method_keyboard_grab_v2 *grab = data;
	wl_list_remove(&im.grab_destroy.link);
	im.grab = NULL;
	if (grab->keyboard) {
		/* The app gets the modifiers as they are now */
		wlr_seat_keyboard_notify_modifiers(im_server->seat,
			&grab->keyboard->modifiers);
	}
}

static void method_grab(struct wl_listener *listener, void *data) {
	struct wlr_input_method_keyboard_grab_v2 *grab = data;
	struct wlr_keyboard *kb = wlr_seat_get_keyboard(grab->input_method->seat);
	im.grab = grab;
	wlr_input_method_keyboard_grab_v2_set_keyboard(grab, kb);
	c8_listen(&im.grab_destroy, &grab->events.destroy, grab_destroy);
}

static void method_destroy(struct wl_listener *listener, void *data) {
	wl_list_remove(&im.method_commit.link);
	wl_list_remove(&im.method_grab.link);
	wl_list_remove(&im.method_destroy.link);
	wl_list_remove(&im.method_popup.link);
	im.method = NULL;
	/* Text in progress is dropped */
	struct text_input *ti = active_input();
	if (ti) {
		wlr_text_input_v3_send_preedit_string(ti->input, NULL, 0, 0);
		wlr_text_input_v3_send_done(ti->input);
	}
}

static void new_popup(struct wl_listener *listener, void *data);

static void new_method(struct wl_listener *listener, void *data) {
	struct wlr_input_method_v2 *method = data;
	if (im.method) {
		/* One at a time */
		wlr_input_method_v2_send_unavailable(method);
		return;
	}
	im.method = method;
	c8_listen(&im.method_commit, &method->events.commit, method_commit);
	c8_listen(&im.method_grab, &method->events.grab_keyboard, method_grab);
	c8_listen(&im.method_destroy, &method->events.destroy, method_destroy);
	c8_listen(&im.method_popup, &method->events.new_popup_surface, new_popup);
	struct text_input *ti = active_input();
	if (ti) {
		wlr_input_method_v2_send_activate(method);
		send_state(ti);
	}
}

/* The input method gets the keys only while the app in front is taking
 * text from it. A grab alone isn't enough: any program can ask for one,
 * and would then read every key typed anywhere, passwords too. */
static bool grab_takes_keys(struct c8_server *server) {
	return im.grab != NULL && !c8_locked(server) && active_input() != NULL;
}

/* Keys while the input method has the keyboard; true if it took them */
bool c8_im_key(struct c8_server *server, struct wlr_keyboard *kb,
		struct wlr_keyboard_key_event *event) {
	if (!grab_takes_keys(server)) {
		return false;
	}
	wlr_input_method_keyboard_grab_v2_set_keyboard(im.grab, kb);
	wlr_input_method_keyboard_grab_v2_send_key(im.grab, event->time_msec,
		event->keycode, event->state);
	return true;
}

bool c8_im_modifiers(struct c8_server *server, struct wlr_keyboard *kb) {
	if (!grab_takes_keys(server)) {
		return false;
	}
	wlr_input_method_keyboard_grab_v2_set_keyboard(im.grab, kb);
	wlr_input_method_keyboard_grab_v2_send_modifiers(im.grab, &kb->modifiers);
	return true;
}

static void new_popup(struct wl_listener *listener, void *data) {
	struct wlr_input_popup_surface_v2 *popup = data;
	struct popup *p = calloc(1, sizeof(*p));
	p->server = im_server;
	p->popup = popup;
	p->tree = wlr_scene_subsurface_tree_create(im_server->layers.overlay,
		popup->surface);
	c8_listen(&p->commit, &popup->surface->events.commit, popup_commit);
	c8_listen(&p->destroy, &popup->events.destroy, popup_destroy);
	wl_list_insert(&im.popups, &p->link);
	place_popup(p);
}

void c8_im_init(struct c8_server *server) {
	im_server = server;
	wl_list_init(&im.text_inputs);
	wl_list_init(&im.popups);
	im.text_inputs_manager = wlr_text_input_manager_v3_create(server->display);
	c8_listen(&im.new_text_input, &im.text_inputs_manager->events.new_text_input,
		new_text_input);
	im.manager = wlr_input_method_manager_v2_create(server->display);
	c8_listen(&im.new_method, &im.manager->events.new_input_method, new_method);
}

void c8_im_finish(struct c8_server *server) {
	wl_list_remove(&im.new_text_input.link);
	wl_list_remove(&im.new_method.link);
}
