aboutsummaryrefslogtreecommitdiff
path: root/autistdraw.c
blob: 90b5ed8f1b814add431c26c3a6ba94e3f02db8f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// <poll.h> might need this for sigset_t
#define _XOPEN_SOURCE 600

#include <stdio.h>
#include <unistd.h>
#include <locale.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>

#include <poll.h>
#include <signal.h>

#include <curses.h>
#include "termo.h"

#include "config.h"

#define PALETTE_WIDTH 9                 ///< Width of the palette
#define TOP_BAR_CUTOFF 3                ///< Height of the top bar

#define BITMAP_BLOCK_SIZE 50            ///< Step for extending bitmap size

typedef struct app_context app_context_t;
struct app_context
{
	termo_t *tk;                        ///< Termo instance

	chtype palette[2 * 9];              ///< Attribute palette

	uint8_t *bitmap;                    ///< Canvas data for drawing
	int bitmap_x;                       ///< X coord. of left top bitmap corner
	int bitmap_y;                       ///< Y coord. of left top bitmap corner
	size_t bitmap_w;                    ///< Canvas data width
	size_t bitmap_h;                    ///< Canvas data height

	int center_x;                       ///< X coordinate at center
	int center_y;                       ///< Y coordinate at center

	// These two are computed from `center_x' and `center_y':

	int corner_x;                       ///< X coordinate of LT screen corner
	int corner_y;                       ///< Y coordinate of LT screen corner

	int move_saved_x;                   ///< Saved X coord. for moving
	int move_saved_y;                   ///< Saved Y coord. for moving

	uint8_t current_color_left;         ///< Left mouse button color
	uint8_t current_color_right;        ///< Right mouse button color
};

static void
app_init (app_context_t *self)
{
	memset (self, 0, sizeof *self);
}

static int g_winch_pipe[2];

static void
display (const char *format, ...)
{
	va_list ap;

	mvwhline (stdscr, 0, 0, A_REVERSE, COLS);
	attron (A_REVERSE);

	va_start (ap, format);
	vw_printw (stdscr, format, ap);
	va_end (ap);

	attroff (A_REVERSE);
	refresh ();
}

static void
init_palette (app_context_t *app)
{
	start_color ();

	// Also does init_pair (0, -1, -1);
	use_default_colors ();
	// Duplicate it for convenience.
	init_pair (9, -1, -1);

	// Add the basic 8 colors to the default pair.  Once normally, once
	// inverted to workaround VTE's inability to set a bright background.
	for (int i = 0; i < 8; i++)
	{
		init_pair (1  + i, COLOR_WHITE, COLOR_BLACK + i);
		init_pair (10 + i, COLOR_BLACK + i, COLOR_WHITE);
	}

	// Initialize the palette of characters with attributes
	for (int i = 0; i < PALETTE_WIDTH; i++)
	{
		app->palette[i]     = ' ' | COLOR_PAIR (i);
		app->palette[i + 9] = ' ' | COLOR_PAIR (i + 9) | A_REVERSE | A_BOLD;
	}

	// This usually creates a solid black or white.
	app->current_color_left = app->current_color_right = 9;
}

static void
update_canvas_for_screen (app_context_t *app)
{
	app->corner_x = app->center_x - COLS / 2;
	app->corner_y = app->center_y - (LINES - TOP_BAR_CUTOFF) / 2;
}

static void
redraw (app_context_t *app)
{
	int i;

	mvwhline (stdscr, 1, 0, A_REVERSE, COLS);
	mvwhline (stdscr, 2, 0, A_REVERSE, COLS);

	for (i = 0; i < COLS; i++)
	{
		int pair = (float) i / COLS * PALETTE_WIDTH;
		mvaddch (1, i, app->palette[pair]);
		mvaddch (2, i, app->palette[pair + PALETTE_WIDTH]);
	}

	display ("Choose a color from the palette and draw.  "
		"Press Escape or ^C to quit.");
	refresh ();
}

static bool
is_in_bitmap_data (app_context_t *app, int x, int y)
{
	return x >= app->bitmap_x
		&& y >= app->bitmap_y
		&& x <  app->bitmap_x + (int) app->bitmap_w
		&& y <  app->bitmap_y + (int) app->bitmap_h;
}

static void
redraw_canvas (app_context_t *app)
{
	int y = app->corner_y;
	for (int screen_y = TOP_BAR_CUTOFF; screen_y < LINES; screen_y++, y++)
	{
		move (screen_y, 0);

		int x = app->corner_x;
		for (int screen_x = 0; screen_x < COLS; screen_x++, x++)
		{
			uint8_t color;
			if (!is_in_bitmap_data (app, x, y))
				color = 0;
			else
			{
				int data_x = x - app->bitmap_x;
				int data_y = y - app->bitmap_y;
				color = app->bitmap[data_y * app->bitmap_w + data_x];
			}

			addch (app->palette[color]);
		}
	}
	refresh ();
}

static bool
is_visible (app_context_t *app, int x, int y)
{
	return x >= app->corner_x
		&& y >= app->corner_y
		&& x <  app->corner_x + COLS
		&& y <  app->corner_y + LINES - TOP_BAR_CUTOFF;
}

static void
make_place_for_point (app_context_t *app, int x, int y)
{
	if (is_in_bitmap_data (app, x, y))
		return;

	// Make sure the point has some place to go
	int new_bitmap_x = app->bitmap_x;
	int new_bitmap_y = app->bitmap_y;

	while (new_bitmap_x > x)
		new_bitmap_x -= BITMAP_BLOCK_SIZE;
	while (new_bitmap_y > y)
		new_bitmap_y -= BITMAP_BLOCK_SIZE;

	int new_bitmap_w = app->bitmap_w + (app->bitmap_x - new_bitmap_x);
	int new_bitmap_h = app->bitmap_h + (app->bitmap_y - new_bitmap_y);

	while (new_bitmap_x + new_bitmap_w <= x)
		new_bitmap_w += BITMAP_BLOCK_SIZE;
	while (new_bitmap_y + new_bitmap_h <= y)
		new_bitmap_h += BITMAP_BLOCK_SIZE;

	uint8_t *new_bitmap = calloc (new_bitmap_w * new_bitmap_h,
		sizeof *new_bitmap);
	if (app->bitmap)
	{
		// Copy data, assuming that the area can only get larger
		for (size_t data_y = 0; data_y < app->bitmap_h; data_y++)
			memcpy (new_bitmap
				+ ((data_y + app->bitmap_y - new_bitmap_y) * new_bitmap_w)
				+ (app->bitmap_x - new_bitmap_x),
				app->bitmap + (data_y * app->bitmap_w),
				app->bitmap_w * sizeof *new_bitmap);

		free (app->bitmap);
	}

	// Replace the bitmap with the reallocated version
	app->bitmap_x = new_bitmap_x;
	app->bitmap_y = new_bitmap_y;
	app->bitmap_w = new_bitmap_w;
	app->bitmap_h = new_bitmap_h;
	app->bitmap   = new_bitmap;
}

static void
draw_point (app_context_t *app, int x, int y, uint8_t color)
{
	make_place_for_point (app, x, y);

	int data_x = x - app->bitmap_x;
	int data_y = y - app->bitmap_y;
	app->bitmap[data_y * app->bitmap_w + data_x] = color;

	if (is_visible (app, x, y))
	{
		int screen_x = x - app->corner_x;
		int screen_y = y - app->corner_y + TOP_BAR_CUTOFF;

		move (screen_y, screen_x);
		addch (app->palette[color]);
		refresh ();
	}
}

static bool
on_key (app_context_t *app, termo_key_t *key)
{
	if (key->type == TERMO_TYPE_KEYSYM
	 && key->code.sym == TERMO_SYM_ESCAPE)
		return false;

	if (key->type == TERMO_TYPE_KEY
	 && (key->modifiers & TERMO_KEYMOD_CTRL)
	 && (key->code.codepoint == 'C' || key->code.codepoint == 'c'))
		return false;

	if (key->type != TERMO_TYPE_MOUSE)
		return true;

	int screen_y, screen_x, button;
	termo_mouse_event_t event;

	termo_interpret_mouse (app->tk, key, &event, &button, &screen_y, &screen_x);
	if (event != TERMO_MOUSE_PRESS && event != TERMO_MOUSE_DRAG)
		return true;

	if (button == 2)
	{
		if (event == TERMO_MOUSE_DRAG)
		{
			app->corner_x += app->move_saved_x - screen_x;
			app->corner_y += app->move_saved_y - screen_y;

			app->center_x += app->move_saved_x - screen_x;
			app->center_y += app->move_saved_y - screen_y;

			redraw_canvas (app);
		}

		app->move_saved_x = screen_x;
		app->move_saved_y = screen_y;
		return true;
	}

	uint8_t *color;
	if (button == 1)
		color = &app->current_color_left;
	else if (button == 3)
		color = &app->current_color_right;
	else
		return true;

	int canvas_x = app->corner_x + screen_x;
	int canvas_y = app->corner_y + screen_y - TOP_BAR_CUTOFF;

	if (screen_y >= TOP_BAR_CUTOFF)
		draw_point (app, canvas_x, canvas_y, *color);
	else if (screen_y > 0 && event != TERMO_MOUSE_DRAG)
	{
		int pair = (float) screen_x / COLS * PALETTE_WIDTH;
		*color = pair + (screen_y - 1) * PALETTE_WIDTH;
	}

	return true;
}

static void
winch_handler (int signum)
{
	(void) signum;
	write (g_winch_pipe[1], "x", 1);
}

int
main (int argc, char *argv[])
{
	(void) argc;
	(void) argv;

	TERMO_CHECK_VERSION;
	setlocale (LC_CTYPE, "");

	struct sigaction act;
	act.sa_handler = winch_handler;
	act.sa_flags = SA_RESTART;
	sigemptyset (&act.sa_mask);

	// Set up a self-pipe so that we can actually poll on SIGWINCH
	if (sigaction (SIGWINCH, &act, NULL) || pipe (g_winch_pipe))
	{
		fprintf (stderr, "Cannot set up signal handler\n");
		exit (EXIT_FAILURE);
	}

	termo_t *tk = termo_new (STDIN_FILENO, NULL, 0);
	if (!tk)
	{
		fprintf (stderr, "Cannot allocate termo instance\n");
		exit (EXIT_FAILURE);
	}

	termo_set_mouse_proto (tk, termo_guess_mouse_proto (tk));
	termo_set_mouse_tracking_mode (tk, TERMO_MOUSE_TRACKING_DRAG);

	// Set up curses for our drawing needs
	if (!initscr () || nonl () == ERR || curs_set (0) == ERR)
	{
		fprintf (stderr, "Cannot initialize curses\n");
		exit (EXIT_FAILURE);
	}

	app_context_t app;
	app_init (&app);
	app.tk = tk;

	init_palette (&app);
	update_canvas_for_screen (&app);
	redraw (&app);
	redraw_canvas (&app);

	termo_result_t ret;
	termo_key_t key;

	// We listen for mouse/key input and terminal resize events
	struct pollfd fds[2] =
	{
		{ .fd = STDIN_FILENO,    .events = POLLIN },
		{ .fd = g_winch_pipe[0], .events = POLLIN },
	};

	// Run a simple event loop with poll()
	int nextwait = -1;
	bool running = true;
	while (running)
	{
		if (!poll (fds, 2, nextwait))
			if (termo_getkey_force (tk, &key) == TERMO_RES_KEY)
				running &= on_key (&app, &key);

		if (fds[1].revents & (POLLIN | POLLHUP | POLLERR))
		{
			char x;
			read (fds[1].fd, &x, 1);

			// The "official" simple and flicker-prone method of resizing
			// the internal buffers of curses
			endwin ();
			refresh ();

			update_canvas_for_screen (&app);
			redraw (&app);
			redraw_canvas (&app);
		}
		if (fds[0].revents & (POLLIN | POLLHUP | POLLERR))
			termo_advisereadable (tk);

		while ((ret = termo_getkey (tk, &key)) == TERMO_RES_KEY)
			running &= on_key (&app, &key);

		nextwait = -1;
		if (ret == TERMO_RES_AGAIN)
			nextwait = termo_get_waittime (tk);
	}

	endwin ();
	termo_destroy (tk);
}