/* Copyright (C) 2013 G.P. Halkes
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3, as
   published by the Free Software Foundation.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file */

#include <stdlib.h>
#include <string.h>
#include <unictype.h>
#include <uniwidth.h>

#include "window.h"

/* TODO
	- eliminate the start member from the line_t struct
*/


/** @internal
    @brief The maximum size of a UTF-8 character in bytes. Used in ::win_addnstr.
*/
#define UTF8_MAX_BYTES 4

/* Attribute to index mapping. For now this uses a simple linear search. Should
   this turn out to be too expensive, it can be easily replaced by a hash-table
   based solution, an LRU cache with linear search or a sorted list with binary
   search. Whatever the data structure used, by ensuring use of the internal API,
   we can easily replace the implementation later.
*/

/* Attribute to index mapping. To make the mapping quick, a simple hash table
   with hash chaining is used.
*/

typedef struct attr_map_t attr_map_t;
struct attr_map_t {
	attr_t attr;
	int next;
};

/** @internal
    @brief The initial allocation for ::attr_map.
*/
#define ATTR_MAP_START_SIZE 32
/** @internal
    @brief The size of the hash map used for ::t3_attr_t mapping.
*/
#define ATTR_HASH_MAP_SIZE 337

static attr_map_t *attr_map; /**< @internal @brief The map of indices to attribute sets. */
static int attr_map_fill, /**< @internal @brief The number of elements used in ::attr_map. */
	attr_map_allocated; /**< @internal @brief The number of elements allocated in ::attr_map. */
static int attr_hash_map[ATTR_HASH_MAP_SIZE]; /**< @internal @brief Hash map for quickly mapping ::t3_attr_t's to indices. */

td_bool win_bce;

static void adjust_lines(window_t *win);

/** Create a new window_t.
    @param parent window_t used for clipping and relative positioning.
    @param height The desired height in terminal lines.
    @param width The desired width in terminal columns.
    @param y The vertical location of the window in terminal lines.
    @param x The horizontal location of the window in terminal columns.
    @param depth The depth of the window in the stack of windows.
    @return A pointer to a new window_t struct or @c NULL if not enough
    	memory could be allocated.

    The @p depth parameter determines the z-order of the windows. Windows
    with lower depth will hide windows with higher depths. However, this only
    holds relative to the @p parent window. The position will be relative to
    the top-left corner of the @p parent window, or to the top-left corner of
    the terminal if @p parent is @c NULL.
*/
window_t *win_new(int height, int width) {
	window_t *retval;
	int i;

	if (height <= 0 || width <= 0)
		return NULL;

	if ((retval = calloc(1, sizeof(window_t))) == NULL)
		return NULL;

	retval->width = width;
	retval->height = height;
	retval->cursor_state = CURSOR_NORM;

	if ((retval->lines = calloc(1, sizeof(line_data_t) * height)) == NULL) {
		win_del(retval);
		return NULL;
	}

	for (i = 0; i < height; i++) {
		retval->lines[i].allocated = width > INITIAL_ALLOC ? INITIAL_ALLOC : width;
		if ((retval->lines[i].data = malloc(retval->lines[i].allocated)) == NULL) {
			win_del(retval);
			return NULL;
		}
	}
	adjust_lines(retval);

	if ((retval->output_buffer.data = malloc(INITIAL_ALLOC)) == NULL) {
		win_del(retval);
		return NULL;
	}
	retval->output_buffer.allocated = INITIAL_ALLOC;

	return retval;
}

/** Discard a window_t.
    @param win The window_t to discard.

    Note that child windows are @em not automatically discarded as well. All
    child windows have their parent attribute set to @c NULL.
*/
void win_del(window_t *win) {
	int i;
	if (win == NULL)
		return;

	if (win->lines != NULL) {
		for (i = 0; i < win->height; i++)
			free(win->lines[i].data);
		free(win->lines);
	}
	free(win->output_buffer.data);
	free(win);
}

/** Make a deep copy of a window_t. */
window_t *win_copy(window_t *win) {
	window_t *retval;
	int i;

	if (win == NULL)
		return NULL;

	if ((retval = calloc(1, sizeof(window_t))) == NULL)
		return NULL;

	retval->width = win->width;
	retval->height = win->height;
	retval->cursor_state = win->cursor_state;
	retval->paint_x = win->paint_x;
	retval->paint_y = win->paint_y;

	if ((retval->lines = calloc(1, sizeof(line_data_t) * retval->height)) == NULL) {
		win_del(retval);
		return NULL;
	}

	for (i = 0; i < retval->height; i++) {
		retval->lines[i].length = win->lines[i].length;
		retval->lines[i].allocated = win->lines[i].length;
		if ((retval->lines[i].data = malloc(retval->lines[i].allocated)) == NULL) {
			win_del(retval);
			return NULL;
		}
		memcpy(retval->lines[i].data, win->lines[i].data, win->lines[i].length);
	}

	if ((retval->output_buffer.data = malloc(INITIAL_ALLOC)) == NULL) {
		win_del(retval);
		return NULL;
	}
	retval->output_buffer.allocated = INITIAL_ALLOC;

	return retval;
}

/** Change a window_t's size.
    @param win The window_t to change the size of.
    @param height The desired new height of the window_t in terminal lines.
    @param width The desired new width of the window_t in terminal columns.
    @return A boolean indicating succes, depending on the validity of the
        parameters and whether reallocation of the internal data
        structures succeeds.
*/
td_bool win_resize(window_t *win, int height, int width) {
	int i;

	if (height <= 0 || width <= 0)
		return td_false;

	if (win->lines == NULL) {
		win->height = height;
		win->width = width;
		return td_true;
	}

	if (height > win->height) {
		void *result;
		if ((result = realloc(win->lines, height * sizeof(line_data_t))) == NULL)
			return td_false;
		win->lines = result;
		memset(win->lines + win->height, 0, sizeof(line_data_t) * (height - win->height));
		for (i = win->height; i < height; i++) {
			if ((win->lines[i].data = malloc(INITIAL_ALLOC)) == NULL) {
				for (i = win->height; i < height && win->lines[i].data != NULL; i++)
					free(win->lines[i].data);
				return td_false;
			}
			win->lines[i].allocated = INITIAL_ALLOC;
		}
	} else if (height < win->height) {
		for (i = height; i < win->height; i++)
			free(win->lines[i].data);
		memset(win->lines + height, 0, sizeof(line_data_t) * (win->height - height));
	}

	adjust_lines(win);

	win->height = height;
	win->width = width;
	return td_true;
}

/** Change the position where characters are written to the window_t. */
void win_set_paint(window_t *win, int y, int x) {
	win->paint_x = x < 0 ? 0 : (x < win->width ? x : win->width - 1);
	win->paint_y = y < 0 ? 0 : (y < win->height ? y : win->height - 1);
}

td_bool win_compare(window_t *winA, window_t *winB, FILE *descr_out) {
	int i;

	if (winA->height != winB->height || winA->width != winB->width) {
		if (descr_out != NULL)
			fprintf(descr_out, "Terminals have different size: %dx%d vs. %dx%d\n",
				winA->width, winA->height, winB->width, winB->height);
		return td_false;
	}

	if (winA->cursor_state != winB->cursor_state ||
			(winA->cursor_state != CURSOR_INVIS && (winA->paint_x != winB->paint_x || winA->paint_y != winB->paint_y)))
	{
		static const char *cursor_state_strings[3] = {
			"visible", "invisible", "highly visible"
		};

		if (descr_out != NULL)
			fprintf(descr_out, "Cursor state is different: %s at %d,%d vs. %s at %d,%d\n",
				cursor_state_strings[winA->cursor_state], winA->paint_x + 1, winA->paint_y + 1,
				cursor_state_strings[winB->cursor_state], winB->paint_x + 1, winB->paint_y + 1);
		return td_false;
	}

	for (i = 0; i < winA->height; i++) {
		if (winA->lines[i].width != winB->lines[i].width)
			fatal("Internal error in tracking window contents.\n");
		if (winA->lines[i].length != winB->lines[i].length ||
				memcmp(winA->lines[i].data, winB->lines[i].data, winA->lines[i].length) != 0)
		{
			if (descr_out != NULL) {
				size_t block_size_bytesA, block_size_bytesB;
				uint32_t block_sizeA, block_sizeB;
				int column;
				int offset;

				/* Find first block that is different. */
				for (offset = 0, column = 0; offset < winA->lines[i].length && offset < winB->lines[i].length;
						offset += (block_sizeA >> 1), column += _BLOCK_SIZE_TO_WIDTH(block_sizeA))
				{
					block_sizeA = get_value(winA->lines[i].data + offset, &block_size_bytesA);
					block_sizeB = get_value(winB->lines[i].data + offset, &block_size_bytesB);
					if (block_sizeA != block_sizeB)
						break;
					offset += block_size_bytesA;
					if (memcmp(winA->lines[i].data + offset, winB->lines[i].data + offset, block_sizeA >> 1) != 0)
						break;
				}

				fprintf(descr_out, "First difference encountered at position %d,%d\n", column + 1, i + 1);
			}
			return td_false;
		}
	}
	return td_true;
}


int win_get_paint_x(window_t *win) {
	return win->paint_x;
}

int win_get_paint_y(window_t *win) {
	return win->paint_y;
}

int win_get_height(window_t *win) {
	return win->height;
}

int win_get_width(window_t *win) {
	return win->width;
}

void win_scroll(window_t *win) {
	line_data_t first_line = win->lines[0];
	int i;

	for (i = 1; i < win->height; i++)
		win->lines[i - 1] = win->lines[i];
	first_line.length = 0;
	first_line.width = 0;
	win->lines[win->height - 1] = first_line;
	adjust_lines(win);
}

void win_scroll_back(window_t *win) {
	line_data_t last_line = win->lines[win->height - 1];
	int i;

	for (i = win->height - 1; i > 0; i--)
		win->lines[i] = win->lines[i - 1];

	last_line.length = 0;
	last_line.width = 0;
	win->lines[0] = last_line;
	adjust_lines(win);
}

/** Ensure that a line_data_t struct has at least a specified number of
        bytes of unused space.
    @param line The line_data_t struct to check.
    @param n The required unused space in bytes.
    @return A boolean indicating whether, after possibly reallocating, the
    	requested number of bytes is available.
*/
td_bool ensure_space(line_data_t *line, size_t n) {
	int newsize;
	char *resized;

	if (n > INT_MAX || INT_MAX - (int) n < line->length)
		return td_false;

	if (line->allocated > line->length + (int) n)
		return td_true;

	newsize = line->allocated;

	do {
		/* Sanity check for overflow of allocated variable. Prevents infinite loops. */
		if (newsize > INT_MAX / 2)
			newsize = INT_MAX;
		else
			newsize *= 2;
	} while (newsize - line->length < (int) n);

	if ((resized = realloc(line->data, sizeof(attr_t) * newsize)) == NULL)
		return td_false;
	line->data = resized;
	line->allocated = newsize;
	return td_true;
}

/** @internal
    @brief Map a set of attributes to an integer.
    @param attr The attribute set to map.
*/
int map_attr(attr_t attr) {
	int ptr;

	for (ptr = attr_hash_map[attr % ATTR_HASH_MAP_SIZE]; ptr != -1 && attr_map[ptr].attr != attr; ptr = attr_map[ptr].next) {}

	if (ptr != -1)
		return ptr;

	if (attr_map_fill >= attr_map_allocated) {
		int new_allocation = attr_map_allocated == 0 ? ATTR_MAP_START_SIZE : attr_map_allocated * 2;
		attr_map_t *new_map;

		if ((new_map = realloc(attr_map, new_allocation * sizeof(attr_map_t))) == NULL)
			fatal("Out of memory\n");
		attr_map = new_map;
		attr_map_allocated = new_allocation;
	}
	attr_map[attr_map_fill].attr = attr;
	attr_map[attr_map_fill].next = attr_hash_map[attr % ATTR_HASH_MAP_SIZE];
	attr_hash_map[attr % ATTR_HASH_MAP_SIZE] = attr_map_fill;

	return attr_map_fill++;
}

/** @internal
    @brief Get the set of attributes associated with a mapped integer.
    @param idx The mapped attribute index as returned by ::_t3_map_attr.
*/
attr_t get_attr(int idx) {
	if (idx < 0 || idx > attr_map_fill)
		return 0;
	return attr_map[idx].attr;
}

/** @internal
    @brief Initialize data structures used for attribute set mappings.
*/
void init_attr_map(void) {
	int i;
	for (i = 0; i < ATTR_HASH_MAP_SIZE; i++)
		attr_hash_map[i] = -1;
}

/** @internal
    @brief Clean up the memory used for attribute set mappings.
*/
void free_attr_map(void) {
	free(attr_map);
	attr_map = NULL;
	attr_map_allocated = 0;
	attr_map_fill = 0;
	init_attr_map();
}

void win_set_default_attrs(window_t *win, attr_t attrs) {
	win->default_attrs = map_attr(attrs);
}

attr_t win_get_default_attrs(window_t *win) {
	return get_attr(win->default_attrs);
}

/** Get the first UTF-8 value encoded in a string.
    @param src The UTF-8 string to parse.
    @param size The location to store the size of the character.
    @return The value at the start of @p src.

    @note This function assumes that the input is a valid UTF-8 encoded value.
*/
uint32_t get_value(const char *src, size_t *size) {
	int bytes_left;
	uint32_t retval;

	switch ((uint8_t) src[0]) {
		case  0: case  1: case  2: case  3: case  4: case  5: case  6: case  7:
		case  8: case  9: case 10: case 11: case 12: case 13: case 14: case 15:
		case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23:
		case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31:
		case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39:
		case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47:
		case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55:
		case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63:
		case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71:
		case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79:
		case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87:
		case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95:
		case  96: case  97: case  98: case  99: case 100: case 101: case 102: case 103:
		case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111:
		case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119:
		case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127:
			*size = 1;
			return src[0];
		case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201:
		case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 209:
		case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217:
		case 218: case 219: case 220: case 221: case 222: case 223:
			bytes_left = 1;
			retval = src[0] & 0x1F;
			break;
		case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231:
		case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239:
			bytes_left = 2;
			retval = src[0] & 0x0F;
			break;
		case 240: case 241: case 242: case 243: case 244: case 245: case 246: case 247:
			bytes_left = 3;
			retval = src[0] & 0x07;
			break;
		case 248: case 249: case 250: case 251:
			bytes_left = 4;
			retval = src[0] & 0x03;
			break;
		case 252: case 253:
			bytes_left = 5;
			retval = src[1] & 1;
			break;
		/* Add default case to shut up the compiler. */
		default:
			return 0;
	}

	*size = bytes_left + 1;
	src++;
	for (; bytes_left > 0; bytes_left--)
		retval = (retval << 6) | (src++[0] & 0x3f);
	return retval;
}

/** Get the first codepoint represented by a UTF-8 string.
    @param src The UTF-8 string to parse.
	@param size The location to store the number of bytes in the first
	    codepoint, which should contain the number of bytes in src on entry
		(may be @c NULL).
    @return The codepoint at the start of @p src or @c FFFD if an invalid
        codepoint is encountered.
*/
uint32_t utf8_get(const char *src, size_t *size) {
	size_t max_size, _size;
	int bytes_left;
	uint32_t retval, least;

	/* Just assume the buffer is large enough if size is not passed. */
	max_size = size == NULL ? 4 : *size;
	_size = 1;

	switch ((uint8_t) src[0]) {
		case  0: case  1: case  2: case  3: case  4: case  5: case  6: case  7:
		case  8: case  9: case 10: case 11: case 12: case 13: case 14: case 15:
		case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23:
		case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31:
		case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39:
		case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47:
		case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55:
		case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63:
		case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71:
		case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79:
		case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87:
		case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95:
		case  96: case  97: case  98: case  99: case 100: case 101: case 102: case 103:
		case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111:
		case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119:
		case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127:
			if (size != NULL)
				*size = _size;
			return src[0];
		case 128: case 129: case 130: case 131: case 132: case 133: case 134: case 135:
		case 136: case 137: case 138: case 139: case 140: case 141: case 142: case 143:
		case 144: case 145: case 146: case 147: case 148: case 149: case 150: case 151:
		case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159:
		case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167:
		case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175:
		case 176: case 177: case 178: case 179: case 180: case 181: case 182: case 183:
		case 184: case 185: case 186: case 187: case 188: case 189: case 190: case 191:
		case 192: case 193:
			if (size != NULL)
				*size = _size;
			return 0xFFFD;
		case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201:
		case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 209:
		case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217:
		case 218: case 219: case 220: case 221: case 222: case 223:
			least = 0x80;
			bytes_left = 1;
			retval = src[0] & 0x1F;
			break;
		case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231:
		case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239:
			least = 0x800;
			bytes_left = 2;
			retval = src[0] & 0x0F;
			break;
		case 240: case 241: case 242: case 243: case 244:
			least = 0x10000L;
			bytes_left = 3;
			retval = src[0] & 0x07;
			break;
		case 245: case 246: case 247: case 248: case 249: case 250: case 251: case 252:
		case 253: case 254: case 255:
			if (size != NULL)
				*size = _size;
			return 0xFFFD;
		default:
			if (size != NULL)
				*size = _size;
			return 0xFFFD;
	}

	src++;
	for (; bytes_left > 0 && _size < max_size; bytes_left--, _size++) {
		if ((src[0] & 0xC0) != 0x80) {
			if (size != NULL)
				*size = _size;
			return 0xFFFD;
		}
		retval = (retval << 6) | (src[0] & 0x3F);
		src++;
	}
	if (size != NULL)
		*size = _size;

	if (retval < least)
		return 0xFFFD;
	if (retval > 0x10FFFFL)
		return 0xFFFD;
	if (bytes_left > 0)
		return 0xFFFD;
	return retval;
}

/** Write a UTF-8 encoded value.
    @param c The codepoint to convert.
    @param dst The location to store the result.
    @return The number of bytes stored in @p dst.

    The value must be lower than 0x80000000 (i.e. at most 31 bits may be used).
    No check is made for this however, so the calling code must ensure that this
    is the case.
*/
size_t _put_value(uint32_t c, char *dst) {
	if (c < 0x80) {
		dst[0] = c;
		return 1;
	} else if (c < 0x800) {
		dst[0] = 0xc0 | (c >> 6);
		dst[1] = 0x80 | (c & 0x3f);
		return 2;
	} else if (c < 0x10000) {
		dst[0] = 0xe0 | (c >> 12);
		dst[1] = 0x80 | ((c >> 6) & 0x3f);
		dst[2] = 0x80 | (c & 0x3f);
		return 3;
	} else if (c < 0x200000) {
		dst[0] = 0xf0 | (c >> 18);
		dst[1] = 0x80 | ((c >> 12) & 0x3f);
		dst[2] = 0x80 | ((c >> 6) & 0x3f);
		dst[3] = 0x80 | (c & 0x3f);
		return 4;
	} else if (c < 0x4000000) {
		dst[0] = 0xf8 | (c >> 24);
		dst[1] = 0x80 | ((c >> 18) & 0x3f);
		dst[1] = 0x80 | ((c >> 12) & 0x3f);
		dst[2] = 0x80 | ((c >> 6) & 0x3f);
		dst[3] = 0x80 | (c & 0x3f);
		return 5;
	} else {
		dst[0] = 0xfc | (c >> 30);
		dst[1] = 0x80 | ((c >> 24) & 0x3f);
		dst[1] = 0x80 | ((c >> 18) & 0x3f);
		dst[1] = 0x80 | ((c >> 12) & 0x3f);
		dst[2] = 0x80 | ((c >> 6) & 0x3f);
		dst[3] = 0x80 | (c & 0x3f);
		return 6;
	}
}

/** Get the width of a Unicode codepoint.

    This function is a wrapper around uc_width, which takes into account that
    for some characters uc_width returns a value that is different from what
    terminals actually use.
*/
int utf8_wcwidth(uint32_t c) {
	static const char nul;
	if (c >= 0x1160 && c < 0x11fa)
		return 0;
	if (c == 0x00ad)
		return 1;
	return uc_width(c, &nul);
}

/** Create memory block representing a space character with specific attributes.
    @param attr The attribute index to use.
    @param out An array of size at least 8 to write to.
    @return The number of bytes written to @p out.
*/
static size_t create_space_block(int attr, char *out) {
	size_t result_size;
	result_size = _put_value(attr, out + 1);
	result_size++;
	out[result_size] = ' ';
	out[0] = result_size << 1;
	result_size++;
	return result_size;
}

/** Get the attribute index from a block. */
static uint32_t get_block_attr(const char *block) {
	size_t discard;
	for (block++; ((*block) & 0xc0) == 0x80; block++) {}

	return get_value(block, &discard);
}

/** Insert a zero-width character into an existing block.
    @param win The window to write to.
    @param str The string containing the UTF-8 encoded zero-width character.
    @param n The number of bytes in @p str.
    @return A boolean indicating success.
*/
static td_bool _win_add_zerowidth(window_t *win, const char *str, size_t n) {
	uint32_t block_size, new_block_size;
	size_t block_size_bytes, new_block_size_bytes;
	char new_block_size_str[6];
	int pos_width, i;

	if (win->lines == NULL)
		return td_false;

	if (win->paint_y >= win->height)
		return td_true;
	/* Combining characters may be added _at_ width. */
	if (win->paint_x > win->width)
		return td_true;

	if (win->cached_pos_line != win->paint_y || win->cached_pos_width >= win->paint_x) {
		win->cached_pos_line = win->paint_y;
		win->cached_pos = 0;
		win->cached_pos_width = 0;
	}

	/* Simply drop characters that don't belong to any other character. */
	if (win->lines[win->paint_y].length == 0 ||
			win->paint_x == 0 || win->paint_x > win->lines[win->paint_y].width)
		return td_true;

	/* Ensure we have space for n characters, and possibly extend the block size header by 1. */
	if (!ensure_space(win->lines + win->paint_y, n + 1))
		return td_false;

	pos_width = win->cached_pos_width;

	/* Locate the first character that at least partially overlaps the position
	   where this string is supposed to go. Note that this loop will iterate at
	   least once, because if win->cached_pos == win->lines[win->paint_y].length,
	   then win->cached_pos_width will equal win->paint_x, and thereby get invalidated
	   above. */
	block_size = 0; /* Shut up the compiler. */
	for (i = win->cached_pos; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) {
		block_size = get_value(win->lines[win->paint_y].data + i, &block_size_bytes);
		pos_width += _BLOCK_SIZE_TO_WIDTH(block_size);

		/* Do the check for whether we found the insertion point here, so we don't update i. */
		if (pos_width >= win->paint_x)
			break;
	}

	/* Check whether we are being asked to add a zero-width character in the middle
	   of a double-width character. If so, ignore. */
	if (pos_width > win->paint_x)
		return td_true;

	new_block_size = block_size + (n << 1);
	new_block_size_bytes = _put_value(new_block_size, new_block_size_str);

	/* WARNING: from this point on, the block_size and new_block_size variables have
	   a new meaning: the actual size of the block, rather than including the bit
	   indicating the width of the character as well. */
	block_size >>= 1;
	new_block_size >>= 1;

	/* Move the data after the insertion point up by the size of the character
	   string to insert and the difference in block size header size. */
	memmove(win->lines[win->paint_y].data + i + new_block_size + new_block_size_bytes,
		win->lines[win->paint_y].data + i + block_size + block_size_bytes,
		win->lines[win->paint_y].length - i - block_size - block_size_bytes);
	/* Copy the bytes of the new character into the string. */
	memcpy(win->lines[win->paint_y].data + i + block_size + block_size_bytes, str, n);
	/* If applicable, move the data for this block by the difference in block size header size. */
	if (new_block_size_bytes != block_size_bytes) {
		memmove(win->lines[win->paint_y].data + i + new_block_size_bytes,
			win->lines[win->paint_y].data + i + block_size_bytes, new_block_size);
	}
	/* Copy in the new block size header. */
	memcpy(win->lines[win->paint_y].data + i, new_block_size_str, new_block_size_bytes);

	win->lines[win->paint_y].length += n + (new_block_size_bytes - block_size_bytes);
	return td_true;
}

/** Write one or more blocks to a window.
    @param win The window to write to.
    @param blocks The string containing the blocks.
    @param n The number of bytes in @p blocks.
    @return A boolean indicating success.
*/
static td_bool _win_write_blocks(window_t *win, const char *blocks, size_t n) {
	uint32_t block_size;
	size_t block_size_bytes;
	size_t k;
	int i;
	int width = 0;
	int extra_spaces = 0;
	uint32_t extra_spaces_attr;
	td_bool result = td_true;


	if (win->lines == NULL)
		return td_false;

	if (win->paint_y >= win->height || win->paint_x >= win->width || n == 0)
		return td_true;

	for (k = 0; k < n; k += (block_size >> 1) + block_size_bytes) {
		block_size = get_value(blocks + k, &block_size_bytes);
		if (win->paint_x + width + _BLOCK_SIZE_TO_WIDTH(block_size) > win->width)
			break;
		width += _BLOCK_SIZE_TO_WIDTH(block_size);
	}

	if (k < n) {
		extra_spaces = win->width - win->paint_x - width;
		extra_spaces_attr = get_block_attr(blocks + k);
	}
	n = k;

	if (win->cached_pos_line != win->paint_y || win->cached_pos_width > win->paint_x) {
		win->cached_pos_line = win->paint_y;
		win->cached_pos = 0;
		win->cached_pos_width = 0;
	}

	if (win->lines[win->paint_y].width <= win->paint_x) {
		/* Add characters after existing characters. */
		char default_attr_str[8];
		size_t default_attr_size;
		int diff = win->paint_x - win->lines[win->paint_y].width;

		default_attr_size = create_space_block(map_attr(win->default_attrs), default_attr_str);

		if (!ensure_space(win->lines + win->paint_y, n + diff * (default_attr_size)))
			return td_false;

		for (i = diff; i > 0; i--) {
			memcpy(win->lines[win->paint_y].data + win->lines[win->paint_y].length, default_attr_str, default_attr_size);
			win->lines[win->paint_y].length += default_attr_size;
		}

		memcpy(win->lines[win->paint_y].data + win->lines[win->paint_y].length, blocks, n);
		win->lines[win->paint_y].length += n;
		win->lines[win->paint_y].width += width + diff;
	} else {
		/* Character (partly) overwrite existing chars. */
		int pos_width = win->cached_pos_width;
		size_t start_replace = 0, start_space_attr, start_spaces, end_replace, end_space_attr, end_spaces;
		int sdiff;
		char start_space_str[8], end_space_str[8];
		size_t start_space_bytes, end_space_bytes;

		/* Locate the first character that at least partially overlaps the position
		   where this string is supposed to go. Note that this loop will always be
		   entered once, because win->cached_pos will always be < line length.
		   To see why this is the case, consider that when win->cached_pos equals the
		   line length. Then win->paint_x equals the width of the line and that case
		   will be handled above. */
		block_size = 0; /* Shut up the compiler. */
		for (i = win->cached_pos; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) {
			block_size = get_value(win->lines[win->paint_y].data + i, &block_size_bytes);
			if (_BLOCK_SIZE_TO_WIDTH(block_size) + pos_width > win->paint_x)
				break;

			pos_width += _BLOCK_SIZE_TO_WIDTH(block_size);
		}

		win->cached_pos = i;
		win->cached_pos_width = pos_width;

		start_replace = i;

		/* If the character only partially overlaps, we replace the first part with
		   spaces with the attributes of the old character. */
		start_space_attr = get_block_attr(win->lines[win->paint_y].data + start_replace);
		start_spaces = win->paint_x - pos_width;

		/* Now we need to find which other character(s) overlap. However, the current
		   string may overlap with a double width character but only for a single
		   position. In that case we will replace the trailing portion of the character
		   with spaces with the old character's attributes. */
		pos_width += _BLOCK_SIZE_TO_WIDTH(block_size);

		i += (block_size >> 1) + block_size_bytes;

		/* If the character where we start overwriting already fully overlaps with the
		   new string, then we need to only replace this and any spaces that result
		   from replacing the trailing portion need to use the start space attribute */
		if (pos_width >= win->paint_x + width) {
			end_space_attr = start_space_attr;
			end_replace = i;
		} else {
			for (; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) {
				block_size = get_value(win->lines[win->paint_y].data + i, &block_size_bytes);
				pos_width += _BLOCK_SIZE_TO_WIDTH(block_size);
				if (pos_width >= win->paint_x + width)
					break;
			}

			end_space_attr = get_block_attr(win->lines[win->paint_y].data + i);
			end_replace = i < win->lines[win->paint_y].length ? (int) (i + (block_size >> 1) + block_size_bytes) : i;
		}

		end_spaces = pos_width > win->paint_x + width ? pos_width - win->paint_x - width : 0;

		start_space_bytes = create_space_block(start_space_attr, start_space_str);
		end_space_bytes = create_space_block(end_space_attr, end_space_str);

		/* Move the existing characters out of the way. */
		sdiff = n + end_spaces * end_space_bytes + start_spaces * start_space_bytes - (end_replace - start_replace);
		if (sdiff > 0 && !ensure_space(win->lines + win->paint_y, sdiff))
			return td_false;

		memmove(win->lines[win->paint_y].data + end_replace + sdiff, win->lines[win->paint_y].data + end_replace,
			win->lines[win->paint_y].length - end_replace);

		for (i = start_replace; start_spaces > 0; start_spaces--) {
			memcpy(win->lines[win->paint_y].data + i, start_space_str, start_space_bytes);
			i += start_space_bytes;
		}

		memcpy(win->lines[win->paint_y].data + i, blocks, n);
		i += n;
		for (; end_spaces > 0; end_spaces--) {
			memcpy(win->lines[win->paint_y].data + i, end_space_str, end_space_bytes);
			i += end_space_bytes;
		}

		win->lines[win->paint_y].length += sdiff;
		if (win->lines[win->paint_y].width < width + win->paint_x)
			win->lines[win->paint_y].width = width + win->paint_x;
	}
	win->paint_x += width;

	if (extra_spaces > 0) {
		char extra_space_str[8];
		size_t extra_space_bytes;

		extra_space_bytes = create_space_block(extra_spaces_attr, extra_space_str);

		for (i = 0; i < extra_spaces; i++)
			result &= _win_write_blocks(win, extra_space_str, extra_space_bytes);
	}

	return result;
}


/** Add a string with explicitly specified size to a window_t with specified attributes.
    @param win The window_t to add the string to.
    @param str The string to add.
    @param n The size of @p str.
    @param attr The attributes to use.
    @retval ::ERR_SUCCESS on succes
    @retval ::ERR_NONPRINT if a control character was encountered.
    @retval ::ERR_ERRNO otherwise.

    The default attributes are combined with the specified attributes, with
    @p attr used as the priority attributes. All other win_add* functions are
    (indirectly) implemented using this function.
*/
int win_addnstr(window_t *win, const char *str, size_t n) {
	size_t bytes_read;
	char block[1 + 6 + UTF8_MAX_BYTES];
	uint32_t c;
	int retval = ERR_SUCCESS;
	int width;
	size_t block_bytes;

	for (; n > 0; n -= bytes_read, str += bytes_read) {
		bytes_read = n;
		c = utf8_get(str, &bytes_read);

		width = utf8_wcwidth(c);
		/* UC_CATEGORY_MASK_Cn is for unassigned/reserved code points. These are
		   not necessarily unprintable. */
		if (width < 0 || uc_is_general_category_withtable(c, UTF8_CONTROL_MASK)) {
			retval = ERR_NONPRINT;
			continue;
		} else if (width == 0) {
			_win_add_zerowidth(win, str, bytes_read);
			continue;
		}

		block_bytes = _put_value(win->default_attrs, block + 1);
		memcpy(block + 1 + block_bytes, str, bytes_read);
		block_bytes += bytes_read;
		_put_value((block_bytes << 1) + (width == 2 ? 1 : 0), block);
		block_bytes++;

		if (!_win_write_blocks(win, block, block_bytes))
			return ERR_ERRNO;
		if (win->paint_x >= win->width) {
			win->paint_y++;
			win->paint_x = 0;
			if (win->paint_y >= win->height) {
				if (win->cup_active) {
					win->paint_y = win->height - 1;
				} else {
					win_scroll(win);
					win->paint_y = win->height - 1;
				}
			}
		}
	}
	return retval;
}

/** Clear current window_t painting line to end. */
void win_clrtoeol(window_t *win) {
	char space_str[8];
	size_t space_str_bytes;
	int saved_paint_x, saved_paint_y;
	int spaces;

	if (win->paint_y >= win->height || win->paint_x >= win->width)
		return;

	space_str_bytes = create_space_block(map_attr(win_bce ? win->default_attrs : 0), space_str);
	saved_paint_x = win->paint_x;
	saved_paint_y = win->paint_y;

	for (spaces = win->width - win->paint_x; spaces > 0; spaces--)
		_win_write_blocks(win, space_str, space_str_bytes);

	win->paint_x = saved_paint_x;
	win->paint_y = saved_paint_y;
}

/** Clear current window_t painting line to begin. */
void win_clrtobol(window_t *win) {
	char space_str[8];
	size_t space_str_bytes;
	int saved_paint_x, saved_paint_y;
	int spaces;

	if (win->paint_y >= win->height || win->paint_x >= win->width)
		return;

	space_str_bytes = create_space_block(map_attr(win_bce ? win->default_attrs : 0), space_str);
	saved_paint_x = win->paint_x;
	saved_paint_y = win->paint_y;

	win->paint_x = 0;

	for (spaces = saved_paint_x; spaces > 0; spaces--)
		_win_write_blocks(win, space_str, space_str_bytes);

	win->paint_x = saved_paint_x;
	win->paint_y = saved_paint_y;
}

void win_clrtobot(window_t *win) {
	int saved_paint_x, saved_paint_y;
	saved_paint_x = win->paint_x;
	saved_paint_y = win->paint_y;

	win_clrtoeol(win);
	for (; win->paint_y + 1 != win->height; win->paint_y++)
		win_clrtoeol(win);
	win_clrtoeol(win);
	win->paint_x = saved_paint_x;
	win->paint_y = saved_paint_y;
}

void win_clrtotop(window_t *win) {
	int saved_paint_x, saved_paint_y, i;
	saved_paint_x = win->paint_x;
	saved_paint_y = win->paint_y;

	win->paint_x = 0;
	win->paint_y = 0;
	for (i = 0; i < saved_paint_y; i++)
		win_clrtoeol(win);

	win->paint_x = saved_paint_x;
	win->paint_y = saved_paint_y;
	win_clrtobol(win);
}

static void adjust_lines(window_t *win) {
	char space_str[8];
	size_t space_str_bytes;
	int saved_paint_x = win->paint_x;
	int saved_paint_y = win->paint_y;
	int line;

	space_str_bytes = create_space_block(map_attr(win->default_attrs), space_str);

	for (line = 0; line < win->height; line++) {
		if (win->lines[line].width < win->width) {
			win->paint_y = line;
			win->paint_x = win->width - 1;
			_win_write_blocks(win, space_str, space_str_bytes);
		} else if (win->width < win->lines[line].width) {
			int sumwidth = 0, i;
			uint32_t block_size;
			size_t block_size_bytes;

			block_size = get_value(win->lines[line].data, & block_size_bytes);
			for (i = 0; i < win->lines[line].length &&
					sumwidth + _BLOCK_SIZE_TO_WIDTH(block_size) <= win->width; i += (block_size >> 1) + block_size_bytes)
			{
				sumwidth += _BLOCK_SIZE_TO_WIDTH(block_size);
				block_size = get_value(win->lines[line].data + i, & block_size_bytes);
			}

			if (sumwidth < win->width) {
				int spaces = win->width - sumwidth;
				char space_str[8];
				size_t space_str_bytes;

				space_str_bytes = create_space_block(map_attr(0), space_str);
				if ((int) (spaces * space_str_bytes) < win->lines[line].length - i ||
						ensure_space(win->lines + line, spaces * space_str_bytes - win->lines[line].length + i)) {
					win->paint_x = sumwidth;
					for (; spaces > 0; spaces--)
						_win_write_blocks(win, space_str, space_str_bytes);
				}
			}

			win->lines[line].length = i;
			win->lines[line].width = win->width;
		}
	}

	win->paint_x = saved_paint_x;
	win->paint_y = saved_paint_y;
}

void win_set_cursor(window_t *win, cursor_t cursor_state) {
	win->cursor_state = cursor_state;
}

void win_save_cursor(window_t *win) {
	win->saved_cursor_x = win->paint_x;
	win->saved_cursor_y = win->paint_y;
}

void win_restore_cursor(window_t *win) {
	win->paint_x = win->saved_cursor_x;
	win->paint_y = win->saved_cursor_y;
}

void win_set_cup(window_t *win, td_bool cup_active) {
	win->cup_active = cup_active;
}

td_bool win_get_cup(window_t *win) {
	return win->cup_active;
}

/** @} */
