-
-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
terminal.c
1557 lines (1381 loc) · 41.1 KB
/
terminal.c
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
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// VT220/xterm-like terminal emulator.
// Powered by libvterm http://www.leonerd.org.uk/code/libvterm
//
// libvterm is a pure C99 terminal emulation library with abstract input and
// display. This means that the library needs to read data from the master fd
// and feed VTerm instances, which will invoke user callbacks with screen
// update instructions that must be mirrored to the real display.
//
// Keys are sent to VTerm instances by calling
// vterm_keyboard_key/vterm_keyboard_unichar, which generates byte streams that
// must be fed back to the master fd.
//
// Nvim buffers are used as the display mechanism for both the visible screen
// and the scrollback buffer.
//
// When a line becomes invisible due to a decrease in screen height or because
// a line was pushed up during normal terminal output, we store the line
// information in the scrollback buffer, which is mirrored in the nvim buffer
// by appending lines just above the visible part of the buffer.
//
// When the screen height increases, libvterm will ask for a row in the
// scrollback buffer, which is mirrored in the nvim buffer displaying lines
// that were previously invisible.
//
// The vterm->nvim synchronization is performed in intervals of 10 milliseconds,
// to minimize screen updates when receiving large bursts of data.
//
// This module is decoupled from the processes that normally feed it data, so
// it's possible to use it as a general purpose console buffer (possibly as a
// log/display mechanism for nvim in the future)
//
// Inspired by: vimshell http://www.wana.at/vimshell
// Conque https://code.google.com/p/conque
// Some code from pangoterm http://www.leonerd.org.uk/code/pangoterm
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <vterm.h>
#include "nvim/api/private/helpers.h"
#include "nvim/ascii.h"
#include "nvim/buffer.h"
#include "nvim/change.h"
#include "nvim/edit.h"
#include "nvim/event/loop.h"
#include "nvim/event/time.h"
#include "nvim/ex_cmds.h"
#include "nvim/ex_docmd.h"
#include "nvim/fileio.h"
#include "nvim/getchar.h"
#include "nvim/highlight.h"
#include "nvim/keymap.h"
#include "nvim/log.h"
#include "nvim/macros.h"
#include "nvim/main.h"
#include "nvim/map.h"
#include "nvim/mbyte.h"
#include "nvim/memline.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/misc1.h"
#include "nvim/mouse.h"
#include "nvim/move.h"
#include "nvim/option.h"
#include "nvim/os/input.h"
#include "nvim/screen.h"
#include "nvim/state.h"
#include "nvim/syntax.h"
#include "nvim/terminal.h"
#include "nvim/ui.h"
#include "nvim/vim.h"
#include "nvim/window.h"
typedef struct terminal_state {
VimState state;
Terminal *term;
int save_rd; // saved value of RedrawingDisabled
bool close;
bool got_bsl; // if the last input was <C-\>
} TerminalState;
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "terminal.c.generated.h"
#endif
// Delay for refreshing the terminal buffer after receiving updates from
// libvterm. Improves performance when receiving large bursts of data.
#define REFRESH_DELAY 10
static TimeWatcher refresh_timer;
static bool refresh_pending = false;
typedef struct {
size_t cols;
VTermScreenCell cells[];
} ScrollbackLine;
struct terminal {
TerminalOptions opts; // options passed to terminal_open
VTerm *vt;
VTermScreen *vts;
// buffer used to:
// - convert VTermScreen cell arrays into utf8 strings
// - receive data from libvterm as a result of key presses.
char textbuf[0x1fff];
ScrollbackLine **sb_buffer; // Scrollback buffer storage for libvterm
size_t sb_current; // number of rows pushed to sb_buffer
size_t sb_size; // sb_buffer size
// "virtual index" that points to the first sb_buffer row that we need to
// push to the terminal buffer when refreshing the scrollback. When negative,
// it actually points to entries that are no longer in sb_buffer (because the
// window height has increased) and must be deleted from the terminal buffer
int sb_pending;
// buf_T instance that acts as a "drawing surface" for libvterm
// we can't store a direct reference to the buffer because the
// refresh_timer_cb may be called after the buffer was freed, and there's
// no way to know if the memory was reused.
handle_T buf_handle;
// program exited
bool closed, destroy;
// some vterm properties
bool forward_mouse;
int invalid_start, invalid_end; // invalid rows in libvterm screen
struct {
int row, col;
bool visible;
} cursor;
int pressed_button; // which mouse button is pressed
bool pending_resize; // pending width/height
bool color_set[16];
size_t refcount; // reference count
};
static VTermScreenCallbacks vterm_screen_callbacks = {
.damage = term_damage,
.moverect = term_moverect,
.movecursor = term_movecursor,
.settermprop = term_settermprop,
.bell = term_bell,
.sb_pushline = term_sb_push,
.sb_popline = term_sb_pop,
};
static PMap(ptr_t) invalidated_terminals = MAP_INIT;
void terminal_init(void)
{
time_watcher_init(&main_loop, &refresh_timer, NULL);
// refresh_timer_cb will redraw the screen which can call vimscript
refresh_timer.events = multiqueue_new_child(main_loop.events);
}
void terminal_teardown(void)
{
time_watcher_stop(&refresh_timer);
multiqueue_free(refresh_timer.events);
time_watcher_close(&refresh_timer, NULL);
pmap_destroy(ptr_t)(&invalidated_terminals);
// terminal_destroy might be called after terminal_teardown is invoked
// make sure it is in an empty, valid state
pmap_init(ptr_t, &invalidated_terminals);
}
// public API {{{
Terminal *terminal_open(buf_T *buf, TerminalOptions opts)
{
// Create a new terminal instance and configure it
Terminal *rv = xcalloc(1, sizeof(Terminal));
rv->opts = opts;
rv->cursor.visible = true;
// Associate the terminal instance with the new buffer
rv->buf_handle = buf->handle;
buf->terminal = rv;
// Create VTerm
rv->vt = vterm_new(opts.height, opts.width);
vterm_set_utf8(rv->vt, 1);
// Setup state
VTermState *state = vterm_obtain_state(rv->vt);
// Set up screen
rv->vts = vterm_obtain_screen(rv->vt);
vterm_screen_enable_altscreen(rv->vts, true);
// delete empty lines at the end of the buffer
vterm_screen_set_callbacks(rv->vts, &vterm_screen_callbacks, rv);
vterm_screen_set_damage_merge(rv->vts, VTERM_DAMAGE_SCROLL);
vterm_screen_reset(rv->vts, 1);
// force a initial refresh of the screen to ensure the buffer will always
// have as many lines as screen rows when refresh_scrollback is called
rv->invalid_start = 0;
rv->invalid_end = opts.height;
aco_save_T aco;
aucmd_prepbuf(&aco, buf);
refresh_screen(rv, buf);
set_option_value("buftype", 0, "terminal", OPT_LOCAL); // -V666
// Default settings for terminal buffers
buf->b_p_ma = false; // 'nomodifiable'
buf->b_p_ul = -1; // 'undolevels'
buf->b_p_scbk = // 'scrollback' (initialize local from global)
(p_scbk < 0) ? 10000 : MAX(1, p_scbk);
buf->b_p_tw = 0; // 'textwidth'
set_option_value("wrap", false, NULL, OPT_LOCAL);
set_option_value("list", false, NULL, OPT_LOCAL);
if (buf->b_ffname != NULL) {
buf_set_term_title(buf, (char *)buf->b_ffname);
}
RESET_BINDING(curwin);
// Reset cursor in current window.
curwin->w_cursor = (pos_T){ .lnum = 1, .col = 0, .coladd = 0 };
// Apply TermOpen autocmds _before_ configuring the scrollback buffer.
apply_autocmds(EVENT_TERMOPEN, NULL, NULL, false, buf);
// Local 'scrollback' _after_ autocmds.
buf->b_p_scbk = (buf->b_p_scbk < 1) ? SB_MAX : buf->b_p_scbk;
aucmd_restbuf(&aco);
// Configure the scrollback buffer.
rv->sb_size = (size_t)buf->b_p_scbk;
rv->sb_buffer = xmalloc(sizeof(ScrollbackLine *) * rv->sb_size);
// Configure the color palette. Try to get the color from:
//
// - b:terminal_color_{NUM}
// - g:terminal_color_{NUM}
// - the VTerm instance
for (int i = 0; i < 16; i++) {
RgbValue color_val = -1;
char var[64];
snprintf(var, sizeof(var), "terminal_color_%d", i);
char *name = get_config_string(var);
if (name) {
color_val = name_to_color(name);
xfree(name);
if (color_val != -1) {
VTermColor color;
vterm_color_rgb(&color,
(uint8_t)((color_val >> 16) & 0xFF),
(uint8_t)((color_val >> 8) & 0xFF),
(uint8_t)((color_val >> 0) & 0xFF));
vterm_state_set_palette_color(state, i, &color);
rv->color_set[i] = true;
}
}
}
return rv;
}
void terminal_close(Terminal *term, int status)
{
if (term->closed) {
if (status == -1 && !term->refcount) {
terminal_destroy(term);
}
return;
}
term->forward_mouse = false;
// flush any pending changes to the buffer
if (!exiting) {
block_autocmds();
refresh_terminal(term);
unblock_autocmds();
}
buf_T *buf = handle_get_buffer(term->buf_handle);
term->closed = true;
if (status == -1 || exiting) {
// If status is -1, this was called by close_buffer(buffer.c). Or if
// exiting, we must inform the buffer the terminal no longer exists so that
// close_buffer() doesn't call this again.
term->buf_handle = 0;
if (buf) {
buf->terminal = NULL;
}
if (!term->refcount) {
// We should not wait for the user to press a key.
term->opts.close_cb(term->opts.data);
}
} else {
char msg[sizeof("\r\n[Process exited ]") + NUMBUFLEN];
snprintf(msg, sizeof msg, "\r\n[Process exited %d]", status);
terminal_receive(term, msg, strlen(msg));
}
if (buf && !is_autocmd_blocked()) {
dict_T *dict = get_vim_var_dict(VV_EVENT);
tv_dict_add_nr(dict, S_LEN("status"), status);
apply_autocmds(EVENT_TERMCLOSE, NULL, NULL, false, buf);
tv_dict_clear(dict);
}
}
void terminal_check_size(Terminal *term)
{
if (term->closed) {
return;
}
int curwidth, curheight;
vterm_get_size(term->vt, &curheight, &curwidth);
uint16_t width = 0, height = 0;
FOR_ALL_TAB_WINDOWS(tp, wp) {
if (wp->w_buffer && wp->w_buffer->terminal == term) {
const uint16_t win_width =
(uint16_t)(MAX(0, wp->w_width_inner - win_col_off(wp)));
width = MAX(width, win_width);
height = (uint16_t)MAX(height, wp->w_height_inner);
}
}
// if no window displays the terminal, or such all windows are zero-height,
// don't resize the terminal.
if ((curheight == height && curwidth == width) || height == 0 || width == 0) {
return;
}
vterm_set_size(term->vt, height, width);
vterm_screen_flush_damage(term->vts);
term->pending_resize = true;
invalidate_terminal(term, -1, -1);
}
void terminal_enter(void)
{
buf_T *buf = curbuf;
assert(buf->terminal); // Should only be called when curbuf has a terminal.
TerminalState state, *s = &state;
memset(s, 0, sizeof(TerminalState));
s->term = buf->terminal;
stop_insert_mode = false;
// Ensure the terminal is properly sized. Ideally window size management
// code should always have resized the terminal already, but check here to
// be sure.
terminal_check_size(s->term);
int save_state = State;
s->save_rd = RedrawingDisabled;
State = TERM_FOCUS;
mapped_ctrl_c |= TERM_FOCUS; // Always map CTRL-C to avoid interrupt.
RedrawingDisabled = false;
// Disable these options in terminal-mode. They are nonsense because cursor is
// placed at end of buffer to "follow" output. #11072
win_T *save_curwin = curwin;
bool save_w_p_cul = curwin->w_p_cul;
char_u *save_w_p_culopt = NULL;
char_u save_w_p_culopt_flags = curwin->w_p_culopt_flags;
int save_w_p_cuc = curwin->w_p_cuc;
long save_w_p_so = curwin->w_p_so;
long save_w_p_siso = curwin->w_p_siso;
if (curwin->w_p_cul && curwin->w_p_culopt_flags & CULOPT_NBR) {
if (strcmp((char *)curwin->w_p_culopt, "number")) {
save_w_p_culopt = curwin->w_p_culopt;
curwin->w_p_culopt = (char_u *)xstrdup("number");
}
curwin->w_p_culopt_flags = CULOPT_NBR;
} else {
curwin->w_p_cul = false;
}
curwin->w_p_cuc = false;
curwin->w_p_so = 0;
curwin->w_p_siso = 0;
adjust_topline(s->term, buf, 0); // scroll to end
// erase the unfocused cursor
invalidate_terminal(s->term, s->term->cursor.row, s->term->cursor.row + 1);
showmode();
curwin->w_redr_status = true; // For mode() in statusline. #8323
ui_busy_start();
apply_autocmds(EVENT_TERMENTER, NULL, NULL, false, curbuf);
s->state.execute = terminal_execute;
s->state.check = terminal_check;
state_enter(&s->state);
restart_edit = 0;
State = save_state;
RedrawingDisabled = s->save_rd;
apply_autocmds(EVENT_TERMLEAVE, NULL, NULL, false, curbuf);
if (save_curwin == curwin) { // save_curwin may be invalid (window closed)!
curwin->w_p_cul = save_w_p_cul;
if (save_w_p_culopt) {
xfree(curwin->w_p_culopt);
curwin->w_p_culopt = save_w_p_culopt;
}
curwin->w_p_culopt_flags = save_w_p_culopt_flags;
curwin->w_p_cuc = save_w_p_cuc;
curwin->w_p_so = save_w_p_so;
curwin->w_p_siso = save_w_p_siso;
} else if (save_w_p_culopt) {
xfree(save_w_p_culopt);
}
// draw the unfocused cursor
invalidate_terminal(s->term, s->term->cursor.row, s->term->cursor.row + 1);
if (curbuf->terminal == s->term && !s->close) {
terminal_check_cursor();
}
unshowmode(true);
ui_busy_stop();
if (s->close) {
bool wipe = s->term->buf_handle != 0;
s->term->opts.close_cb(s->term->opts.data);
if (wipe) {
do_cmdline_cmd("bwipeout!");
}
}
}
static void terminal_check_cursor(void)
{
Terminal *term = curbuf->terminal;
curwin->w_wrow = term->cursor.row;
curwin->w_wcol = term->cursor.col + win_col_off(curwin);
curwin->w_cursor.lnum = MIN(curbuf->b_ml.ml_line_count,
row_to_linenr(term, term->cursor.row));
// Nudge cursor when returning to normal-mode.
int off = is_focused(term) ? 0 : (curwin->w_p_rl ? 1 : -1);
curwin->w_cursor.col = MAX(0, term->cursor.col + win_col_off(curwin) + off);
curwin->w_cursor.coladd = 0;
mb_check_adjust_col(curwin);
}
// Function executed before each iteration of terminal mode.
// Return:
// 1 if the iteration should continue normally
// 0 if the main loop must exit
static int terminal_check(VimState *state)
{
if (stop_insert_mode) {
return 0;
}
terminal_check_cursor();
if (must_redraw) {
update_screen(0);
}
if (need_maketitle) { // Update title in terminal-mode. #7248
maketitle();
}
setcursor();
ui_flush();
return 1;
}
static int terminal_execute(VimState *state, int key)
{
TerminalState *s = (TerminalState *)state;
switch (key) {
case K_LEFTMOUSE:
case K_LEFTDRAG:
case K_LEFTRELEASE:
case K_MOUSEMOVE:
case K_MIDDLEMOUSE:
case K_MIDDLEDRAG:
case K_MIDDLERELEASE:
case K_RIGHTMOUSE:
case K_RIGHTDRAG:
case K_RIGHTRELEASE:
case K_MOUSEDOWN:
case K_MOUSEUP:
if (send_mouse_event(s->term, key)) {
return 0;
}
break;
case K_EVENT:
// We cannot let an event free the terminal yet. It is still needed.
s->term->refcount++;
state_handle_k_event();
s->term->refcount--;
if (s->term->buf_handle == 0) {
s->close = true;
return 0;
}
break;
case K_COMMAND:
do_cmdline(NULL, getcmdkeycmd, NULL, 0);
break;
case Ctrl_N:
if (s->got_bsl) {
return 0;
}
FALLTHROUGH;
default:
if (key == Ctrl_BSL && !s->got_bsl) {
s->got_bsl = true;
break;
}
if (s->term->closed) {
s->close = true;
return 0;
}
s->got_bsl = false;
terminal_send_key(s->term, key);
}
if (curbuf->terminal == NULL) {
return 0;
}
if (s->term != curbuf->terminal) {
invalidate_terminal(s->term, s->term->cursor.row, s->term->cursor.row + 1);
invalidate_terminal(curbuf->terminal,
curbuf->terminal->cursor.row,
curbuf->terminal->cursor.row + 1);
s->term = curbuf->terminal;
}
return 1;
}
void terminal_destroy(Terminal *term)
{
buf_T *buf = handle_get_buffer(term->buf_handle);
if (buf) {
term->buf_handle = 0;
buf->terminal = NULL;
}
if (!term->refcount) {
if (pmap_has(ptr_t)(&invalidated_terminals, term)) {
// flush any pending changes to the buffer
block_autocmds();
refresh_terminal(term);
unblock_autocmds();
pmap_del(ptr_t)(&invalidated_terminals, term);
}
for (size_t i = 0; i < term->sb_current; i++) {
xfree(term->sb_buffer[i]);
}
xfree(term->sb_buffer);
vterm_free(term->vt);
xfree(term);
}
}
void terminal_send(Terminal *term, char *data, size_t size)
{
if (term->closed) {
return;
}
term->opts.write_cb(data, size, term->opts.data);
}
static bool is_filter_char(int c)
{
unsigned int flag = 0;
switch (c) {
case 0x08:
flag = TPF_BS;
break;
case 0x09:
flag = TPF_HT;
break;
case 0x0A:
case 0x0D:
break;
case 0x0C:
flag = TPF_FF;
break;
case 0x1b:
flag = TPF_ESC;
break;
case 0x7F:
flag = TPF_DEL;
break;
default:
if (c < ' ') {
flag = TPF_C0;
} else if (c >= 0x80 && c <= 0x9F) {
flag = TPF_C1;
}
}
return !!(tpf_flags & flag);
}
void terminal_paste(long count, char_u **y_array, size_t y_size)
{
if (y_size == 0) {
return;
}
vterm_keyboard_start_paste(curbuf->terminal->vt);
terminal_flush_output(curbuf->terminal);
size_t buff_len = STRLEN(y_array[0]);
char_u *buff = xmalloc(buff_len);
for (int i = 0; i < count; i++) { // -V756
// feed the lines to the terminal
for (size_t j = 0; j < y_size; j++) {
if (j) {
// terminate the previous line
terminal_send(curbuf->terminal, "\n", 1);
}
size_t len = STRLEN(y_array[j]);
if (len > buff_len) {
buff = xrealloc(buff, len);
buff_len = len;
}
char_u *dst = buff;
char_u *src = y_array[j];
while (*src != '\0') {
len = (size_t)utf_ptr2len(src);
int c = utf_ptr2char(src);
if (!is_filter_char(c)) {
memcpy(dst, src, len);
dst += len;
}
src += len;
}
terminal_send(curbuf->terminal, (char *)buff, (size_t)(dst - buff));
}
}
xfree(buff);
vterm_keyboard_end_paste(curbuf->terminal->vt);
terminal_flush_output(curbuf->terminal);
}
void terminal_flush_output(Terminal *term)
{
size_t len = vterm_output_read(term->vt, term->textbuf,
sizeof(term->textbuf));
terminal_send(term, term->textbuf, len);
}
void terminal_send_key(Terminal *term, int c)
{
VTermModifier mod = VTERM_MOD_NONE;
// Convert K_ZERO back to ASCII
if (c == K_ZERO) {
c = Ctrl_AT;
}
VTermKey key = convert_key(c, &mod);
if (key) {
vterm_keyboard_key(term->vt, key, mod);
} else {
vterm_keyboard_unichar(term->vt, (uint32_t)c, mod);
}
terminal_flush_output(term);
}
void terminal_receive(Terminal *term, char *data, size_t len)
{
if (!data) {
return;
}
vterm_input_write(term->vt, data, len);
vterm_screen_flush_damage(term->vts);
}
static int get_rgb(VTermState *state, VTermColor color)
{
vterm_state_convert_color_to_rgb(state, &color);
return RGB_(color.rgb.red, color.rgb.green, color.rgb.blue);
}
void terminal_get_line_attributes(Terminal *term, win_T *wp, int linenr, int *term_attrs)
{
int height, width;
vterm_get_size(term->vt, &height, &width);
VTermState *state = vterm_obtain_state(term->vt);
assert(linenr);
int row = linenr_to_row(term, linenr);
if (row >= height) {
// Terminal height was decreased but the change wasn't reflected into the
// buffer yet
return;
}
width = MIN(TERM_ATTRS_MAX, width);
for (int col = 0; col < width; col++) {
VTermScreenCell cell;
bool color_valid = fetch_cell(term, row, col, &cell);
bool fg_default = !color_valid || VTERM_COLOR_IS_DEFAULT_FG(&cell.fg);
bool bg_default = !color_valid || VTERM_COLOR_IS_DEFAULT_BG(&cell.bg);
// Get the rgb value set by libvterm.
int vt_fg = fg_default ? -1 : get_rgb(state, cell.fg);
int vt_bg = bg_default ? -1 : get_rgb(state, cell.bg);
bool fg_indexed = VTERM_COLOR_IS_INDEXED(&cell.fg);
bool bg_indexed = VTERM_COLOR_IS_INDEXED(&cell.bg);
int vt_fg_idx = ((!fg_default && fg_indexed) ? cell.fg.indexed.idx + 1 : 0);
int vt_bg_idx = ((!bg_default && bg_indexed) ? cell.bg.indexed.idx + 1 : 0);
bool fg_set = vt_fg_idx && vt_fg_idx <= 16 && term->color_set[vt_fg_idx-1];
bool bg_set = vt_bg_idx && vt_bg_idx <= 16 && term->color_set[vt_bg_idx-1];
int hl_attrs = (cell.attrs.bold ? HL_BOLD : 0)
| (cell.attrs.italic ? HL_ITALIC : 0)
| (cell.attrs.reverse ? HL_INVERSE : 0)
| (cell.attrs.underline ? HL_UNDERLINE : 0)
| (cell.attrs.strike ? HL_STRIKETHROUGH: 0)
| ((fg_indexed && !fg_set) ? HL_FG_INDEXED : 0)
| ((bg_indexed && !bg_set) ? HL_BG_INDEXED : 0);
int attr_id = 0;
if (hl_attrs || !fg_default || !bg_default) {
attr_id = hl_get_term_attr(&(HlAttrs) {
.cterm_ae_attr = (int16_t)hl_attrs,
.cterm_fg_color = vt_fg_idx,
.cterm_bg_color = vt_bg_idx,
.rgb_ae_attr = (int16_t)hl_attrs,
.rgb_fg_color = vt_fg,
.rgb_bg_color = vt_bg,
.rgb_sp_color = -1,
.hl_blend = -1,
});
}
if (term->cursor.visible && term->cursor.row == row
&& term->cursor.col == col) {
attr_id = hl_combine_attr(attr_id,
is_focused(term) && wp == curwin
? win_hl_attr(wp, HLF_TERM)
: win_hl_attr(wp, HLF_TERMNC));
}
term_attrs[col] = attr_id;
}
}
Buffer terminal_buf(const Terminal *term)
{
return term->buf_handle;
}
bool terminal_running(const Terminal *term)
{
return !term->closed;
}
// }}}
// libvterm callbacks {{{
static int term_damage(VTermRect rect, void *data)
{
invalidate_terminal(data, rect.start_row, rect.end_row);
return 1;
}
static int term_moverect(VTermRect dest, VTermRect src, void *data)
{
invalidate_terminal(data, MIN(dest.start_row, src.start_row),
MAX(dest.end_row, src.end_row));
return 1;
}
static int term_movecursor(VTermPos new, VTermPos old, int visible, void *data)
{
Terminal *term = data;
term->cursor.row = new.row;
term->cursor.col = new.col;
invalidate_terminal(term, old.row, old.row + 1);
invalidate_terminal(term, new.row, new.row + 1);
return 1;
}
static void buf_set_term_title(buf_T *buf, char *title)
FUNC_ATTR_NONNULL_ALL
{
Error err = ERROR_INIT;
dict_set_var(buf->b_vars,
STATIC_CSTR_AS_STRING("term_title"),
STRING_OBJ(cstr_as_string(title)),
false,
false,
&err);
api_clear_error(&err);
status_redraw_buf(buf);
}
static int term_settermprop(VTermProp prop, VTermValue *val, void *data)
{
Terminal *term = data;
switch (prop) {
case VTERM_PROP_ALTSCREEN:
break;
case VTERM_PROP_CURSORVISIBLE:
term->cursor.visible = val->boolean;
invalidate_terminal(term, term->cursor.row, term->cursor.row + 1);
break;
case VTERM_PROP_TITLE: {
buf_T *buf = handle_get_buffer(term->buf_handle);
buf_set_term_title(buf, val->string);
break;
}
case VTERM_PROP_MOUSE:
term->forward_mouse = (bool)val->number;
break;
default:
return 0;
}
return 1;
}
static int term_bell(void *data)
{
ui_call_bell();
return 1;
}
// Scrollback push handler (from pangoterm).
static int term_sb_push(int cols, const VTermScreenCell *cells, void *data)
{
Terminal *term = data;
if (!term->sb_size) {
return 0;
}
// copy vterm cells into sb_buffer
size_t c = (size_t)cols;
ScrollbackLine *sbrow = NULL;
if (term->sb_current == term->sb_size) {
if (term->sb_buffer[term->sb_current - 1]->cols == c) {
// Recycle old row if it's the right size
sbrow = term->sb_buffer[term->sb_current - 1];
} else {
xfree(term->sb_buffer[term->sb_current - 1]);
}
// Make room at the start by shifting to the right.
memmove(term->sb_buffer + 1, term->sb_buffer,
sizeof(term->sb_buffer[0]) * (term->sb_current - 1));
} else if (term->sb_current > 0) {
// Make room at the start by shifting to the right.
memmove(term->sb_buffer + 1, term->sb_buffer,
sizeof(term->sb_buffer[0]) * term->sb_current);
}
if (!sbrow) {
sbrow = xmalloc(sizeof(ScrollbackLine) + c * sizeof(sbrow->cells[0]));
sbrow->cols = c;
}
// New row is added at the start of the storage buffer.
term->sb_buffer[0] = sbrow;
if (term->sb_current < term->sb_size) {
term->sb_current++;
}
if (term->sb_pending < (int)term->sb_size) {
term->sb_pending++;
}
memcpy(sbrow->cells, cells, sizeof(cells[0]) * c);
pmap_put(ptr_t)(&invalidated_terminals, term, NULL);
return 1;
}
/// Scrollback pop handler (from pangoterm).
///
/// @param cols
/// @param cells VTerm state to update.
/// @param data Terminal
static int term_sb_pop(int cols, VTermScreenCell *cells, void *data)
{
Terminal *term = data;
if (!term->sb_current) {
return 0;
}
if (term->sb_pending) {
term->sb_pending--;
}
ScrollbackLine *sbrow = term->sb_buffer[0];
term->sb_current--;
// Forget the "popped" row by shifting the rest onto it.
memmove(term->sb_buffer, term->sb_buffer + 1,
sizeof(term->sb_buffer[0]) * (term->sb_current));
size_t cols_to_copy = (size_t)cols;
if (cols_to_copy > sbrow->cols) {
cols_to_copy = sbrow->cols;
}
// copy to vterm state
memcpy(cells, sbrow->cells, sizeof(cells[0]) * cols_to_copy);
for (size_t col = cols_to_copy; col < (size_t)cols; col++) {
cells[col].chars[0] = 0;
cells[col].width = 1;
}
xfree(sbrow);
pmap_put(ptr_t)(&invalidated_terminals, term, NULL);
return 1;
}
// }}}
// input handling {{{
static void convert_modifiers(int key, VTermModifier *statep)
{
if (mod_mask & MOD_MASK_SHIFT) {
*statep |= VTERM_MOD_SHIFT;
}
if (mod_mask & MOD_MASK_CTRL) {
*statep |= VTERM_MOD_CTRL;
}
if (mod_mask & MOD_MASK_ALT) {
*statep |= VTERM_MOD_ALT;
}
switch (key) {
case K_S_TAB:
case K_S_UP:
case K_S_DOWN:
case K_S_LEFT:
case K_S_RIGHT:
case K_S_F1:
case K_S_F2:
case K_S_F3:
case K_S_F4:
case K_S_F5:
case K_S_F6:
case K_S_F7:
case K_S_F8:
case K_S_F9:
case K_S_F10:
case K_S_F11:
case K_S_F12:
*statep |= VTERM_MOD_SHIFT;
break;
case K_C_LEFT:
case K_C_RIGHT:
*statep |= VTERM_MOD_CTRL;
break;
}
}
static VTermKey convert_key(int key, VTermModifier *statep)
{
convert_modifiers(key, statep);
switch (key) {
case K_BS:
return VTERM_KEY_BACKSPACE;
case K_S_TAB:
FALLTHROUGH;
case TAB:
return VTERM_KEY_TAB;
case Ctrl_M:
return VTERM_KEY_ENTER;
case ESC:
return VTERM_KEY_ESCAPE;
case K_S_UP:
FALLTHROUGH;
case K_UP:
return VTERM_KEY_UP;
case K_S_DOWN:
FALLTHROUGH;
case K_DOWN:
return VTERM_KEY_DOWN;
case K_S_LEFT: