summaryrefslogtreecommitdiff
path: root/clients/terminal.c
blob: 60da93af365a95521acd95d0a088646b6313b43f (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
/*
 * Copyright © 2008 Kristian Høgsberg
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that copyright
 * notice and this permission notice appear in supporting documentation, and
 * that the name of the copyright holders not be used in advertising or
 * publicity pertaining to distribution of the software without specific,
 * written prior permission.  The copyright holders make no representations
 * about the suitability of this software for any purpose.  It is provided "as
 * is" without express or implied warranty.
 *
 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, 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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <pty.h>
#include <ctype.h>
#include <cairo.h>
#include <glib.h>

#include <X11/keysym.h>

#include "wayland-util.h"
#include "wayland-client.h"
#include "wayland-glib.h"

#include "window.h"

static int option_fullscreen;

#define MOD_SHIFT	0x01
#define MOD_ALT		0x02
#define MOD_CTRL	0x04

#define ATTRMASK_BOLD		0x01
#define ATTRMASK_UNDERLINE	0x02
#define ATTRMASK_BLINK		0x04
#define ATTRMASK_INVERSE	0x08

/* Buffer sizes */
#define MAX_RESPONSE		11
#define MAX_ESCAPE		64

/* Terminal modes */
#define MODE_SHOW_CURSOR	0x00000001
#define MODE_INVERSE		0x00000002
#define MODE_AUTOWRAP		0x00000004
#define MODE_AUTOREPEAT		0x00000008
#define MODE_LF_NEWLINE		0x00000010

union utf8_char {
	unsigned char byte[4];
	uint32_t ch;
};

enum utf8_state {
	utf8state_start,
	utf8state_accept,
	utf8state_reject,
	utf8state_expect3,
	utf8state_expect2,
	utf8state_expect1
};

struct utf8_state_machine {
	enum utf8_state state;
	int len;
	union utf8_char s;
};

static void
init_state_machine(struct utf8_state_machine *machine)
{
	machine->state = utf8state_start;
	machine->len = 0;
	machine->s.ch = 0;
}

static enum utf8_state
utf8_next_char(struct utf8_state_machine *machine, char c)
{
	switch(machine->state) {
	case utf8state_start:
	case utf8state_accept:
	case utf8state_reject:
		machine->s.ch = 0;
		machine->len = 0;
		if(c == 0xC0 || c == 0xC1) {
			/* overlong encoding, reject */
			machine->state = utf8state_reject;
		} else if((c & 0x80) == 0) {
			/* single byte, accept */
			machine->s.byte[machine->len++] = c;
			machine->state = utf8state_accept;
		} else if((c & 0xC0) == 0x80) {
			/* parser out of sync, ignore byte */
			machine->state = utf8state_start;
		} else if((c & 0xE0) == 0xC0) {
			/* start of two byte sequence */
			machine->s.byte[machine->len++] = c;
			machine->state = utf8state_expect1;
		} else if((c & 0xF0) == 0xE0) {
			/* start of three byte sequence */
			machine->s.byte[machine->len++] = c;
			machine->state = utf8state_expect2;
		} else if((c & 0xF8) == 0xF0) {
			/* start of four byte sequence */
			machine->s.byte[machine->len++] = c;
			machine->state = utf8state_expect3;
		} else {
			/* overlong encoding, reject */
			machine->state = utf8state_reject;
		}
		break;
	case utf8state_expect3:
		machine->s.byte[machine->len++] = c;
		if((c & 0xC0) == 0x80) {
			/* all good, continue */
			machine->state = utf8state_expect2;
		} else {
			/* missing extra byte, reject */
			machine->state = utf8state_reject;
		}
		break;
	case utf8state_expect2:
		machine->s.byte[machine->len++] = c;
		if((c & 0xC0) == 0x80) {
			/* all good, continue */
			machine->state = utf8state_expect1;
		} else {
			/* missing extra byte, reject */
			machine->state = utf8state_reject;
		}
		break;
	case utf8state_expect1:
		machine->s.byte[machine->len++] = c;
		if((c & 0xC0) == 0x80) {
			/* all good, accept */
			machine->state = utf8state_accept;
		} else {
			/* missing extra byte, reject */
			machine->state = utf8state_reject;
		}
		break;
	default:
		machine->state = utf8state_reject;
		break;
	}
	
	return machine->state;
}

struct terminal_color { double r, g, b, a; };
struct attr {
	unsigned char fg, bg;
	char a;        /* attributes format:
	                * 76543210
			*     ilub */
	char r;        /* reserved */
};
struct color_scheme {
	struct terminal_color palette[16];
	struct terminal_color border;
	struct attr default_attr;
};

static void
attr_init(struct attr *data_attr, struct attr attr, int n)
{
	int i;
	for (i = 0; i < n; i++) {
		data_attr[i] = attr;
	}
}

struct terminal {
	struct window *window;
	struct display *display;
	union utf8_char *data;
	char *tab_ruler;
	struct attr *data_attr;
	struct attr curr_attr;
	uint32_t mode;
	char origin_mode;
	char saved_origin_mode;
	struct attr saved_attr;
	union utf8_char last_char;
	int margin_top, margin_bottom;
	int data_pitch, attr_pitch;  /* The width in bytes of a line */
	int width, height, start, row, column;
	int saved_row, saved_column;
	int fd, master;
	GIOChannel *channel;
	uint32_t modifiers;
	char escape[MAX_ESCAPE];
	int escape_length;
	int state;
	int qmark_flag;
	struct utf8_state_machine state_machine;
	int margin;
	int fullscreen;
	int focused;
	struct color_scheme *color_scheme;
	struct terminal_color color_table[256];
	cairo_font_extents_t extents;
	cairo_font_face_t *font_normal, *font_bold;
};

/* Create default tab stops, every 8 characters */
static void
terminal_init_tabs(struct terminal *terminal)
{
	int i = 0;
	
	while (i < terminal->width) {
		if (i % 8 == 0)
			terminal->tab_ruler[i] = 1;
		else
			terminal->tab_ruler[i] = 0;
		i++;
	}
}

static void
terminal_init(struct terminal *terminal)
{
	terminal->curr_attr = terminal->color_scheme->default_attr;
	terminal->origin_mode = 0;
	terminal->mode = MODE_SHOW_CURSOR |
			 MODE_AUTOREPEAT |
			 MODE_AUTOWRAP;

	terminal->row = 0;
	terminal->column = 0;

	terminal->saved_attr = terminal->curr_attr;
	terminal->saved_origin_mode = terminal->origin_mode;
	terminal->saved_row = terminal->row;
	terminal->saved_column = terminal->column;

	if (terminal->tab_ruler != NULL) terminal_init_tabs(terminal);
}

static void
init_color_table(struct terminal *terminal)
{
	int c, r;
	struct terminal_color *color_table = terminal->color_table;

	for (c = 0; c < 256; c ++) {
		if (c < 16) {
			color_table[c] = terminal->color_scheme->palette[c];
		} else if (c < 232) {
			r = c - 16;
			color_table[c].b = ((double)(r % 6) / 6.0); r /= 6;
			color_table[c].g = ((double)(r % 6) / 6.0); r /= 6;
			color_table[c].r = ((double)(r % 6) / 6.0);
			color_table[c].a = 1.0;
		} else {
			r = (c - 232) * 10 + 8;
			color_table[c].r = ((double) r) / 256.0;
			color_table[c].g = color_table[c].r;
			color_table[c].b = color_table[c].r;
			color_table[c].a = 1.0;
		}
	}
}

static union utf8_char *
terminal_get_row(struct terminal *terminal, int row)
{
	int index;

	index = (row + terminal->start) % terminal->height;

	return &terminal->data[index * terminal->width];
}

static struct attr*
terminal_get_attr_row(struct terminal *terminal, int row) {
	int index;

	index = (row + terminal->start) % terminal->height;

	return &terminal->data_attr[index * terminal->width];
}

static struct attr
terminal_get_attr(struct terminal *terminal, int row, int col) {
	return terminal_get_attr_row(terminal, row)[col];
}

static void
terminal_scroll_buffer(struct terminal *terminal, int d)
{
	int i;

	d = d % (terminal->height + 1);
	terminal->start = (terminal->start + d) % terminal->height;
	if (terminal->start < 0) terminal->start = terminal->height + terminal->start;
	if(d < 0) {
		d = 0 - d;
		for(i = 0; i < d; i++) {
			memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
			attr_init(terminal_get_attr_row(terminal, i),
			    terminal->curr_attr, terminal->width);
		}
	} else {
		for(i = terminal->height - d; i < terminal->height; i++) {
			memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
			attr_init(terminal_get_attr_row(terminal, i),
			    terminal->curr_attr, terminal->width);
		}
	}
}

static void
terminal_scroll_window(struct terminal *terminal, int d)
{
	int i;
	int window_height;
	int from_row, to_row;
	struct attr *dup_attr;
	
	// scrolling range is inclusive
	window_height = terminal->margin_bottom - terminal->margin_top + 1;
	d = d % (window_height + 1);
	if(d < 0) {
		d = 0 - d;
		to_row = terminal->margin_bottom;
		from_row = terminal->margin_bottom - d;
		
		for (i = 0; i < (window_height - d); i++) {
			memcpy(terminal_get_row(terminal, to_row - i),
			       terminal_get_row(terminal, from_row - i),
			       terminal->data_pitch);
			memcpy(terminal_get_attr_row(terminal, to_row - i),
			       terminal_get_attr_row(terminal, from_row - i),
			       terminal->attr_pitch);
		}
		dup_attr = terminal_get_attr_row(terminal, terminal->margin_top);
		for (i = terminal->margin_top; i < (terminal->margin_top + d); i++) {
			memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
			if (i > terminal->margin_top) {
				memcpy(terminal_get_attr_row(terminal, i),
				       dup_attr, terminal->attr_pitch);
			}
		}
	} else {
		to_row = terminal->margin_top;
		from_row = terminal->margin_top + d;
		
		for (i = 0; i < (window_height - d); i++) {
			memcpy(terminal_get_row(terminal, to_row + i),
			       terminal_get_row(terminal, from_row + i),
			       terminal->data_pitch);
			memcpy(terminal_get_attr_row(terminal, to_row + i),
			       terminal_get_attr_row(terminal, from_row + i),
			       terminal->attr_pitch);
		}
		dup_attr = terminal_get_attr_row(terminal, terminal->margin_bottom);
		for (i = terminal->margin_bottom - d + 1; i <= terminal->margin_bottom; i++) {
			memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
			if (i < terminal->margin_bottom) {
				memcpy(terminal_get_attr_row(terminal, i),
				       dup_attr, terminal->attr_pitch);
			}
		}
	}
}

static void
terminal_scroll(struct terminal *terminal, int d)
{
	if(terminal->margin_top == 0 && terminal->margin_bottom == terminal->height - 1)
		terminal_scroll_buffer(terminal, d);
	else
		terminal_scroll_window(terminal, d);
}

static void
terminal_resize(struct terminal *terminal, int width, int height)
{
	size_t size;
	union utf8_char *data;
	struct attr *data_attr;
	char *tab_ruler;
	int data_pitch, attr_pitch;
	int i, l, total_rows, start;
	struct rectangle rectangle;
	struct winsize ws;

	if (terminal->width == width && terminal->height == height)
		return;

	data_pitch = width * sizeof(union utf8_char);
	size = data_pitch * height;
	data = malloc(size);
	attr_pitch = width * sizeof(struct attr);
	data_attr = malloc(attr_pitch * height);
	tab_ruler = malloc(width);
	memset(data, 0, size);
	memset(tab_ruler, 0, width);
	attr_init(data_attr, terminal->curr_attr, width * height);
	if (terminal->data && terminal->data_attr) {
		if (width > terminal->width)
			l = terminal->width;
		else
			l = width;

		if (terminal->height > height) {
			total_rows = height;
			start = terminal->height - height;
		} else {
			total_rows = terminal->height;
			start = 0;
		}

		for (i = 0; i < total_rows; i++) {
			memcpy(&data[width * i],
			       terminal_get_row(terminal, i),
			       l * sizeof(union utf8_char));
			memcpy(&data_attr[width * i],
			       terminal_get_attr_row(terminal, i),
			       l * sizeof(struct attr));
		}

		free(terminal->data);
		free(terminal->data_attr);
		free(terminal->tab_ruler);
	}

	terminal->data_pitch = data_pitch;
	terminal->attr_pitch = attr_pitch;
	terminal->width = width;
	terminal->height = height;
	if(terminal->margin_bottom >= terminal->height)
		terminal->margin_bottom = terminal->height - 1;
	terminal->data = data;
	terminal->data_attr = data_attr;
	terminal->tab_ruler = tab_ruler;
	terminal_init_tabs(terminal);

	if (terminal->row >= terminal->height)
		terminal->row = terminal->height - 1;
	if (terminal->column >= terminal->width)
		terminal->column = terminal->width - 1;
	terminal->start = 0;
	
	if (!terminal->fullscreen) {
		rectangle.width = terminal->width *
			terminal->extents.max_x_advance + 2 * terminal->margin;
		rectangle.height = terminal->height *
			terminal->extents.height + 2 * terminal->margin;
		window_set_child_size(terminal->window, &rectangle);
	}

	/* Update the window size */
	ws.ws_row = terminal->height;
	ws.ws_col = terminal->width;
	window_get_child_rectangle(terminal->window, &rectangle);
	ws.ws_xpixel = rectangle.width;
	ws.ws_ypixel = rectangle.height;
	ioctl(terminal->master, TIOCSWINSZ, &ws);
}

struct color_scheme DEFAULT_COLORS = {
	{
		{0,    0,    0,    1}, /* black */
		{0.66, 0,    0,    1}, /* red */
		{0  ,  0.66, 0,    1}, /* green */
		{0.66, 0.33, 0,    1}, /* orange (nicer than muddy yellow) */
		{0  ,  0  ,  0.66, 1}, /* blue */
		{0.66, 0  ,  0.66, 1}, /* magenta */
		{0,    0.66, 0.66, 1}, /* cyan */
		{0.66, 0.66, 0.66, 1}, /* light grey */
		{0.22, 0.33, 0.33, 1}, /* dark grey */
		{1,    0.33, 0.33, 1}, /* high red */
		{0.33, 1,    0.33, 1}, /* high green */
		{1,    1,    0.33, 1}, /* high yellow */
		{0.33, 0.33, 1,    1}, /* high blue */
		{1,    0.33, 1,    1}, /* high magenta */
		{0.33, 1,    1,    1}, /* high cyan */
		{1,    1,    1,    1}  /* white */
	},
	{0, 0, 0, 1},                  /* black border */
	{7, 0, 0, }                    /* bg:black (0), fg:light gray (7)  */
};

static void
terminal_draw_contents(struct terminal *terminal)
{
	struct rectangle rectangle;
	cairo_t *cr;
	cairo_font_extents_t extents;
	int top_margin, side_margin;
	int row, col;
	struct attr attr;
	union utf8_char *p_row;
	struct utf8_chars {
		union utf8_char c;
		char null;
	} toShow;
	int foreground, background, bold, underline, tmp;
	int text_x, text_y;
	cairo_surface_t *surface;
	double d;

	toShow.null = 0;

	window_get_child_rectangle(terminal->window, &rectangle);

	surface = display_create_surface(terminal->display, &rectangle);
	cr = cairo_create(surface);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_set_source_rgba(cr,
			      terminal->color_scheme->border.r,
			      terminal->color_scheme->border.g,
			      terminal->color_scheme->border.b,
			      terminal->color_scheme->border.a);
	cairo_paint(cr);
	cairo_set_operator(cr, CAIRO_OPERATOR_OVER);

	cairo_set_font_face(cr, terminal->font_normal);
	cairo_set_font_size(cr, 14);

	cairo_font_extents(cr, &extents);
	side_margin = (rectangle.width - terminal->width * extents.max_x_advance) / 2;
	top_margin = (rectangle.height - terminal->height * extents.height) / 2;

	cairo_set_line_width(cr, 1.0);

	for (row = 0; row < terminal->height; row++) {
		p_row = terminal_get_row(terminal, row);
		for (col = 0; col < terminal->width; col++) {
			/* get the attributes for this character cell */
			attr = terminal_get_attr(terminal, row, col);
			if ((attr.a & ATTRMASK_INVERSE) ||
				((terminal->mode & MODE_SHOW_CURSOR) &&
				terminal->focused && terminal->row == row &&
				terminal->column == col))
			{
				foreground = attr.bg;
				background = attr.fg;
			} else {
				foreground = attr.fg;
				background = attr.bg;
			}
			if (terminal->mode & MODE_INVERSE) {
				tmp = foreground;
				foreground = background;
				background = tmp;
			}
			bold = attr.a & (ATTRMASK_BOLD | ATTRMASK_BLINK);
			underline = attr.a & ATTRMASK_UNDERLINE;

			/* paint the background */
			cairo_set_source_rgba(cr,
					      terminal->color_table[background].r,
					      terminal->color_table[background].g,
					      terminal->color_table[background].b,
					      terminal->color_table[background].a);
			cairo_move_to(cr, side_margin + (col * extents.max_x_advance),
			      top_margin + (row * extents.height));
			cairo_rel_line_to(cr, extents.max_x_advance, 0);
			cairo_rel_line_to(cr, 0, extents.height);
			cairo_rel_line_to(cr, -extents.max_x_advance, 0);
			cairo_close_path(cr);
			cairo_fill(cr);

			/* paint the foreground */
			if (bold)
				cairo_set_font_face(cr, terminal->font_bold);
			else
				cairo_set_font_face(cr, terminal->font_normal);
			cairo_set_source_rgba(cr,
					      terminal->color_table[foreground].r,
					      terminal->color_table[foreground].g,
					      terminal->color_table[foreground].b,
					      terminal->color_table[foreground].a);

			text_x = side_margin + col * extents.max_x_advance;
			text_y = top_margin + extents.ascent + row * extents.height;
			if (underline) {
				cairo_move_to(cr, text_x, text_y + 2);
				cairo_line_to(cr, text_x + extents.max_x_advance, text_y + 2);
				cairo_stroke(cr);
			}
			cairo_move_to(cr, text_x, text_y);
			
			toShow.c = p_row[col];
			cairo_show_text(cr, (char *) toShow.c.byte);
		}
	}

	if ((terminal->mode & MODE_SHOW_CURSOR) && !terminal->focused) {
		d = 0.5;

		cairo_set_line_width(cr, 1);
		cairo_move_to(cr, side_margin + terminal->column * extents.max_x_advance + d,
			      top_margin + terminal->row * extents.height + d);
		cairo_rel_line_to(cr, extents.max_x_advance - 2 * d, 0);
		cairo_rel_line_to(cr, 0, extents.height - 2 * d);
		cairo_rel_line_to(cr, -extents.max_x_advance + 2 * d, 0);
		cairo_close_path(cr);

		cairo_stroke(cr);
	}

	cairo_destroy(cr);

	window_copy_surface(terminal->window,
			    &rectangle,
			    surface);

	cairo_surface_destroy(surface);
}

static void
terminal_draw(struct terminal *terminal)
{
	struct rectangle rectangle;
	int32_t width, height;

	window_get_child_rectangle(terminal->window, &rectangle);

	width = (rectangle.width - 2 * terminal->margin) /
		(int32_t) terminal->extents.max_x_advance;
	height = (rectangle.height - 2 * terminal->margin) /
		(int32_t) terminal->extents.height;
	terminal_resize(terminal, width, height);

	window_draw(terminal->window);
	terminal_draw_contents(terminal);
	window_flush(terminal->window);
}

static void
redraw_handler(struct window *window, void *data)
{
	struct terminal *terminal = data;

	terminal_draw(terminal);
}

#define STATE_NORMAL 0
#define STATE_ESCAPE 1
#define STATE_ESCAPE_SPECIAL 2
#define STATE_ESCAPE_CSI  3

static void
terminal_data(struct terminal *terminal, const char *data, size_t length);

static void
handle_char(struct terminal *terminal, union utf8_char utf8);

static void
handle_sgr(struct terminal *terminal, int code);

static void
handle_term_parameter(struct terminal *terminal, int code, int sr)
{
	int i;

	if (terminal->qmark_flag) {
		switch(code) {
		case 3:  /* DECCOLM */
			if (sr)
				terminal_resize(terminal, 132, 24);
			else
				terminal_resize(terminal, 80, 24);
			
			/* set columns, but also home cursor and clear screen */
			terminal->row = 0; terminal->column = 0;
			for (i = 0; i < terminal->height; i++) {
				memset(terminal_get_row(terminal, i),
				    0, terminal->data_pitch);
				attr_init(terminal_get_attr_row(terminal, i),
				    terminal->curr_attr, terminal->width);
			}
			break;
		case 5:  /* DECSCNM */
			if (sr)	terminal->mode |=  MODE_INVERSE;
			else	terminal->mode &= ~MODE_INVERSE;
			break;
		case 6:  /* DECOM */
			terminal->origin_mode = sr;
			if (terminal->origin_mode)
				terminal->row = terminal->margin_top;
			else
				terminal->row = 0;
			terminal->column = 0;
			break;
		case 7:  /* DECAWM */
			if (sr)	terminal->mode |=  MODE_AUTOWRAP;
			else	terminal->mode &= ~MODE_AUTOWRAP;
			break;
		case 8:  /* DECARM */
			if (sr)	terminal->mode |=  MODE_AUTOREPEAT;
			else	terminal->mode &= ~MODE_AUTOREPEAT;
			break;
		case 25:
			if (sr)	terminal->mode |=  MODE_SHOW_CURSOR;
			else	terminal->mode &= ~MODE_SHOW_CURSOR;
			break;
		default:
			fprintf(stderr, "Unknown parameter: ?%d\n", code);
			break;
		}
	} else {
		switch(code) {
		case 20: /* LNM */
			if (sr)	terminal->mode |=  MODE_LF_NEWLINE;
			else	terminal->mode &= ~MODE_LF_NEWLINE;
			break;
		default:
			fprintf(stderr, "Unknown parameter: %d\n", code);
			break;
		}
	}
}

static void
handle_escape(struct terminal *terminal)
{
	union utf8_char *row;
	struct attr *attr_row;
	char *p;
	int i, count, x, y, top, bottom;
	int args[10], set[10] = { 0, };
	char response[MAX_RESPONSE] = {0, };

	terminal->escape[terminal->escape_length++] = '\0';
	i = 0;
	p = &terminal->escape[2];
	while ((isdigit(*p) || *p == ';') && i < 10) {
		if (*p == ';') {
			if (!set[i]) {
				args[i] = 0;
				set[i] = 1;
			}
			p++;
			i++;
		} else {
			args[i] = strtol(p, &p, 10);
			set[i] = 1;
		}
	}
	
	switch (*p) {
	case 'A':    /* CUU */
		count = set[0] ? args[0] : 1;
		if (count == 0) count = 1;
		if (terminal->row - count >= terminal->margin_top)
			terminal->row -= count;
		else
			terminal->row = terminal->margin_top;
		break;
	case 'B':    /* CUD */
		count = set[0] ? args[0] : 1;
		if (count == 0) count = 1;
		if (terminal->row + count <= terminal->margin_bottom)
			terminal->row += count;
		else
			terminal->row = terminal->margin_bottom;
		break;
	case 'C':    /* CUF */
		count = set[0] ? args[0] : 1;
		if (count == 0) count = 1;
		if ((terminal->column + count) < terminal->width)
			terminal->column += count;
		else
			terminal->column = terminal->width - 1;
		break;
	case 'D':    /* CUB */
		count = set[0] ? args[0] : 1;
		if (count == 0) count = 1;
		if ((terminal->column - count) >= 0)
			terminal->column -= count;
		else
			terminal->column = 0;
		break;
	case 'E':    /* CNL */
		count = set[0] ? args[0] : 1;
		if (terminal->row + count <= terminal->margin_bottom)
			terminal->row += count;
		else
			terminal->row = terminal->margin_bottom;
		terminal->column = 0;
		break;
	case 'F':    /* CPL */
		count = set[0] ? args[0] : 1;
		if (terminal->row - count >= terminal->margin_top)
			terminal->row -= count;
		else
			terminal->row = terminal->margin_top;
		terminal->column = 0;
		break;
	case 'G':    /* CHA */
		y = set[0] ? args[0] : 1;
		y = y <= 0 ? 1 : y > terminal->width ? terminal->width : y;
		
		terminal->column = y - 1;
		break;
	case 'f':    /* HVP */
	case 'H':    /* CUP */
		x = (set[1] ? args[1] : 1) - 1;
		x = x < 0 ? 0 :
		    (x >= terminal->width ? terminal->width - 1 : x);
		
		y = (set[0] ? args[0] : 1) - 1;
		if (terminal->origin_mode) {
			y += terminal->margin_top;
			y = y < terminal->margin_top ? terminal->margin_top :
			    (y > terminal->margin_bottom ? terminal->margin_bottom : y);
		} else {
			y = y < 0 ? 0 :
			    (y >= terminal->height ? terminal->height - 1 : y);
		}
		
		terminal->row = y;
		terminal->column = x;
		break;
	case 'I':    /* CHT */
		count = set[0] ? args[0] : 1;
		if (count == 0) count = 1;
		while (count > 0 && terminal->column < terminal->width) {
			if (terminal->tab_ruler[terminal->column]) count--;
			terminal->column++;
		}
		terminal->column--;
		break;
	case 'J':    /* ED */
		row = terminal_get_row(terminal, terminal->row);
		attr_row = terminal_get_attr_row(terminal, terminal->row);
		if (!set[0] || args[0] == 0 || args[0] > 2) {
			memset(&row[terminal->column],
			       0, (terminal->width - terminal->column) * sizeof(union utf8_char));
			attr_init(&attr_row[terminal->column],
			       terminal->curr_attr, terminal->width - terminal->column);
			for (i = terminal->row + 1; i < terminal->height; i++) {
				memset(terminal_get_row(terminal, i),
				    0, terminal->data_pitch);
				attr_init(terminal_get_attr_row(terminal, i),
				    terminal->curr_attr, terminal->width);
			}
		} else if (args[0] == 1) {
			memset(row, 0, (terminal->column+1) * sizeof(union utf8_char));
			attr_init(attr_row, terminal->curr_attr, terminal->column+1);
			for (i = 0; i < terminal->row; i++) {
				memset(terminal_get_row(terminal, i),
				    0, terminal->data_pitch);
				attr_init(terminal_get_attr_row(terminal, i),
				    terminal->curr_attr, terminal->width);
			}
		} else if (args[0] == 2) {
			for (i = 0; i < terminal->height; i++) {
				memset(terminal_get_row(terminal, i),
				    0, terminal->data_pitch);
				attr_init(terminal_get_attr_row(terminal, i),
				    terminal->curr_attr, terminal->width);
			}
		}
		break;
	case 'K':    /* EL */
		row = terminal_get_row(terminal, terminal->row);
		attr_row = terminal_get_attr_row(terminal, terminal->row);
		if (!set[0] || args[0] == 0 || args[0] > 2) {
			memset(&row[terminal->column], 0,
			    (terminal->width - terminal->column) * sizeof(union utf8_char));
			attr_init(&attr_row[terminal->column], terminal->curr_attr,
			    terminal->width - terminal->column);
		} else if (args[0] == 1) {
			memset(row, 0, (terminal->column+1) * sizeof(union utf8_char));
			attr_init(attr_row, terminal->curr_attr, terminal->column+1);
		} else if (args[0] == 2) {
			memset(row, 0, terminal->data_pitch);
			attr_init(attr_row, terminal->curr_attr, terminal->width);
		}
		break;
	case 'S':    /* SU */
		terminal_scroll(terminal, set[0] ? args[0] : 1);
		break;
	case 'T':    /* SD */
		terminal_scroll(terminal, 0 - (set[0] ? args[0] : 1));
		break;
	case 'Z':    /* CBT */
		count = set[0] ? args[0] : 1;
		if (count == 0) count = 1;
		while (count > 0 && terminal->column >= 0) {
			if (terminal->tab_ruler[terminal->column]) count--;
			terminal->column--;
		}
		terminal->column++;
		break;
	case '`':    /* HPA */
		y = set[0] ? args[0] : 1;
		y = y <= 0 ? 1 : y > terminal->width ? terminal->width : y;
		
		terminal->column = y - 1;
		break;
	case 'b':    /* REP */
		count = set[0] ? args[0] : 1;
		if (count == 0) count = 1;
		if (terminal->last_char.byte[0])
			for (i = 0; i < count; i++)
				handle_char(terminal, terminal->last_char);
		terminal->last_char.byte[0] = 0;
		break;
	case 'c':    /* Primary DA */
		write(terminal->master, "\e[?1;2c", 7);
		sleep(1);
		break;
	case 'd':    /* VPA */
		x = set[0] ? args[0] : 1;
		x = x <= 0 ? 1 : x > terminal->height ? terminal->height : x;
		
		terminal->row = x - 1;
		break;
	case 'g':    /* TBC */
		if (!set[0] || args[0] == 0) {
			terminal->tab_ruler[terminal->column] = 0;
		} else if (args[0] == 3) {
			memset(terminal->tab_ruler, 0, terminal->width);
		}
		break;
	case 'h':    /* SM */
		for(i = 0; i < 10 && set[i]; i++) {
			handle_term_parameter(terminal, args[i], 1);
		}
		break;
	case 'l':    /* RM */
		for(i = 0; i < 10 && set[i]; i++) {
			handle_term_parameter(terminal, args[i], 0);
		}
		break;
	case 'm':    /* SGR */
		if (set[0] && set[1] && set[2] && args[1] == 5) {
			if (args[0] == 38) {
				handle_sgr(terminal, args[2] + 256);
				break;
			} else if (args[0] == 48) {
				handle_sgr(terminal, args[2] + 512);
				break;
			}
		}
		for(i = 0; i < 10; i++) {
			if(set[i]) {
				handle_sgr(terminal, args[i]);
			} else if(i == 0) {
				handle_sgr(terminal, 0);
				break;
			} else {
				break;
			}
		}
		break;
	case 'n':    /* DSR */
		i = set[0] ? args[0] : 0;
		if (i == 0 || i == 5) {
			write(terminal->master, "\e[0n", 4);
		} else if (i == 6) {
			snprintf(response, MAX_RESPONSE, "\e[%d;%dR",
			         terminal->origin_mode ?
				     terminal->row+terminal->margin_top : terminal->row+1,
				 terminal->column+1);
			write(terminal->master, response, strlen(response));
		}
		sleep(1);  /* is this required? why? */
 		break;
	case 'r':
		if(!set[0]) {
			terminal->margin_top = 0;
			terminal->margin_bottom = terminal->height-1;
			terminal->row = 0;
			terminal->column = 0;
		} else {
			top = (set[0] ? args[0] : 1) - 1;
			top = top < 0 ? 0 :
			      (top >= terminal->height ? terminal->height - 1 : top);
			bottom = (set[1] ? args[1] : 1) - 1;
			bottom = bottom < 0 ? 0 :
			         (bottom >= terminal->height ? terminal->height - 1 : bottom);
			if(bottom > top) {
				terminal->margin_top = top;
				terminal->margin_bottom = bottom;
			} else {
				terminal->margin_top = 0;
				terminal->margin_bottom = terminal->height-1;
			}
			if(terminal->origin_mode)
				terminal->row = terminal->margin_top;
			else
				terminal->row = 0;
			terminal->column = 0;
		}
		break;
	case 's':
		terminal->saved_row = terminal->row;
		terminal->saved_column = terminal->column;
		break;
	case 'u':
		terminal->row = terminal->saved_row;
		terminal->column = terminal->saved_column;
		break;
	default:
		fprintf(stderr, "Unknown CSI escape: %c\n", *p);
		break;
	}	
}

static void
handle_non_csi_escape(struct terminal *terminal, char code)
{
	switch(code) {
	case 'M':    /* RI */
		terminal->row -= 1;
		if(terminal->row < terminal->margin_top) {
			terminal->row = terminal->margin_top;
			terminal_scroll(terminal, -1);
		}
		break;
	case 'E':    /* NEL */
		terminal->column = 0;
		// fallthrough
	case 'D':    /* IND */
		terminal->row += 1;
		if(terminal->row > terminal->margin_bottom) {
			terminal->row = terminal->margin_bottom;
			terminal_scroll(terminal, +1);
		}
		break;
	case 'c':    /* RIS */
		terminal_init(terminal);
		break;
	case 'H':    /* HTS */
		terminal->tab_ruler[terminal->column] = 1;
		break;
	case '7':    /* DECSC */
		terminal->saved_row = terminal->row;
		terminal->saved_column = terminal->column;
		terminal->saved_attr = terminal->curr_attr;
		terminal->saved_origin_mode = terminal->origin_mode;
		break;
	case '8':    /* DECRC */
		terminal->row = terminal->saved_row;
		terminal->column = terminal->saved_column;
		terminal->curr_attr = terminal->saved_attr;
		terminal->origin_mode = terminal->saved_origin_mode;
		break;
	default:
		fprintf(stderr, "Unknown escape code: %c\n", code);
		break;
	}
}

static void
handle_special_escape(struct terminal *terminal, char special, char code)
{
	int i, numChars;

	if (special == '#') {
		switch(code) {
		case '8':
			/* fill with 'E', no cheap way to do this */
			memset(terminal->data, 0, terminal->data_pitch * terminal->height);
			numChars = terminal->width * terminal->height;
			for(i = 0; i < numChars; i++) {
				terminal->data[i].byte[0] = 'E';
			}
			break;
		default:
			fprintf(stderr, "Unknown HASH escape #%c\n", code);
			break;
		}
	} else {
		fprintf(stderr, "Unknown special escape %c%c\n", special, code);
	}
}

static void
handle_sgr(struct terminal *terminal, int code)
{
	switch(code) {
	case 0:
		terminal->curr_attr = terminal->color_scheme->default_attr;
		break;
	case 1:
		terminal->curr_attr.a |= ATTRMASK_BOLD;
		if (terminal->curr_attr.fg < 8)
			terminal->curr_attr.fg += 8;
		break;
	case 4:
		terminal->curr_attr.a |= ATTRMASK_UNDERLINE;
		break;
	case 5:
		terminal->curr_attr.a |= ATTRMASK_BLINK;
		break;
	case 2:
	case 21:
	case 22:
		terminal->curr_attr.a &= ~ATTRMASK_BOLD;
		if (terminal->curr_attr.fg < 16 && terminal->curr_attr.fg >= 8)
			terminal->curr_attr.fg -= 8;
		break;
	case 24:
		terminal->curr_attr.a &= ~ATTRMASK_UNDERLINE;
		break;
	case 25:
		terminal->curr_attr.a &= ~ATTRMASK_BLINK;
		break;
	case 7:
	case 26:
		terminal->curr_attr.a |= ATTRMASK_INVERSE;
		break;
	case 27:
		terminal->curr_attr.a &= ~ATTRMASK_INVERSE;
		break;
	case 39:
		terminal->curr_attr.fg = terminal->color_scheme->default_attr.fg;
		break;
	case 49:
		terminal->curr_attr.bg = terminal->color_scheme->default_attr.bg;
		break;
	default:
		if(code >= 30 && code <= 37) {
			terminal->curr_attr.fg = code - 30;
			if (terminal->curr_attr.a & ATTRMASK_BOLD)
				terminal->curr_attr.fg += 8;
		} else if(code >= 40 && code <= 47) {
			terminal->curr_attr.bg = code - 40;
		} else if(code >= 256 && code < 512) {
			terminal->curr_attr.fg = code - 256;
		} else if(code >= 512 && code < 768) {
			terminal->curr_attr.bg = code - 512;
		} else {
			fprintf(stderr, "Unknown SGR code: %d\n", code);
		}
		break;
	}
}

/* Returns 1 if c was special, otherwise 0 */
static int
handle_special_char(struct terminal *terminal, char c)
{
	union utf8_char *row;
	struct attr *attr_row;
	
	row = terminal_get_row(terminal, terminal->row);
	attr_row = terminal_get_attr_row(terminal, terminal->row);
	
	switch(c) {
	case '\r':
		terminal->column = 0;
		break;
	case '\n':
		if (terminal->mode & MODE_LF_NEWLINE) {
			terminal->column = 0;
		}
		/* fallthrough */
	case '\v':
	case '\f':
		terminal->row++;
		if(terminal->row > terminal->margin_bottom) {
			terminal->row = terminal->margin_bottom;
			terminal_scroll(terminal, +1);
		}

		break;
	case '\t':
		while (terminal->column < terminal->width) {
			if (terminal->tab_ruler[terminal->column]) break;
			row[terminal->column].byte[0] = ' ';
			row[terminal->column].byte[1] = '\0';
			attr_row[terminal->column] = terminal->curr_attr;
			terminal->column++;
		}
		if (terminal->column >= terminal->width) {
			terminal->column = terminal->width - 1;
		}

		break;
	case '\b':
		if (terminal->column >= terminal->width) {
			terminal->column = terminal->width - 2;
		} else if (terminal->column > 0) {
			terminal->column--;
		} else if (terminal->mode & MODE_AUTOWRAP) {
			terminal->column = terminal->width - 1;
			terminal->row -= 1;
			if (terminal->row < terminal->margin_top) {
				terminal->row = terminal->margin_top;
				terminal_scroll(terminal, -1);
			}
		}

		break;
	case '\a':
		/* Bell */
		break;
	default:
		return 0;
	}
	
	return 1;
}

static void
handle_char(struct terminal *terminal, union utf8_char utf8)
{
	union utf8_char *row;
	struct attr *attr_row;
	
	if (handle_special_char(terminal, utf8.byte[0])) return;
	
	/* There are a whole lot of non-characters, control codes,
	 * and formatting codes that should probably be ignored,
	 * for example: */
	if (strncmp((char*) utf8.byte, "\xEF\xBB\xBF", 3) == 0) {
		/* BOM, ignore */
		return;
	} 
	
	/* Some of these non-characters should be translated, e.g.: */
	if (utf8.byte[0] < 32) {
		utf8.byte[0] = utf8.byte[0] + 64;
	}
	
	/* handle right margin effects */
	if (terminal->column >= terminal->width) {
		if (terminal->mode & MODE_AUTOWRAP) {
			terminal->column = 0;
			terminal->row += 1;
			if (terminal->row > terminal->margin_bottom) {
				terminal->row = terminal->margin_bottom;
				terminal_scroll(terminal, +1);
			}
		} else {
			terminal->column--;
 		}
 	}
	
	row = terminal_get_row(terminal, terminal->row);
	attr_row = terminal_get_attr_row(terminal, terminal->row);
	
	row[terminal->column] = utf8;
	attr_row[terminal->column++] = terminal->curr_attr;

	if (utf8.ch != terminal->last_char.ch)
		terminal->last_char = utf8;
}

static void
terminal_data(struct terminal *terminal, const char *data, size_t length)
{
	int i;
	union utf8_char utf8;
	enum utf8_state parser_state;

	for (i = 0; i < length; i++) {
		parser_state =
			utf8_next_char(&terminal->state_machine, data[i]);
		switch(parser_state) {
		case utf8state_accept:
			utf8.ch = terminal->state_machine.s.ch;
			break;
		case utf8state_reject:
			/* the unicode replacement character */
			utf8.byte[0] = 0xEF;
			utf8.byte[1] = 0xBF;
			utf8.byte[2] = 0xBD;
			utf8.byte[3] = 0x00;
			break;
		default:
			continue;
		}

		/* assume escape codes never use non-ASCII characters */
		if (terminal->state == STATE_ESCAPE) {
			terminal->escape[terminal->escape_length++] = utf8.byte[0];
			if (utf8.byte[0] == '[') {
				terminal->state = STATE_ESCAPE_CSI;
				continue;
			} else if (utf8.byte[0] == '#' || utf8.byte[0] == '(' ||
				utf8.byte[0] == ')')
			{
				terminal->state = STATE_ESCAPE_SPECIAL;
				continue;
			} else {
				terminal->state = STATE_NORMAL;
				handle_non_csi_escape(terminal, utf8.byte[0]);
				continue;
			}
		} else if (terminal->state == STATE_ESCAPE_SPECIAL) {
			terminal->escape[terminal->escape_length++] = utf8.byte[0];
			terminal->state = STATE_NORMAL;
			if (isdigit(utf8.byte[0]) || isalpha(utf8.byte[0])) {
				handle_special_escape(terminal, terminal->escape[1],
				                      utf8.byte[0]);
				continue;
			}
		} else if (terminal->state == STATE_ESCAPE_CSI) {
			if (handle_special_char(terminal, utf8.byte[0]) != 0) {
				/* do nothing */
			} else if (utf8.byte[0] == '?') {
				terminal->qmark_flag = 1;
			} else {
				/* Don't overflow the buffer */
				if (terminal->escape_length < MAX_ESCAPE)
					terminal->escape[terminal->escape_length++] = utf8.byte[0];
				if (terminal->escape_length >= MAX_ESCAPE)
					terminal->state = STATE_NORMAL;
			}
			
			if (isalpha(utf8.byte[0]) || utf8.byte[0] == '@' ||
				utf8.byte[0] == '`')
			{
				terminal->state = STATE_NORMAL;
				handle_escape(terminal);
				continue;
			} else {
				continue;
			}
		}

		/* this is valid, because ASCII characters are never used to
		 * introduce a multibyte sequence in UTF-8 */
		if (utf8.byte[0] == '\e') {
			terminal->state = STATE_ESCAPE;
			terminal->escape[0] = '\e';
			terminal->escape_length = 1;
			terminal->qmark_flag = 0;
		} else {
			handle_char(terminal, utf8);
		} /* if */
	} /* for */

	window_schedule_redraw(terminal->window);
}

static void
key_handler(struct window *window, uint32_t key, uint32_t sym,
	    uint32_t state, uint32_t modifiers, void *data)
{
	struct terminal *terminal = data;
	char ch[MAX_RESPONSE];
	int len = 0;

	switch (sym) {
	case XK_F11:
		if (!state)
			break;
		terminal->fullscreen ^= 1;
		window_set_fullscreen(window, terminal->fullscreen);
		window_schedule_redraw(terminal->window);
		break;

	case XK_Delete:
		sym = 0x04;
	case XK_BackSpace:
	case XK_Tab:
	case XK_Linefeed:
	case XK_Clear:
	case XK_Pause:
	case XK_Scroll_Lock:
	case XK_Sys_Req:
	case XK_Escape:
		ch[len++] = sym & 0x7f;
		break;

	case XK_Return:
		if (terminal->mode & MODE_LF_NEWLINE) {
			ch[len++] = 0x0D;
			ch[len++] = 0x0A;
		} else {
			ch[len++] = 0x0D;
		}
		break;

	case XK_Shift_L:
	case XK_Shift_R:
	case XK_Control_L:
	case XK_Control_R:
	case XK_Alt_L:
	case XK_Alt_R:
		break;

	default:
		if (modifiers & WINDOW_MODIFIER_CONTROL)
			sym = sym & 0x1f;
		else if (modifiers & WINDOW_MODIFIER_ALT)
			ch[len++] = 0x1b;
		if (sym < 256)
			ch[len++] = sym;
		break;
	}

	if (state && len > 0)
		write(terminal->master, ch, len);
}

static void
keyboard_focus_handler(struct window *window,
		       struct input *device, void *data)
{
	struct terminal *terminal = data;

	terminal->focused = (device != NULL);
	window_schedule_redraw(terminal->window);
}

static struct terminal *
terminal_create(struct display *display, int fullscreen)
{
	struct terminal *terminal;
	cairo_surface_t *surface;
	cairo_t *cr;

	terminal = malloc(sizeof *terminal);
	if (terminal == NULL)
		return terminal;

	memset(terminal, 0, sizeof *terminal);
	terminal->fullscreen = fullscreen;
	terminal->color_scheme = &DEFAULT_COLORS;
	terminal_init(terminal);
	terminal->margin_top = 0;
	terminal->margin_bottom = 10000;  /* much too large, will be trimmed down
	                                   * by terminal_resize */
	terminal->window = window_create(display, "Wayland Terminal",
					 500, 400);

	init_state_machine(&terminal->state_machine);
	init_color_table(terminal);

	terminal->display = display;
	terminal->margin = 5;

	window_set_fullscreen(terminal->window, terminal->fullscreen);
	window_set_user_data(terminal->window, terminal);
	window_set_redraw_handler(terminal->window, redraw_handler);

	window_set_key_handler(terminal->window, key_handler);
	window_set_keyboard_focus_handler(terminal->window,
					  keyboard_focus_handler);

	surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
	cr = cairo_create(surface);
	terminal->font_bold = cairo_toy_font_face_create ("mono",
	                      CAIRO_FONT_SLANT_NORMAL,
	                      CAIRO_FONT_WEIGHT_BOLD);
	cairo_font_face_reference(terminal->font_bold);
	terminal->font_normal = cairo_toy_font_face_create ("mono",
	                        CAIRO_FONT_SLANT_NORMAL,
	                        CAIRO_FONT_WEIGHT_NORMAL);
	cairo_font_face_reference(terminal->font_normal);
	cairo_set_font_face(cr, terminal->font_normal);
	cairo_set_font_size(cr, 14);
	cairo_font_extents(cr, &terminal->extents);
	cairo_destroy(cr);
	cairo_surface_destroy(surface);

	terminal_resize(terminal, 80, 24);
	terminal_draw(terminal);

	return terminal;
}

static gboolean
io_handler(GIOChannel   *source,
	   GIOCondition  condition,
	   gpointer      data)
{
	struct terminal *terminal = data;
	gchar buffer[256];
	gsize bytes_read;
	GError *error = NULL;

	g_io_channel_read_chars(source, buffer, sizeof buffer,
				&bytes_read, &error);

	terminal_data(terminal, buffer, bytes_read);

	return TRUE;
}

static int
terminal_run(struct terminal *terminal, const char *path)
{
	int master;
	pid_t pid;

	pid = forkpty(&master, NULL, NULL, NULL);
	if (pid == 0) {
		setenv("TERM", "vt100", 1);
		if (execl(path, path, NULL)) {
			printf("exec failed: %m\n");
			exit(EXIT_FAILURE);
		}
	} else if (pid < 0) {
		fprintf(stderr, "failed to fork and create pty (%m).\n");
		return -1;
	}

	terminal->master = master;
	terminal->channel = g_io_channel_unix_new(master);
	fcntl(master, F_SETFL, O_NONBLOCK);
	g_io_add_watch(terminal->channel, G_IO_IN,
		       io_handler, terminal);

	return 0;
}

static const GOptionEntry option_entries[] = {
	{ "fullscreen", 'f', 0, G_OPTION_ARG_NONE,
	  &option_fullscreen, "Run in fullscreen mode" },
	{ NULL }
};

int main(int argc, char *argv[])
{
	struct display *d;
	struct terminal *terminal;

	d = display_create(&argc, &argv, option_entries);
	if (d == NULL) {
		fprintf(stderr, "failed to create display: %m\n");
		return -1;
	}

	terminal = terminal_create(d, option_fullscreen);
	if (terminal_run(terminal, "/bin/bash"))
		exit(EXIT_FAILURE);

	display_run(d);

	return 0;
}