aboutsummaryrefslogtreecommitdiff
path: root/autistdraw.c
blob: 2d86f63773b2de043b7277cefe14ed113866d9aa (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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
/*
 * autistdraw.c: terminal drawing for NEET autists^Wartists
 *
 * Copyright (c) 2014, Přemysl Janouch <p.janouch@gmail.com>
 * All rights reserved.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <fcntl.h>
#include <signal.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>

#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif // ! NI_MAXHOST

#ifndef NI_MAXSERV
#define NI_MAXSERV 32
#endif // ! NI_MAXSERV

#include <termios.h>
#ifndef TIOCGWINSZ
#include <sys/ioctl.h>
#endif  // ! TIOCGWINSZ

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

#include "config.h"
#include "utils.c"

#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

#define PROTOCOL_VERSION    1           ///< Network protocol version

enum
{
	MESSAGE_HELLO,                      ///< Server/client hello
	MESSAGE_GET_BITMAP,                 ///< Request bitmap data
	MESSAGE_PUT_POINT,                  ///< Request to place a point

	MESSAGE_COUNT                       ///< Total number of messages
};

typedef enum network_mode network_mode_t;
enum network_mode
{
	NETWORK_MODE_STANDALONE,            ///< No networking taking place
	NETWORK_MODE_SERVER,                ///< We're the server
	NETWORK_MODE_CLIENT                 ///< We're a client
};

typedef struct client client_t;
struct client
{
	LIST_HEADER (client_t)

	int fd;                             ///< Client connection
	ev_io read_watcher;                 ///< Client readability watcher
	ev_io write_watcher;                ///< Client writability watcher
	struct msg_reader msg_reader;       ///< Client message reader
	write_queue_t write_queue;          ///< Write queue
};

#define BITMAP_PIXEL(app, x, y) (app)->bitmap[(y) * (app)->bitmap_w + (x)]

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

	ev_io tty_watcher;                  ///< TTY input watcher
	ev_timer tty_timer;                 ///< TTY timeout timer
	ev_signal winch_watcher;            ///< SIGWINCH watcher

	network_mode_t mode;                ///< Networking mode

	// Client:
	int server_fd;                      ///< Server connection
	ev_io server_read_watcher;          ///< Server readability watcher
	ev_io server_write_watcher;         ///< Server writability watcher
	struct msg_reader msg_reader;       ///< Server message reader
	write_queue_t write_queue;          ///< Server write queue

	bool no_wait;                       ///< Don't wait for server confirmations

	// Server:
	int listen_fd;                      ///< Listening FD
	ev_io listen_watcher;               ///< Listening FD watcher
	client_t *clients;                  ///< Client connections

	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 remove_client (app_context_t *app, client_t *client);
static void on_server_disconnected (app_context_t *app);

static void
app_init (app_context_t *self)
{
	memset (self, 0, sizeof *self);
	self->server_fd = -1;
	self->listen_fd = -1;
	msg_reader_init (&self->msg_reader);
	write_queue_init (&self->write_queue);
}

static void
app_free (app_context_t *self)
{
	if (self->tk)
		termo_destroy (self->tk);
	while (self->clients)
		// XXX: we probably shouldn't do this from here
		remove_client (self, self->clients);

	free (self->bitmap);
	msg_reader_free (&self->msg_reader);
	write_queue_free (&self->write_queue);
}

// --- Server-client messaging -------------------------------------------------

static bool
read_loop (EV_P_ ev_io *watcher,
	bool (*cb) (EV_P_ ev_io *, const void *, ssize_t))
{
	char buf[8192];
	while (true)
	{
		ssize_t n_read = recv (watcher->fd, buf, sizeof buf, 0);
		if (n_read < 0)
		{
			if (errno == EAGAIN)
				break;
			if (errno == EINTR)
				continue;
		}
		if (n_read <= 0 || !cb (EV_A_ watcher, buf, n_read))
			return false;
	}
	return true;
}

static bool
flush_queue (write_queue_t *queue, ev_io *watcher)
{
	struct iovec vec[queue->len], *vec_iter = vec;
	for (write_req_t *iter = queue->head; iter; iter = iter->next)
		*vec_iter++ = iter->data;

	ssize_t written;
again:
	written = writev (watcher->fd, vec, N_ELEMENTS (vec));
	if (written < 0)
	{
		if (errno == EAGAIN)
			goto skip;
		if (errno == EINTR)
			goto again;
		return false;
	}

	write_queue_processed (queue, written);

skip:
	if (write_queue_is_empty (queue))
		ev_io_stop (EV_DEFAULT_ watcher);
	else
		ev_io_start (EV_DEFAULT_ watcher);
	return true;
}

static write_req_t *
flush_writer (struct msg_writer *writer)
{
	write_req_t *req = xcalloc (1, sizeof *req);
	req->data.iov_base = msg_writer_flush (writer, &req->data.iov_len);
	return req;
}

static void
flush_writer_to_client (struct msg_writer *writer, client_t *client)
{
	write_queue_add (&client->write_queue, flush_writer (writer));
	ev_io_start (EV_DEFAULT_ &client->write_watcher);
}

static void
flush_writer_to_server (struct msg_writer *writer, app_context_t *app)
{
	write_queue_add (&app->write_queue, flush_writer (writer));
	ev_io_start (EV_DEFAULT_ &app->server_write_watcher);
}

static void
send_draw_point_response (client_t *client, int x, int y, uint8_t color)
{
	struct msg_writer writer;
	msg_writer_init (&writer);
	msg_writer_u8 (&writer, MESSAGE_PUT_POINT);
	msg_writer_i32 (&writer, x);
	msg_writer_i32 (&writer, y);
	msg_writer_u8 (&writer, color);

	flush_writer_to_client (&writer, client);
}

static void
send_draw_point_request (app_context_t *app, int x, int y, uint8_t color)
{
	struct msg_writer writer;
	msg_writer_init (&writer);
	msg_writer_u8 (&writer, MESSAGE_PUT_POINT);
	msg_writer_i32 (&writer, x);
	msg_writer_i32 (&writer, y);
	msg_writer_u8 (&writer, color);

	flush_writer_to_server (&writer, app);
}

static void
send_hello_request (app_context_t *app)
{
	struct msg_writer writer;
	msg_writer_init (&writer);
	msg_writer_u8 (&writer, MESSAGE_HELLO);
	msg_writer_u8 (&writer, PROTOCOL_VERSION);

	flush_writer_to_server (&writer, app);
}

static void
send_hello_response (client_t *client)
{
	struct msg_writer writer;
	msg_writer_init (&writer);
	msg_writer_u8 (&writer, MESSAGE_HELLO);
	msg_writer_u8 (&writer, PROTOCOL_VERSION);

	flush_writer_to_client (&writer, client);
}

static void
send_get_bitmap_request (app_context_t *app)
{
	struct msg_writer writer;
	msg_writer_init (&writer);
	msg_writer_u8 (&writer, MESSAGE_GET_BITMAP);

	flush_writer_to_server (&writer, app);
}

static void
send_get_bitmap_response (client_t *client, app_context_t *app)
{
	struct msg_writer writer;
	msg_writer_init (&writer);
	msg_writer_u8 (&writer, MESSAGE_GET_BITMAP);
	msg_writer_i32 (&writer, app->bitmap_x);
	msg_writer_i32 (&writer, app->bitmap_y);
	msg_writer_u64 (&writer, app->bitmap_w);
	msg_writer_u64 (&writer, app->bitmap_h);

	// Simple RLE compression
	size_t size = app->bitmap_w * app->bitmap_h;
	uint8_t last_value = 0, count = 0;
	for (size_t i = 0; i < size; i++)
	{
		uint8_t value = app->bitmap[i];
		if ((count && value != last_value) || count == 0xFF)
		{
			msg_writer_u8 (&writer, count);
			msg_writer_u8 (&writer, last_value);
			count = 0;
		}
		count++;
		last_value = value;
	}
	if (count)
	{
		msg_writer_u8 (&writer, count);
		msg_writer_u8 (&writer, last_value);
	}

	flush_writer_to_client (&writer, client);
}

// --- Server-client messaging -------------------------------------------------

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 = 0;
			if (is_in_bitmap_data (app, x, y))
				color = BITMAP_PIXEL (app,
					x - app->bitmap_x, y - app->bitmap_y);

			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 = xcalloc (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_internal (app_context_t *app, int x, int y, uint8_t color)
{
	make_place_for_point (app, x, y);
	BITMAP_PIXEL (app, x - app->bitmap_x, y - app->bitmap_y) = 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 void
draw_point (app_context_t *app, int x, int y, uint8_t color)
{
	if (app->mode == NETWORK_MODE_CLIENT)
	{
		send_draw_point_request (app, x, y, color);

		// We don't usually draw anything immediately in client mode,
		// instead we wait for confirmation from the server
		if (!app->no_wait)
			return;
	}

	draw_point_internal (app, x, y, color);

	// Broadcast clients about the event
	if (app->mode == NETWORK_MODE_SERVER)
		for (client_t *iter = app->clients; iter; iter = iter->next)
			send_draw_point_response (iter, x, y, color);
}

static void
draw_line (app_context_t *app, int x0, int x1, int y0, int y1, uint8_t color)
{
	// Integer version of Bresenham's line drawing algorithm,
	// loosely based on code from libcaca because screw math
	int dx = abs (x1 - x0);
	int dy = abs (y1 - y0);

	bool steep = dx < dy;
	if (steep)
	{
		// Flip the coordinate system on input
		int tmp;
		tmp = x0; x0 = y0; y0 = tmp;
		tmp = x1; x1 = y1; y1 = tmp;
		tmp = dx; dx = dy; dy = tmp;
	}

	int step_x = x0 > x1 ? -1 : 1;
	int step_y = y0 > y1 ? -1 : 1;

	int dpr = dy * 2;
	int delta = dpr - dx;
	int dpru = delta - dx;

	while (dx-- >= 0)
	{
		// Unflip the coordinate system on output
		if (steep)
			draw_point (app, y0, x0, color);
		else
			draw_point (app, x0, y0, color);

		x0 += step_x;
		if (delta > 0)
		{
			y0 += step_y;
			delta += dpru;
		}
		else
			delta += dpr;
	}
}

// --- Exports -----------------------------------------------------------------

static bool
is_data_row_empty (app_context_t *app, int y)
{
	for (size_t x = 0; x < app->bitmap_w; x++)
		if (app->bitmap[y * app->bitmap_w + x])
			return false;
	return true;
}

static bool
is_data_column_empty (app_context_t *app, int x)
{
	for (size_t y = 0; y < app->bitmap_h; y++)
		if (app->bitmap[y * app->bitmap_w + x])
			return false;
	return true;
}

static void
find_data_bounding_rect (app_context_t *app,
	size_t *x, size_t *y, size_t *w, size_t *h)
{
	size_t my_x = 0, my_y = 0;
	size_t my_w = app->bitmap_w, my_h = app->bitmap_h;
	size_t i;

	i = 0;
	while (i < app->bitmap_h && is_data_row_empty (app, i++))
		my_y++;

	// Special case: the whole canvas is empty
	if (my_y == my_h)
	{
		my_x = my_w;
		goto end;
	}

	i = app->bitmap_h;
	while (i-- && is_data_row_empty (app, i))
		my_h--;

	i = 0;
	while (i < app->bitmap_w && is_data_column_empty (app, i++))
		my_x++;

	i = app->bitmap_w;
	while (i-- && is_data_column_empty (app, i))
		my_w--;

end:
	*x = my_x;
	*y = my_y;
	*w = my_w - my_x;
	*h = my_h - my_y;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static const char *
color_to_ansi (uint8_t color)
{
	static const char *table[2 * PALETTE_WIDTH] =
	{
		"\033[0m",
		"\033[0;40m",
		"\033[0;41m",
		"\033[0;42m",
		"\033[0;43m",
		"\033[0;44m",
		"\033[0;45m",
		"\033[0;46m",
		"\033[0;47m",
		"\033[0;1;7m",
		"\033[0;1;7;30m",
		"\033[0;1;7;31m",
		"\033[0;1;7;32m",
		"\033[0;1;7;33m",
		"\033[0;1;7;34m",
		"\033[0;1;7;35m",
		"\033[0;1;7;36m",
		"\033[0;1;7;37m",
	};

	if (color >= sizeof table / sizeof table[0])
		return NULL;
	return table[color];
}

static void
export_ansi (app_context_t *app)
{
	FILE *fp = fopen ("export-ansi.asc", "wb");
	if (!fp)
	{
		display ("Error opening file for writing.");
		beep ();
		return;
	}

	size_t x, y, w, h;
	find_data_bounding_rect (app, &x, &y, &w, &h);

	for (size_t row = 0; row < h; row++)
	{
		const char *color = NULL;
		for (size_t column = 0; column < w; column++)
		{
			const char *new_color = color_to_ansi
				(BITMAP_PIXEL (app, x + column, y + row));
			if (color != new_color)
				fputs (new_color, fp);
			color = new_color;
			fputc (' ', fp);
		}

		// We need to reset the attributes
		fputs (color_to_ansi (0), fp);
		fputc ('\n', fp);
	}

	fclose (fp);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

enum
{
	MIRC_NONE        = -1,

	MIRC_WHITE       = 0,
	MIRC_BLACK       = 1,
	MIRC_BLUE        = 2,
	MIRC_GREEN       = 3,
	MIRC_L_RED       = 4,
	MIRC_RED         = 5,
	MIRC_PURPLE      = 6,
	MIRC_ORANGE      = 7,
	MIRC_YELLOW      = 8,
	MIRC_L_GREEN     = 9,
	MIRC_CYAN        = 10,
	MIRC_L_CYAN      = 11,
	MIRC_L_BLUE      = 12,
	MIRC_L_PURPLE    = 13,
	MIRC_GRAY        = 14,
	MIRC_L_GRAY      = 15,

	MIRC_TRANSPARENT = 99
};

static int
color_to_mirc (uint8_t color)
{
	static const int table[2 * PALETTE_WIDTH] =
	{
		// XXX: not sure what to map the default color pair to;
		//   the mIRC code for reverse colours seems to not be well supported
		MIRC_TRANSPARENT, MIRC_BLACK, MIRC_RED, MIRC_GREEN, MIRC_YELLOW,
		MIRC_BLUE, MIRC_PURPLE, MIRC_CYAN, MIRC_L_GRAY,
		MIRC_BLACK, MIRC_GRAY, MIRC_L_RED, MIRC_L_GREEN, MIRC_YELLOW,
		MIRC_L_BLUE, MIRC_L_PURPLE, MIRC_L_CYAN, MIRC_WHITE
	};

	if (color >= sizeof table / sizeof table[0])
		return MIRC_NONE;
	return table[color];
}

static void
export_irc (app_context_t *app)
{
	FILE *fp = fopen ("export-irc.asc", "wb");
	if (!fp)
	{
		display ("Error opening file for writing.");
		beep ();
		return;
	}

	size_t x, y, w, h;
	find_data_bounding_rect (app, &x, &y, &w, &h);

	// This is tricky and needs to be tested with major IRC clients.  Currently
	// works with: weechat 1.0, xchat 2.8.8, freenode's qwebirc.

	// We cannot use the same non-space character for transparent and opaque
	// pixels because many clients don't understand the transparent 99 colour
	// that is needed for the foreground of transparent pixels.  Therefore it
	// is not possible to display correctly using non-monospace fonts.

	for (size_t row = 0; row < h; row++)
	{
		// qwebirc is retarded and in some cases it reduces spaces, misaligning
		// the picture.  Appending two spaces after the attribute reset and
		// rendering opaque pixels as something different from a space seems
		// to prevent that behaviour.
		int color = MIRC_TRANSPARENT;
		fprintf (fp, "\x0f  ");

		for (size_t column = 0; column < w; column++)
		{
			int new_color = color_to_mirc
				(BITMAP_PIXEL (app, x + column, y + row));
			if (color != new_color)
			{
				color = new_color;
				if (color == MIRC_TRANSPARENT)
					fprintf (fp, "\x0f");
				else
					fprintf (fp, "\x03%02d,%02d", color, color);
			}
			fputc ("# "[color == MIRC_TRANSPARENT], fp);
		}
		fputc ('\n', fp);
	}

	fclose (fp);
}

// --- Loading, saving ---------------------------------------------------------

static void
load (app_context_t *app)
{
	// Client cannot load at all, the server would have send the new bitmap out
	if (app->mode != NETWORK_MODE_STANDALONE)
	{
		display ("Cannot load bitmaps in networked mode.");
		beep ();
		return;
	}

	FILE *fp = fopen ("drawing.bin", "rb");
	if (!fp)
	{
		display ("Error opening file for reading.");
		beep ();
		return;
	}

	// Some way of loading/saving is better than no way, let's just do our job.
	// The format neither standardised nor effective but it works for us.
	// We just eat everything and make sure to not crash.

	int x, y;
	size_t w, h;
	if (fscanf (fp, "%d %d %zu %zu", &x, &y, &w, &h) != 4)
		goto error;

	if (w && h > SIZE_MAX / w)
		goto error;
	size_t size = w * h;

	uint8_t *bitmap = calloc (size, sizeof *bitmap);
	if (!bitmap)
		goto error;

	int c;
	uint8_t pixel = 0;
	bool have_nibble = false;
	size_t loaded = 0;

	while (loaded < size && (c = fgetc (fp)) != EOF)
	{
		static const char digits[] = "0123456789abcdef";
		const char *value = strchr (digits, c);
		if (value && c != '\0')
		{
			pixel = pixel << 4 | (value - digits);
			if (have_nibble)
				bitmap[loaded++] = pixel;
			have_nibble = !have_nibble;
		}
	}

	free (app->bitmap);
	app->bitmap = bitmap;
	app->bitmap_h = h;  app->bitmap_x = x;
	app->bitmap_w = w;  app->bitmap_y = y;
	redraw_canvas (app);

error:
	fclose (fp);
}

static void
save (app_context_t *app)
{
	FILE *fp = fopen ("drawing.bin", "wb");
	if (!fp)
	{
		display ("Error opening file for writing.");
		return;
	}

	int x = app->bitmap_x, y = app->bitmap_y;
	size_t w = app->bitmap_w, h = app->bitmap_h;
	fprintf (fp, "%d %d %zu %zu\n", x, y, w, h);

	for (size_t row = 0; row < h; row++)
	{
		for (size_t column = 0; column < w; column++)
			fprintf (fp, "%02x", BITMAP_PIXEL (app, column, row));
		fputc ('\n', fp);
	}

	fclose (fp);
}

// --- Event handlers ----------------------------------------------------------

static void
move_canvas (app_context_t *app, int x, int y)
{
	app->corner_x += x;
	app->corner_y += y;

	app->center_x += x;
	app->center_y += y;

	redraw_canvas (app);
}

static void
on_mouse (app_context_t *app, termo_key_t *key)
{
	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;

	// Middle mouse button, or Ctrl + left mouse button, moves the canvas
	if (button == 2 || (button == 1 && key->modifiers == TERMO_KEYMOD_CTRL))
	{
		if (event == TERMO_MOUSE_DRAG)
			move_canvas (app,
				app->move_saved_x - screen_x,
				app->move_saved_y - screen_y);

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

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

	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)
	{
		if (event == TERMO_MOUSE_DRAG)
			draw_line (app,
				app->move_saved_x, canvas_x,
				app->move_saved_y, canvas_y,
				*color);
		else
			draw_point (app, canvas_x, canvas_y, *color);

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

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

		if (key->modifiers)
			return true;

		switch (key->code.sym)
		{
		case TERMO_SYM_UP:     move_canvas (app,  0, -1);  break;
		case TERMO_SYM_DOWN:   move_canvas (app,  0,  1);  break;
		case TERMO_SYM_LEFT:   move_canvas (app, -1,  0);  break;
		case TERMO_SYM_RIGHT:  move_canvas (app,  1,  0);  break;
		default:                                           break;
		}
		return true;
	}

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

		if (key->modifiers)
			return true;

		if (key->code.codepoint == 'l')  load (app);
		if (key->code.codepoint == 's')  save (app);
		if (key->code.codepoint == 'e')  export_ansi (app);
		if (key->code.codepoint == 'E')  export_irc (app);
		return true;
	}

	if (key->type == TERMO_TYPE_MOUSE)
		on_mouse (app, key);

	return true;
}

static void
on_winch (EV_P_ ev_signal *handle, int revents)
{
	app_context_t *app = ev_userdata (loop);
	(void) handle;
	(void) revents;

#if defined (HAVE_RESIZETERM) && defined (TIOCGWINSZ)
	struct winsize size;
	if (!ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &size))
	{
		char *row = getenv ("LINES");
		char *col = getenv ("COLUMNS");
		unsigned long tmp;
		resizeterm (
			(row && xstrtoul (&tmp, row, 10)) ? (int) tmp : size.ws_row,
			(col && xstrtoul (&tmp, col, 10)) ? (int) tmp : size.ws_col);
	}
#else  // ! HAVE_RESIZETERM || ! TIOCGWINSZ
	endwin ();
	refresh ();
#endif  // ! HAVE_RESIZETERM || ! TIOCGWINSZ

	update_canvas_for_screen (app);
	redraw (app);
	redraw_canvas (app);
}

static void
on_key_timer (EV_P_ ev_timer *handle, int revents)
{
	app_context_t *app = ev_userdata (loop);
	(void) handle;
	(void) revents;

	termo_key_t key;
	if (termo_getkey_force (app->tk, &key) == TERMO_RES_KEY)
		if (!on_key (app, &key))
			ev_break (EV_A_ EVBREAK_ONE);
}

static void
on_tty_readable (EV_P_ ev_io *handle, int revents)
{
	// Ignoring and hoping for the best
	(void) handle;
	(void) revents;

	app_context_t *app = ev_userdata (loop);

	ev_timer_stop (EV_A_ &app->tty_timer);
	termo_advisereadable (app->tk);

	termo_key_t key;
	termo_result_t ret;
	while ((ret = termo_getkey (app->tk, &key)) == TERMO_RES_KEY)
		if (!on_key (app, &key))
			ev_break (EV_A_ EVBREAK_ONE);

	if (ret == TERMO_RES_AGAIN)
		ev_timer_start (EV_A_ &app->tty_timer);
}

// --- Client-specific stuff ---------------------------------------------------

typedef bool (*server_handler_fn) (app_context_t *, struct msg_unpacker *);

static void
on_server_disconnected (app_context_t *app)
{
	write_queue_free (&app->write_queue);
	write_queue_init (&app->write_queue);

	ev_io_stop (EV_DEFAULT_ &app->server_read_watcher);
	ev_io_stop (EV_DEFAULT_ &app->server_write_watcher);
	xclose (app->server_fd);
	app->server_fd = -1;

	display ("Disconnected!");
	beep ();  // Beep beep!  Made a boo-boo.

	// Let the user save the picture at least.
	// Also prevents us from trying to use the dead server handle.
	app->mode = NETWORK_MODE_STANDALONE;
}

static bool
on_server_hello (app_context_t *app, struct msg_unpacker *unpacker)
{
	(void) app;

	uint8_t version;
	if (!msg_unpacker_u8 (unpacker, &version))
		return false;  // Not enough data
	if (version != PROTOCOL_VERSION)
		return false;  // Incompatible version
	return true;
}

static bool
on_server_get_bitmap (app_context_t *app, struct msg_unpacker *unpacker)
{
	int32_t x, y;
	uint64_t w, h;
	if (!msg_unpacker_i32 (unpacker, &x)
	 || !msg_unpacker_i32 (unpacker, &y)
	 || !msg_unpacker_u64 (unpacker, &w)
	 || !msg_unpacker_u64 (unpacker, &h))
		return false;  // Not enough data

	size_t size = w * h;
	if ((h && w > SIZE_MAX / h) || w > SIZE_MAX || h > SIZE_MAX)
		return false;  // The server is flooding us

	uint8_t *bitmap = xcalloc (size, sizeof *app->bitmap);

	// RLE decompression
	size_t i = 0;
	uint8_t len, value;
	while (msg_unpacker_u8 (unpacker, &len)
		&& msg_unpacker_u8 (unpacker, &value))
	{
		// Don't allow overflow
		if (i + len > size || i + len < i)
			break;
		for (size_t x = 0; x < len; x++)
			bitmap[i++] = value;
	}

	free (app->bitmap);
	app->bitmap = bitmap;
	app->bitmap_x = x;
	app->bitmap_y = y;
	app->bitmap_w = w;
	app->bitmap_h = h;

	redraw_canvas (app);
	return true;
}

static bool
on_server_put_point (app_context_t *app, struct msg_unpacker *unpacker)
{
	int32_t x, y;
	uint8_t color;

	if (!msg_unpacker_i32 (unpacker, &x)
	 || !msg_unpacker_i32 (unpacker, &y)
	 || !msg_unpacker_u8 (unpacker, &color))
		return false;  // Not enough data

	// Either a confirmation of our own request, or an event notification;
	// let's just put the pixel in place without further ado
	draw_point_internal (app, x, y, color);
	return true;
}

static bool
on_server_data (EV_P_ ev_io *watcher, const void *buf, ssize_t n_read)
{
	app_context_t *app = ev_userdata (loop);
	(void) watcher;

	msg_reader_feed (&app->msg_reader, buf, n_read);

	static const server_handler_fn handlers[MESSAGE_COUNT] =
	{
		[MESSAGE_HELLO]      = on_server_hello,
		[MESSAGE_GET_BITMAP] = on_server_get_bitmap,
		[MESSAGE_PUT_POINT]  = on_server_put_point,
	};

	void *msg;
	size_t len;
	while ((msg = msg_reader_get (&app->msg_reader, &len)))
	{
		struct msg_unpacker unpacker;
		msg_unpacker_init (&unpacker, msg, len);

		uint8_t type;
		if (!msg_unpacker_u8 (&unpacker, &type)
		 || type >= MESSAGE_COUNT)
			return false;  // Unknown message

		server_handler_fn handler = handlers[type];
		if (!handler)
			return false;  // Unknown message
		if (!handler (app, &unpacker))
			return false;  // Invalid message
		if (msg_unpacker_get_available (&unpacker) > 0)
			return false;  // Overlong message
	}
	return true;
}

static void
on_server_ready (EV_P_ ev_io *watcher, int revents)
{
	app_context_t *app = ev_userdata (loop);

	if (revents & EV_READ)
		if (!read_loop (EV_A_ watcher, on_server_data))
			goto error;
	if (revents & EV_WRITE)
		if (!flush_queue (&app->write_queue, watcher))
			goto error;
	return;

error:
	on_server_disconnected (app);
}

// --- Server-specific stuff ---------------------------------------------------

typedef bool (*client_handler_fn)
	(app_context_t *, client_t *, struct msg_unpacker *);

static void
remove_client (app_context_t *app, client_t *client)
{
	ev_io_stop (EV_DEFAULT_ &client->read_watcher);
	ev_io_stop (EV_DEFAULT_ &client->write_watcher);
	xclose (client->fd);
	msg_reader_free (&client->msg_reader);
	write_queue_free (&client->write_queue);
	LIST_UNLINK (app->clients, client);
	free (client);
}

static bool
on_client_hello (app_context_t *app, client_t *client,
	struct msg_unpacker *unpacker)
{
	(void) app;

	uint8_t version;
	if (!msg_unpacker_u8 (unpacker, &version)
	 || version != PROTOCOL_VERSION)
		// Nope, I don't like you
		return false;

	send_hello_response (client);
	return true;
}

static bool
on_client_get_bitmap (app_context_t *app, client_t *client,
	struct msg_unpacker *unpacker)
{
	(void) unpacker;

	send_get_bitmap_response (client, app);
	return true;
}

static bool
on_client_put_point (app_context_t *app, client_t *client,
	struct msg_unpacker *unpacker)
{
	(void) client;

	int32_t x, y;
	uint8_t color;
	if (!msg_unpacker_i32 (unpacker, &x)
	 || !msg_unpacker_i32 (unpacker, &y)
	 || !msg_unpacker_u8 (unpacker, &color))
		return false;

	// The function takes care of broadcasting to all the other clients,
	// as well as back to the original sender
	draw_point (app, x, y, color);
	return true;
}

static bool
on_client_data (EV_P_ ev_io *watcher, const void *buf, ssize_t n_read)
{
	app_context_t *app = ev_userdata (loop);
	client_t *client = watcher->data;

	msg_reader_feed (&client->msg_reader, buf, n_read);

	static const client_handler_fn handlers[MESSAGE_COUNT] =
	{
		[MESSAGE_HELLO]      = on_client_hello,
		[MESSAGE_GET_BITMAP] = on_client_get_bitmap,
		[MESSAGE_PUT_POINT]  = on_client_put_point,
	};

	void *msg;
	size_t len;
	while ((msg = msg_reader_get (&client->msg_reader, &len)))
	{
		struct msg_unpacker unpacker;
		msg_unpacker_init (&unpacker, msg, len);

		uint8_t type;
		if (!msg_unpacker_u8 (&unpacker, &type))
			return false;  // Invalid message
		if (type >= MESSAGE_COUNT)
			return false;  // Unknown message

		client_handler_fn handler = handlers[type];
		if (!handler)
			return false;  // Unknown message
		if (!handler (app, client, &unpacker))
			return false;  // Invalid message
		if (msg_unpacker_get_available (&unpacker) > 0)
			return false;  // Overlong message data
	}
	return true;
}

static void
on_client_ready (EV_P_ ev_io *watcher, int revents)
{
	app_context_t *app = ev_userdata (loop);
	client_t *client = watcher->data;

	if (revents & EV_READ)
		if (!read_loop (EV_A_ watcher, on_client_data))
			goto error;
	if (revents & EV_WRITE)
		if (!flush_queue (&client->write_queue, watcher))
			goto error;
	return;

error:
	remove_client (app, client);
}

static void
on_new_client (EV_P_ ev_io *watcher, int revents)
{
	app_context_t *app = ev_userdata (loop);
	(void) revents;

	while (true)
	{
		int sock_fd = accept (watcher->fd, NULL, NULL);
		if (sock_fd == -1)
		{
			if (errno == EAGAIN)
				break;
			if (errno == EINTR
			 || errno == ECONNABORTED)
				continue;

			// Stop accepting connections to prevent busy looping
			// TODO: indicate the error to the user
			ev_io_stop (EV_A_ watcher);
			break;
		}

		client_t *client = xcalloc (1, sizeof *client);
		client->fd = sock_fd;
		msg_reader_init (&client->msg_reader);
		write_queue_init (&client->write_queue);

		set_blocking (sock_fd, false);
		ev_io_init (&client->read_watcher,  on_client_ready, sock_fd, EV_READ);
		ev_io_init (&client->write_watcher, on_client_ready, sock_fd, EV_WRITE);
		client->read_watcher.data = client;
		client->write_watcher.data = client;

		// We're only interested in reading as the write queue is empty now
		ev_io_start (EV_A_ &client->read_watcher);

		LIST_PREPEND (app->clients, client);
	}
}

// --- Program startup ---------------------------------------------------------

typedef struct app_options app_options_t;
struct app_options
{
	struct addrinfo *client_address;    ///< Address to connect to
	struct addrinfo *server_address;    ///< Address to listen at
	bool no_wait;                       ///< Don't wait for server confirmations
};

static void
app_options_init (app_options_t *self)
{
	memset (self, 0, sizeof *self);
}

static void
app_options_free (app_options_t *self)
{
	if (self->client_address)  freeaddrinfo (self->client_address);
	if (self->server_address)  freeaddrinfo (self->server_address);
}

static struct addrinfo *
parse_address (const char *address, int flags)
{
	char address_copy[strlen (address) + 1];
	strcpy (address_copy, address);

	char *colon = strrchr (address_copy, ':');
	if (!colon)
	{
		fprintf (stderr, "error: no port number specified in `%s'\n", address);
		return false;
	}

	char *host = address_copy, *service = colon + 1;

	if (host == colon)
		host = NULL;
	else if (host < colon && *host == '[' && colon[-1] == ']')
	{
		// Remove IPv6 RFC 2732-style [] brackets from the host, if present.
		// This also makes it possible to take the usage string literally. :))
		host++;
		colon[-1] = '\0';
	}
	else
		*colon = '\0';

	struct addrinfo *result, hints =
	{
		.ai_socktype = SOCK_STREAM,
		.ai_protocol = IPPROTO_TCP,
		.ai_flags = flags,
	};
	int err = getaddrinfo (host, service, &hints, &result);
	if (err)
	{
		fprintf (stderr, "error: cannot resolve `%s', port `%s': %s\n",
			host, service, gai_strerror (err));
		return false;
	}
	return result;
}

static void
parse_program_arguments (app_options_t *options, int argc, char **argv)
{
	static const struct opt opts[] =
	{
		{ 'h', "help", NULL, 0, "display this help and exit" },
		{ 'V', "version", NULL, 0, "output version information and exit" },
		{ 's', "server", "[ADDRESS]:PORT", 0, "start a server" },
		{ 'c', "client", "[ADDRESS]:PORT", 0, "connect to a server" },
		{ 'n', "no-wait", NULL, OPT_LONG_ONLY,
		  "don't wait for server confirmations" },
		{ 0, NULL, NULL, 0, NULL }
	};

	struct opt_handler oh;
	opt_handler_init (&oh, argc, argv, opts,
		NULL, "Terminal drawing for NEET autists^Wartists");

	int c;
	while ((c = opt_handler_get (&oh)) != -1)
	switch (c)
	{
	case 'h':
		opt_handler_usage (&oh, stdout);
		exit (EXIT_SUCCESS);
	case 'V':
		printf (PROJECT_NAME " " PROJECT_VERSION "\n");
		exit (EXIT_SUCCESS);
	case 's':
		if (options->server_address)
		{
			fprintf (stderr, "%s: %s\n",
				"error", "cannot specify multiple listening addresses");
			exit (EXIT_FAILURE);
		}
		if (!(options->server_address = parse_address (optarg, AI_PASSIVE)))
			exit (EXIT_FAILURE);
		break;
	case 'c':
		if (options->client_address)
		{
			fprintf (stderr, "%s: %s\n",
				"error", "cannot specify multiple addresses to connect to");
			exit (EXIT_FAILURE);
		}
		if (!(options->client_address = parse_address (optarg, 0)))
			exit (EXIT_FAILURE);
		break;
	case 'n':
		options->no_wait = true;
		break;
	default:
		fprintf (stderr, "%s: %s\n", "error", "wrong options");
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}

	if (options->client_address && options->server_address)
	{
		fprintf (stderr, "%s: %s\n",
			"error", "cannot be both a server and a client");
		exit (EXIT_FAILURE);
	}

	argc -= optind;
	argv += optind;

	if (argc)
	{
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}

	opt_handler_free (&oh);
}

static void
initialize_client (app_context_t *app, struct addrinfo *address)
{
	app->mode = NETWORK_MODE_CLIENT;

	int sock_fd, err;
	for (; address; address = address->ai_next)
	{
		sock_fd = socket (address->ai_family,
			address->ai_socktype, address->ai_protocol);
		if (sock_fd == -1)
			continue;

		char host_buf[NI_MAXHOST], serv_buf[NI_MAXSERV];
		err = getnameinfo (address->ai_addr, address->ai_addrlen,
			host_buf, sizeof host_buf, serv_buf, sizeof serv_buf,
			NI_NUMERICHOST | NI_NUMERICSERV);
		if (err)
		{
			fprintf (stderr, "%s: %s: %s\n",
				"error", "getnameinfo", gai_strerror (err));
			fprintf (stderr, "connecting...\n");
		}
		else
		{
			char *x = format_host_port_pair (host_buf, serv_buf);
			fprintf (stderr, "connecting to %s...\n", x);
			free (x);
		}

		if (!connect (sock_fd, address->ai_addr, address->ai_addrlen))
			break;

		xclose (sock_fd);
	}

	if (!address)
	{
		fprintf (stderr, "%s: %s\n", "error", "connection failed");
		exit (EXIT_FAILURE);
	}

	int yes = 1;
	(void) setsockopt (sock_fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof yes);

	set_blocking (sock_fd, false);
	app->server_fd = sock_fd;
	ev_io_init (&app->server_read_watcher,  on_server_ready, sock_fd, EV_READ);
	ev_io_init (&app->server_write_watcher, on_server_ready, sock_fd, EV_WRITE);

	// We're only interested in reading as the write queue is empty now
	ev_io_start (EV_DEFAULT_ &app->server_read_watcher);

	send_hello_request (app);
	send_get_bitmap_request (app);
}

static void
initialize_server (app_context_t *app, struct addrinfo *address)
{
	app->mode = NETWORK_MODE_SERVER;

	int sock_fd = socket (address->ai_family,
		address->ai_socktype, address->ai_protocol);
	if (sock_fd == -1)
		goto fail_socket;

	if (bind (sock_fd, address->ai_addr, address->ai_addrlen)
	 || listen (sock_fd, 10))
		goto fail;

	int yes = 1;
	(void) setsockopt (sock_fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof yes);
	(void) setsockopt (sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);

	set_blocking (sock_fd, false);
	app->listen_fd = sock_fd;
	ev_io_init (&app->listen_watcher, on_new_client, sock_fd, EV_READ);
	ev_io_start (EV_DEFAULT_ &app->listen_watcher);
	return;

fail:
	xclose (sock_fd);
fail_socket:
	fprintf (stderr, "%s: %s: %s\n",
		"error", "initialization failed", strerror (errno));
	exit (EXIT_FAILURE);
}

int
main (int argc, char *argv[])
{
	TERMO_CHECK_VERSION;
	setlocale (LC_CTYPE, "");

	app_context_t app;
	app_init (&app);

	struct ev_loop *loop = EV_DEFAULT;
	if (!loop)
	{
		fprintf (stderr, "%s: %s\n", "error", "cannot initialize libev");
		exit (EXIT_FAILURE);
	}

	app_options_t options;
	app_options_init (&options);
	parse_program_arguments (&options, argc, argv);

	if      (options.client_address)
		initialize_client (&app, options.client_address);
	else if (options.server_address)
		initialize_server (&app, options.server_address);
	else
		app.mode = NETWORK_MODE_STANDALONE;

	app.no_wait = options.no_wait;
	app_options_free (&options);

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

	app.tk = 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, "%s: %s\n", "error", "cannot initialize curses");
		exit (EXIT_FAILURE);
	}

	ev_set_userdata (loop, &app);

	ev_signal_init (&app.winch_watcher, on_winch, SIGWINCH);
	ev_signal_start (EV_DEFAULT_ &app.winch_watcher);

	ev_io_init (&app.tty_watcher, on_tty_readable, STDIN_FILENO, EV_READ);
	ev_io_start (EV_DEFAULT_ &app.tty_watcher);

	ev_timer_init (&app.tty_timer, on_key_timer,
		termo_get_waittime (app.tk) / 1000., 0);

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

	ev_run (loop, 0);
	endwin ();

	app_free (&app);
	ev_loop_destroy (loop);
	return 0;
}