aboutsummaryrefslogtreecommitdiff
path: root/src/base_pty.c
blob: 4d250076e83df7591efe6fe2f8dd85ca11981c29 (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
/*
 * Copyright (c) 2018-2019 Hanspeter Portner (dev@open-music-kontrollers.ch)
 *
 * This is free software: you can redistribute it and/or modify
 * it under the terms of the Artistic License 2.0 as published by
 * The Perl Foundation.
 *
 * This source is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * Artistic License 2.0 for more details.
 *
 * You should have received a copy of the Artistic License 2.0
 * along the source as a COPYING file. If not, obtain it from
 * http://www.perlfoundation.org/artistic_license_2_0.
 */

#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <vterm.h>
#include <pty.h>
#include <sys/wait.h>
#include <poll.h>

#include "base_internal.h"

#define DEFAULT_FG 0xddddddff
#define DEFAULT_BG 0x222222ff

#define DEFAULT_FG_LIGHT 0xdddddd7f
#define DEFAULT_BG_LIGHT 0x2222227f

#define NROWS_MAX 512
#define NCOLS_MAX 512

#define MAX(x, y) (x > y ? y : x)

typedef struct _cell_t cell_t;
typedef struct _d2tk_atom_body_pty_t d2tk_atom_body_pty_t;

struct _cell_t {
	char lbl [8];
	size_t lbl_len;
	bool bold;
	bool italic;
	bool reverse;
	bool cursor;
	uint32_t fg;
	uint32_t bg;
};

struct _d2tk_atom_body_pty_t {
	d2tk_coord_t height;

	d2tk_coord_t ncols;
	d2tk_coord_t nrows;

	int fd;
	pid_t kid;

	VTerm *vterm;
	VTermScreen *screen;
	VTermState *state;

	uint32_t dark;
	uint32_t light;

	bool cursor_visible;
	int cursor_shape;

	cell_t cells [NROWS_MAX][NCOLS_MAX];
};

const size_t d2tk_atom_body_pty_sz = sizeof(d2tk_atom_body_pty_t);

static inline uint32_t
_term_dark(d2tk_atom_body_pty_t *vpty)
{
	return vpty->dark;
}

static inline uint32_t
_term_light(d2tk_atom_body_pty_t *vpty)
{
	return vpty->light;
}

static inline int
_term_read(d2tk_atom_body_pty_t *vpty,
	void (*cb)(const char *buf, size_t len, void *data), void *data)
{
	char buf [4096];
	int count = 0;

	while(true)
	{
		const ssize_t len = read(vpty->fd, buf, sizeof(buf));

		if(len == -1)
		{
			if(errno != EAGAIN)
			{
				fprintf(stderr, "read failed '%s'\n", strerror(errno));
			}
			break;
		}

		if(len == 0)
		{
			break;;
		}

		cb(buf, len, data);
		count += 1;
	}

	return count;
}

static inline int
_term_done(d2tk_atom_body_pty_t *vpty)
{
	if(vpty->kid == 0)
	{
		return 1;
	}

	if(waitpid(vpty->kid, NULL, WNOHANG) == vpty->kid)
	{
		vpty->kid = 0;
		return 1;
	}

	return 0;
}

static void
_term_output(const char *buf, size_t len, void *data)
{
	d2tk_atom_body_pty_t *vpty = data;

	const ssize_t writ = write(vpty->fd, buf, len);

	if(writ == -1)
	{
		fprintf(stderr, "write failed '%s'\n", strerror(errno));
		return;
	}
}

static int
_screen_settermprop(VTermProp prop, VTermValue *val, void *data)
{
	d2tk_atom_body_pty_t *vpty = data;

	switch(prop)
	{
		case VTERM_PROP_CURSORVISIBLE: // bool
		{
			vpty->cursor_visible = val->boolean;
		} break;
		case VTERM_PROP_CURSORSHAPE: // number
		{
			vpty->cursor_shape = val->number;
		} break;

		default:
		{
			// nothing to do
		} break;
	}

	return 0;
}

static int
_screen_resize(int nrows, int ncols, void *data)
{
	d2tk_atom_body_pty_t *vpty = data;

	if( (nrows == vpty->nrows) && (ncols == vpty->ncols) )
	{
		return 0;
	}

	const struct winsize winsize = {
		.ws_row = nrows,
		.ws_col = ncols,
		.ws_xpixel = 0,
		.ws_ypixel = 0
	};

	if(ioctl(vpty->fd, TIOCSWINSZ, &winsize) == -1)
	{
		fprintf(stderr, "ioctl failed '%s'\n", strerror(errno));
		return 1;
	}

	vpty->nrows = nrows;
	vpty->ncols = ncols;

	return 0;
}

static const VTermScreenCallbacks screen_callbacks = {
	.settermprop = _screen_settermprop,
  .resize = _screen_resize
};

static void
_term_clone(FILE *stderr_save, void *data)
{
	char **argv = data;

	execvp(argv[0], argv);

	fprintf(stderr_save, "cannot exec(%s) - %s\n", argv[0], strerror(errno));
}

static int
_term_init(d2tk_atom_body_pty_t *vpty, d2tk_clone_t clone, void *data,
	d2tk_coord_t height, d2tk_coord_t ncols, d2tk_coord_t nrows)
{
	vpty->height = height;
	vpty->nrows = nrows;
	vpty->ncols = ncols;

	struct termios termios = {
		.c_iflag = ICRNL|IXON,
		.c_oflag = OPOST|ONLCR
#ifdef TAB0
			|TAB0
#endif
			,
		.c_cflag = CS8|CREAD,
		.c_lflag = ISIG|ICANON|IEXTEN|ECHO|ECHOE|ECHOK,
		/* c_cc later */
	};

#ifdef IUTF8
	termios.c_iflag |= IUTF8;
#endif
#ifdef NL0
	termios.c_oflag |= NL0;
#endif
#ifdef CR0
	termios.c_oflag |= CR0;
#endif
#ifdef BS0
	termios.c_oflag |= BS0;
#endif
#ifdef VT0
	termios.c_oflag |= VT0;
#endif
#ifdef FF0
	termios.c_oflag |= FF0;
#endif
#ifdef ECHOCTL
	termios.c_lflag |= ECHOCTL;
#endif
#ifdef ECHOKE
	termios.c_lflag |= ECHOKE;
#endif

	cfsetspeed(&termios, 115200);

	termios.c_cc[VINTR]    = 0x1f & 'C';
	termios.c_cc[VQUIT]    = 0x1f & '\\';
	termios.c_cc[VERASE]   = 0x7f;
	termios.c_cc[VKILL]    = 0x1f & 'U';
	termios.c_cc[VEOF]     = 0x1f & 'D';
	termios.c_cc[VEOL]     = _POSIX_VDISABLE;
	termios.c_cc[VEOL2]    = _POSIX_VDISABLE;
	termios.c_cc[VSTART]   = 0x1f & 'Q';
	termios.c_cc[VSTOP]    = 0x1f & 'S';
	termios.c_cc[VSUSP]    = 0x1f & 'Z';
	termios.c_cc[VREPRINT] = 0x1f & 'R';
	termios.c_cc[VWERASE]  = 0x1f & 'W';
	termios.c_cc[VLNEXT]   = 0x1f & 'V';
	termios.c_cc[VMIN]     = 1;
	termios.c_cc[VTIME]    = 0;

	const struct winsize winsize = {
		.ws_row = vpty->nrows,
		.ws_col = vpty->ncols,
		.ws_xpixel = 0,
		.ws_ypixel = 0
	};

	const int stderr_save_fileno = dup(STDERR_FILENO);

	vpty->kid = forkpty(&vpty->fd, NULL, &termios, &winsize);
	if(vpty->kid == -1)
	{
		vpty->kid = 0;
		return 1;
	}
	else if(vpty->kid == 0) // child
	{
		fcntl(stderr_save_fileno, F_SETFD, fcntl(stderr_save_fileno, F_GETFD) | FD_CLOEXEC);
		FILE *stderr_save = fdopen(stderr_save_fileno, "a");

		/* Restore the ISIG signals back to defaults */
		signal(SIGINT,  SIG_DFL);
		signal(SIGQUIT, SIG_DFL);
		signal(SIGSTOP, SIG_DFL);
		signal(SIGCONT, SIG_DFL);

		putenv("TERM=xterm-256color");
		//putenv("COLORTERM=truecolor");

		if(!clone)
		{
			clone = _term_clone;
		}

		clone(stderr_save, data);
		_exit(EXIT_FAILURE);
	}

  fcntl(vpty->fd, F_SETFL, fcntl(vpty->fd, F_GETFL) | O_NONBLOCK);
	close(stderr_save_fileno);

	vpty->vterm = vterm_new(vpty->nrows, vpty->ncols);
	vterm_set_utf8(vpty->vterm, 1);
	vterm_output_set_callback(vpty->vterm, _term_output, vpty);

	vpty->state = vterm_obtain_state(vpty->vterm);

	vpty->screen = vterm_obtain_screen(vpty->vterm);
	vterm_screen_set_callbacks(vpty->screen, &screen_callbacks, vpty);
	vterm_screen_reset(vpty->screen, 1);

	return 0;
}

static int
_term_probe(d2tk_atom_body_pty_t *vpty)
{
	int again = 0;

	struct pollfd fds = {
		.fd = vpty->fd,
		.events = POLLIN
	};

	switch(poll(&fds, 1, 0))
	{
		case -1:
		{
			//printf("[%s] error: %s\n", __func__, strerror(errno));
		} break;
		case 0:
		{
			//printf("[%s] timeout\n", __func__);
		} break;
		default:
		{
			//printf("[%s] ready\n", __func__);
			again = 1;
		} break;
	}

	return again;
}

static int
_term_deinit(d2tk_atom_body_pty_t *vpty)
{
	if(!vpty)
	{
		return 1;
	}

	if(vpty->kid != 0)
	{
		kill(vpty->kid, SIGTERM);

#define RETRIES 100 // over the course of 100 ms
		for(int i = 0; i < RETRIES; i++)
		{
			if(waitpid(vpty->kid, NULL, WNOHANG) == vpty->kid)
			{
				vpty->kid = 0;
				break;
			}

			usleep(1000000 / RETRIES);
		}
#undef RETRIES
	}

	if(vpty->kid !=  0)
	{
		fprintf(stderr, "[%s] sending SIGKILL to pid %i\n", __func__, vpty->kid);
		kill(vpty->kid, SIGKILL);
		waitpid(vpty->kid, NULL, 0);
		vpty->kid = 0;
	}

	if(vpty->vterm)
	{
		vterm_free(vpty->vterm);
	}

	memset(vpty, 0x0, sizeof(d2tk_atom_body_pty_t));

	return 0;
}

static int
_term_event(d2tk_atom_event_type_t event, void *data)
{
	d2tk_atom_body_pty_t *vpty = data;

	switch(event)
	{
		case D2TK_ATOM_EVENT_PROBE:
		{
			return _term_probe(vpty);
		} break;
		case D2TK_ATOM_EVENT_DEINIT:
		{
			return _term_deinit(vpty);
		} break;

		case D2TK_ATOM_EVENT_NONE:
			// fall-through
		default:
		{
			// nothing to do
		} break;
	}

	return 0;
}

static inline void
_term_set_dark_light(d2tk_atom_body_pty_t *vpty, uint32_t fg)
{
	const int32_t r0 = (vpty->light >> 24) & 0xff;
	const int32_t g0 = (vpty->light >> 16) & 0xff;
	const int32_t b0 = (vpty->light >>  8) & 0xff;
	const int32_t d0 = (r0 - g0) + (r0 - b0);

	const int32_t r1 = (fg >> 24) & 0xff;
	const int32_t g1 = (fg >> 16) & 0xff;
	const int32_t b1 = (fg >>  8) & 0xff;
	const int32_t d1 = (r1 - g1) + (r1 - b1);

	if(d1 > d0)
	{
		vpty->light = fg;
		vpty->dark = ( (r1 >> 1) << 24)
			| ( (g1 >> 1) << 16)
			| ( (b1 >> 1) << 8)
			| 0xff;
	}
}

static inline void
_term_update(d2tk_atom_body_pty_t *vpty)
{
	VTermPos cursor;
	VTermPos pos;

	memset(&cursor, 0x0, sizeof(cursor));
	vterm_state_get_cursorpos(vpty->state, &cursor);

	memset(vpty->cells, 0x0, sizeof(vpty->cells));

	for(int y = 0; y < vpty->nrows; y++)
	{
		pos.row = y;

		for(int x = 0; x < vpty->ncols; x++)
		{
			cell_t *tar = &vpty->cells[y][x];

			pos.col = x;

			VTermScreenCell cell;
			memset(&cell, 0x0, sizeof(cell));
			vterm_screen_get_cell(vpty->screen, pos, &cell);

			if( cell.chars[0] && (cell.width == 1) )
			{
				if(cell.chars[0] != ' ')
				{
					const char *tail = utf8catcodepoint(tar->lbl,
						cell.chars[0], sizeof(tar->lbl));

					tar->lbl_len = tail - tar->lbl;
				}
			}

			if(cell.attrs.bold)
			{
				tar->bold = true;
			}

			if(cell.attrs.italic)
			{
				tar->italic = true;
			}

			uint32_t fg_rgba = 0x0;
			uint32_t bg_rgba = 0x0;

			if(VTERM_COLOR_IS_RGB(&cell.fg))
			{
				const VTermColor tmp = cell.fg;

				fg_rgba = (tmp.rgb.red << 24)
					| (tmp.rgb.green << 16)
					| (tmp.rgb.blue << 8)
					| 0xff;
			}
			else if(VTERM_COLOR_IS_INDEXED(&cell.fg))
			{
				VTermColor tmp = cell.fg;
				vterm_screen_convert_color_to_rgb(vpty->screen, &tmp);

				fg_rgba = (tmp.rgb.red << 24)
					| (tmp.rgb.green << 16)
					| (tmp.rgb.blue << 8)
					| 0xff;
			}
			else if(VTERM_COLOR_IS_DEFAULT_FG(&cell.fg))
			{
				fg_rgba = DEFAULT_FG;
			}
			else if(VTERM_COLOR_IS_DEFAULT_BG(&cell.fg))
			{
				fg_rgba = DEFAULT_BG;
			}

			if(VTERM_COLOR_IS_RGB(&cell.bg))
			{
				const VTermColor tmp = cell.bg;

				bg_rgba = (tmp.rgb.red << 24)
					| (tmp.rgb.green << 16)
					| (tmp.rgb.blue << 8)
					| 0xff;
			}
			else if(VTERM_COLOR_IS_INDEXED(&cell.bg))
			{
				VTermColor tmp = cell.bg;
				vterm_screen_convert_color_to_rgb(vpty->screen, &tmp);

				bg_rgba = (tmp.rgb.red << 24)
					| (tmp.rgb.green << 16)
					| (tmp.rgb.blue << 8)
					| 0xff;
			}
			else if(VTERM_COLOR_IS_DEFAULT_FG(&cell.bg))
			{
				bg_rgba = 0xffffffff;
			}
			else if(VTERM_COLOR_IS_DEFAULT_BG(&cell.bg))
			{
				bg_rgba = 0x000000ff;
			}

			tar->cursor = (y == cursor.row) && (x == cursor.col) && vpty->cursor_visible;
			tar->reverse = cell.attrs.reverse;
			tar->fg = fg_rgba;
			tar->bg = bg_rgba;

			_term_set_dark_light(vpty, fg_rgba);
		}
	}
}

static void
_term_resize(d2tk_atom_body_pty_t *vpty, d2tk_coord_t ncols,
	d2tk_coord_t nrows)
{
	if( (nrows != vpty->nrows) || (ncols != vpty->ncols) )
	{
		vterm_set_size(vpty->vterm, nrows, ncols);
	}
}

static inline void
_term_input_cb(const char *buf, size_t len, void *data)
{
	d2tk_atom_body_pty_t *vpty = data;

	vterm_input_write(vpty->vterm, buf, len);
}

static inline void
_term_input(d2tk_atom_body_pty_t *vpty)
{
	if(_term_read(vpty, _term_input_cb, vpty) )
	{
		_term_update(vpty);
	}
}

static inline d2tk_state_t
_term_behave(d2tk_base_t *base, d2tk_atom_body_pty_t *vpty,
	d2tk_id_t id, const d2tk_rect_t *rect)
{
	const d2tk_state_t state = d2tk_base_is_active_hot(base, id, rect,
		D2TK_FLAG_NONE);

	VTermModifier mod = VTERM_MOD_NONE;

	if(d2tk_state_is_focused(state))
	{
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_ENTER, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_ENTER, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_TAB, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_TAB, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_BACKSPACE, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_BACKSPACE, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_ESCAPE, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_ESCAPE, mod);
		}

		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_UP, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_UP, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_DOWN, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_DOWN, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_LEFT, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_LEFT, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_RIGHT, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_RIGHT, mod);
		}

		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_INS, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_INS, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_DEL, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_DEL, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_HOME, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_HOME, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_END, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_END, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_PAGEUP, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_PAGEUP, mod);
		}
		if(d2tk_base_get_keymask(base, D2TK_KEYMASK_PAGEDOWN, true))
		{
			vterm_keyboard_key(vpty->vterm, VTERM_KEY_PAGEDOWN, mod);
		}

		{
			ssize_t len = 0;
			const utf8_int32_t *utf8 = NULL;

			d2tk_base_get_utf8(base, &len, &utf8);

			for(ssize_t i = 0; i < len; i++)
			{
				vterm_keyboard_unichar(vpty->vterm, utf8[i], mod);
			}
		}
	}

	if(d2tk_base_get_modmask(base, D2TK_MODMASK_SHIFT, false))
	{
		mod |= VTERM_MOD_SHIFT;
	}
	if(d2tk_base_get_modmask(base, D2TK_MODMASK_ALT, false))
	{
		mod |= VTERM_MOD_ALT;
	}
	if(d2tk_base_get_modmask(base, D2TK_MODMASK_CTRL, false))
	{
		mod |= VTERM_MOD_CTRL;
	}

	if(d2tk_state_is_focus_in(state))
	{
		vterm_state_focus_in(vpty->state);
	}

	if(d2tk_state_is_focus_out(state))
	{
		vterm_state_focus_out(vpty->state);
	}

	if(d2tk_state_is_hot(state))
	{
		d2tk_coord_t mx, my;
		int dx, dy;
		d2tk_base_get_mouse_pos(base, &mx, &my);
		d2tk_base_get_mouse_scroll(base, &dx, &dy, false);

		const int row = (my - rect->y) * vpty->nrows / rect->h;
		const int col = (mx - rect->x) * vpty->ncols / rect->w;

		vterm_mouse_move(vpty->vterm, row, col, mod);

		vterm_mouse_button(vpty->vterm, 1,
			d2tk_base_get_butmask(base, D2TK_BUTMASK_LEFT, false), mod);
		vterm_mouse_button(vpty->vterm, 2,
			d2tk_base_get_butmask(base, D2TK_BUTMASK_MIDDLE, false), mod);
		vterm_mouse_button(vpty->vterm, 3,
			d2tk_base_get_butmask(base, D2TK_BUTMASK_RIGHT, false), mod);

		if(dy > 0)
		{
			vterm_mouse_button(vpty->vterm, 4, true, mod);
		}
		else if(dy < 0)
		{
			vterm_mouse_button(vpty->vterm, 5, true, mod);
		}
	}

	return state;
}

static inline void
_term_draw(d2tk_base_t *base, d2tk_atom_body_pty_t *vpty,
	const d2tk_rect_t *rect, bool focus)
{
	D2TK_BASE_TABLE(rect, vpty->ncols, vpty->nrows, D2TK_FLAG_TABLE_REL, tab)
	{
		const int x = d2tk_table_get_index_x(tab);
		const int y = d2tk_table_get_index_y(tab);
		const d2tk_rect_t *trect = d2tk_table_get_rect(tab);

		const d2tk_style_t *old_style = d2tk_base_get_style(base);
		d2tk_style_t style = *old_style;
		cell_t *cell = &vpty->cells[y][x];

		style.border_width = 0;
		style.padding = 0;
		style.rounding = 0;

		uint32_t fg = cell->fg;
		uint32_t bg = cell->bg;

		if(cell->cursor)
		{
			// draw box cursor
			if(vpty->cursor_shape == VTERM_PROP_CURSORSHAPE_BLOCK)
			{
				fg = focus ? DEFAULT_BG : DEFAULT_BG_LIGHT;
				bg = focus ? DEFAULT_FG : DEFAULT_FG_LIGHT;
			}
		}
		else if(cell->reverse)
		{
			const uint32_t tmp = fg;

			fg = bg;
			bg = tmp;
		}

		style.text_fill_color[D2TK_TRIPLE_NONE] = bg;
		style.text_stroke_color[D2TK_TRIPLE_NONE] = fg;

		if(cell->bold)
		{
			style.font_face = "FiraCode-Bold.ttf";
		}
		else if(cell->italic)
		{
			style.font_face = "FiraCode-Light.ttf";
		}
		else
		{
			style.font_face = "FiraCode-Regular.ttf";
		}

		d2tk_base_set_style(base, &style);

		d2tk_base_label(base, cell->lbl_len, cell->lbl, 1.f, trect,
			D2TK_ALIGN_LEFT | D2TK_ALIGN_TOP);

		d2tk_base_set_style(base, old_style);

		if(cell->cursor)
		{
			style.font_face = "FiraCode-Bold.ttf";
			style.text_fill_color[D2TK_TRIPLE_NONE] = 0x0;
			style.text_stroke_color[D2TK_TRIPLE_NONE] = focus
				? DEFAULT_FG
				: DEFAULT_FG_LIGHT;
			d2tk_base_set_style(base, &style);

			// draw underline cursor overlay
			if(vpty->cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE)
			{
				static const char lbl [2] = "_";

				d2tk_base_label(base, sizeof(lbl), lbl, 1.f, trect,
					D2TK_ALIGN_LEFT | D2TK_ALIGN_TOP);
			}
			// draw bar cursor overlay
			else if(vpty->cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT)
			{
				static const char lbl [2] = "|";

				d2tk_rect_t bnd = *trect;
				bnd.x -= bnd.w/2;

				d2tk_base_label(base, sizeof(lbl), lbl, 1.f, &bnd,
					D2TK_ALIGN_LEFT | D2TK_ALIGN_TOP);
			}

			d2tk_base_set_style(base, old_style);
		}
	}
}

D2TK_API d2tk_state_t
d2tk_base_pty(d2tk_base_t *base, d2tk_id_t id, d2tk_clone_t clone, void *data,
	d2tk_coord_t height, const d2tk_rect_t *rect, bool reinit)
{
	d2tk_atom_body_pty_t *vpty = _d2tk_base_get_atom(base, id, D2TK_ATOM_PTY,
		_term_event);

	const d2tk_coord_t width = height / 2;
	const d2tk_coord_t ncols = rect->w / width;
	const d2tk_coord_t nrows = rect->h / height;

	if(reinit)
	{
		_term_deinit(vpty);
	}

	if(vpty->height == 0)
	{
		if(_term_init(vpty, clone, data, height, ncols, nrows) != 0)
		{
			fprintf(stderr, "[%s] _term_init failed\n", __func__);
		}
	}

	const d2tk_style_t *old_style = d2tk_base_get_style(base);
	d2tk_style_t style = *old_style;

	style.fill_color[D2TK_TRIPLE_ACTIVE] = _term_dark(vpty);
	style.fill_color[D2TK_TRIPLE_ACTIVE_HOT] = _term_light(vpty);
	style.fill_color[D2TK_TRIPLE_ACTIVE_FOCUS] = _term_dark(vpty);
	style.fill_color[D2TK_TRIPLE_ACTIVE_HOT_FOCUS] = _term_light(vpty);
	style.font_face = "FiraCode-Regular.ttf";
	d2tk_base_set_style(base, &style);

	_term_resize(vpty, ncols, nrows);

	d2tk_state_t state = _term_behave(base, vpty, id, rect);

	_term_input(vpty);

	_term_draw(base, vpty, rect, d2tk_state_is_focused(state));

	if(_term_done(vpty))
	{
		_term_deinit(vpty);

		state |= D2TK_STATE_CLOSE;
	}

	d2tk_base_set_style(base, old_style);

	return state;
}