/
tui.c
2175 lines (1990 loc) · 73 KB
/
tui.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
// Terminal UI functions. Invoked (by ui_bridge.c) on the TUI thread.
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <limits.h>
#include <uv.h>
#include <unibilium.h>
#if defined(HAVE_TERMIOS_H)
# include <termios.h>
#endif
#include "nvim/lib/kvec.h"
#include "nvim/ascii.h"
#include "nvim/vim.h"
#include "nvim/log.h"
#include "nvim/ui.h"
#include "nvim/highlight.h"
#include "nvim/map.h"
#include "nvim/main.h"
#include "nvim/memory.h"
#include "nvim/option.h"
#include "nvim/api/vim.h"
#include "nvim/api/private/helpers.h"
#include "nvim/event/loop.h"
#include "nvim/event/signal.h"
#include "nvim/os/input.h"
#include "nvim/os/os.h"
#include "nvim/os/signal.h"
#include "nvim/os/tty.h"
#ifdef WIN32
# include "nvim/os/os_win_console.h"
#endif
#include "nvim/strings.h"
#include "nvim/syntax.h"
#include "nvim/ui_bridge.h"
#include "nvim/ugrid.h"
#include "nvim/tui/input.h"
#include "nvim/tui/tui.h"
#include "nvim/tui/terminfo.h"
#include "nvim/cursor_shape.h"
#include "nvim/macros.h"
// Space reserved in two output buffers to make the cursor normal or invisible
// when flushing. No existing terminal will require 32 bytes to do that.
#define CNORM_COMMAND_MAX_SIZE 32
#define OUTBUF_SIZE 0xffff
#define TOO_MANY_EVENTS 1000000
#define STARTS_WITH(str, prefix) (strlen(str) >= (sizeof(prefix) - 1) \
&& 0 == memcmp((str), (prefix), sizeof(prefix) - 1))
#define TMUX_WRAP(is_tmux, seq) ((is_tmux) \
? DCS_STR "tmux;\x1b" seq STERM_STR : seq)
#define SCREEN_TMUX_WRAP(is_screen, is_tmux, seq) \
((is_screen) \
? DCS_STR seq STERM_STR : (is_tmux) \
? DCS_STR "tmux;\x1b" seq STERM_STR : seq)
#define LINUXSET0C "\x1b[?0c"
#define LINUXSET1C "\x1b[?1c"
#ifdef NVIM_UNIBI_HAS_VAR_FROM
#define UNIBI_SET_NUM_VAR(var, num) \
do { \
(var) = unibi_var_from_num((num)); \
} while (0)
#else
#define UNIBI_SET_NUM_VAR(var, num) (var).i = (num);
#endif
typedef struct {
int top, bot, left, right;
} Rect;
typedef struct {
UIBridgeData *bridge;
Loop *loop;
unibi_var_t params[9];
char buf[OUTBUF_SIZE];
size_t bufpos;
char norm[CNORM_COMMAND_MAX_SIZE];
char invis[CNORM_COMMAND_MAX_SIZE];
size_t normlen, invislen;
TermInput input;
uv_loop_t write_loop;
unibi_term *ut;
union {
uv_tty_t tty;
uv_pipe_t pipe;
} output_handle;
bool out_isatty;
SignalWatcher winch_handle, cont_handle;
bool cont_received;
UGrid grid;
kvec_t(Rect) invalid_regions;
int row, col;
int out_fd;
bool scroll_region_is_full_screen;
bool can_change_scroll_region;
bool can_set_lr_margin; // smglr
bool can_set_left_right_margin;
bool can_scroll;
bool can_erase_chars;
bool immediate_wrap_after_last_column;
bool bce;
bool mouse_enabled;
bool busy, is_invisible, want_invisible;
bool cork, overflow;
bool cursor_color_changed;
bool is_starting;
FILE *screenshot;
cursorentry_T cursor_shapes[SHAPE_IDX_COUNT];
HlAttrs clear_attrs;
kvec_t(HlAttrs) attrs;
int print_attr_id;
bool default_attr;
bool can_clear_attr;
ModeShape showing_mode;
struct {
int enable_mouse, disable_mouse;
int enable_bracketed_paste, disable_bracketed_paste;
int enable_lr_margin, disable_lr_margin;
int enter_strikethrough_mode;
int set_rgb_foreground, set_rgb_background;
int set_cursor_color;
int reset_cursor_color;
int enable_focus_reporting, disable_focus_reporting;
int resize_screen;
int reset_scroll_region;
int set_cursor_style, reset_cursor_style;
int save_title, restore_title;
int get_bg;
int set_underline_style;
int set_underline_color;
} unibi_ext;
char *space_buf;
} TUIData;
static bool volatile got_winch = false;
static bool did_user_set_dimensions = false;
static bool cursor_style_enabled = false;
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "tui/tui.c.generated.h"
#endif
UI *tui_start(void)
{
UI *ui = xcalloc(1, sizeof(UI)); // Freed by ui_bridge_stop().
ui->stop = tui_stop;
ui->grid_resize = tui_grid_resize;
ui->grid_clear = tui_grid_clear;
ui->grid_cursor_goto = tui_grid_cursor_goto;
ui->mode_info_set = tui_mode_info_set;
ui->update_menu = tui_update_menu;
ui->busy_start = tui_busy_start;
ui->busy_stop = tui_busy_stop;
ui->mouse_on = tui_mouse_on;
ui->mouse_off = tui_mouse_off;
ui->mode_change = tui_mode_change;
ui->grid_scroll = tui_grid_scroll;
ui->hl_attr_define = tui_hl_attr_define;
ui->bell = tui_bell;
ui->visual_bell = tui_visual_bell;
ui->default_colors_set = tui_default_colors_set;
ui->flush = tui_flush;
ui->suspend = tui_suspend;
ui->set_title = tui_set_title;
ui->set_icon = tui_set_icon;
ui->screenshot = tui_screenshot;
ui->option_set= tui_option_set;
ui->raw_line = tui_raw_line;
memset(ui->ui_ext, 0, sizeof(ui->ui_ext));
ui->ui_ext[kUILinegrid] = true;
ui->ui_ext[kUITermColors] = true;
return ui_bridge_attach(ui, tui_main, tui_scheduler);
}
static size_t unibi_pre_fmt_str(TUIData *data, unsigned int unibi_index,
char * buf, size_t len)
{
const char *str = unibi_get_str(data->ut, unibi_index);
if (!str) {
return 0U;
}
return unibi_run(str, data->params, buf, len);
}
static void termname_set_event(void **argv)
{
char *termname = argv[0];
set_tty_option("term", termname);
// Do not free termname, it is freed by set_tty_option.
}
static void terminfo_start(UI *ui)
{
TUIData *data = ui->data;
data->scroll_region_is_full_screen = true;
data->bufpos = 0;
data->default_attr = false;
data->can_clear_attr = false;
data->is_invisible = true;
data->want_invisible = false;
data->busy = false;
data->cork = false;
data->overflow = false;
data->cursor_color_changed = false;
data->showing_mode = SHAPE_IDX_N;
data->unibi_ext.enable_mouse = -1;
data->unibi_ext.disable_mouse = -1;
data->unibi_ext.set_cursor_color = -1;
data->unibi_ext.reset_cursor_color = -1;
data->unibi_ext.enable_bracketed_paste = -1;
data->unibi_ext.disable_bracketed_paste = -1;
data->unibi_ext.enter_strikethrough_mode = -1;
data->unibi_ext.enable_lr_margin = -1;
data->unibi_ext.disable_lr_margin = -1;
data->unibi_ext.enable_focus_reporting = -1;
data->unibi_ext.disable_focus_reporting = -1;
data->unibi_ext.resize_screen = -1;
data->unibi_ext.reset_scroll_region = -1;
data->unibi_ext.set_cursor_style = -1;
data->unibi_ext.reset_cursor_style = -1;
data->unibi_ext.get_bg = -1;
data->unibi_ext.set_underline_color = -1;
data->out_fd = STDOUT_FILENO;
data->out_isatty = os_isatty(data->out_fd);
const char *term = os_getenv("TERM");
#ifdef WIN32
os_tty_guess_term(&term, data->out_fd);
os_setenv("TERM", term, 1);
// Old os_getenv() pointer is invalid after os_setenv(), fetch it again.
term = os_getenv("TERM");
#endif
// Set up unibilium/terminfo.
char *termname = NULL;
if (term) {
os_env_var_lock();
data->ut = unibi_from_term(term);
os_env_var_unlock();
if (data->ut) {
termname = xstrdup(term);
}
}
if (!data->ut) {
data->ut = terminfo_from_builtin(term, &termname);
}
// Update 'term' option.
loop_schedule_deferred(&main_loop,
event_create(termname_set_event, 1, termname));
// None of the following work over SSH; see :help TERM .
const char *colorterm = os_getenv("COLORTERM");
const char *termprg = os_getenv("TERM_PROGRAM");
const char *vte_version_env = os_getenv("VTE_VERSION");
long vtev = vte_version_env ? strtol(vte_version_env, NULL, 10) : 0;
bool iterm_env = termprg && strstr(termprg, "iTerm.app");
bool nsterm = (termprg && strstr(termprg, "Apple_Terminal"))
|| terminfo_is_term_family(term, "nsterm");
bool konsole = terminfo_is_term_family(term, "konsole")
|| os_getenv("KONSOLE_PROFILE_NAME")
|| os_getenv("KONSOLE_DBUS_SESSION");
const char *konsolev_env = os_getenv("KONSOLE_VERSION");
long konsolev = konsolev_env ? strtol(konsolev_env, NULL, 10)
: (konsole ? 1 : 0);
patch_terminfo_bugs(data, term, colorterm, vtev, konsolev, iterm_env, nsterm);
augment_terminfo(data, term, vtev, konsolev, iterm_env, nsterm);
data->can_change_scroll_region =
!!unibi_get_str(data->ut, unibi_change_scroll_region);
data->can_set_lr_margin =
!!unibi_get_str(data->ut, unibi_set_lr_margin);
data->can_set_left_right_margin =
!!unibi_get_str(data->ut, unibi_set_left_margin_parm)
&& !!unibi_get_str(data->ut, unibi_set_right_margin_parm);
data->can_scroll =
!!unibi_get_str(data->ut, unibi_delete_line)
&& !!unibi_get_str(data->ut, unibi_parm_delete_line)
&& !!unibi_get_str(data->ut, unibi_insert_line)
&& !!unibi_get_str(data->ut, unibi_parm_insert_line);
data->can_erase_chars = !!unibi_get_str(data->ut, unibi_erase_chars);
data->immediate_wrap_after_last_column =
terminfo_is_term_family(term, "conemu")
|| terminfo_is_term_family(term, "cygwin")
|| terminfo_is_term_family(term, "win32con")
|| terminfo_is_term_family(term, "interix");
data->bce = unibi_get_bool(data->ut, unibi_back_color_erase);
data->normlen = unibi_pre_fmt_str(data, unibi_cursor_normal,
data->norm, sizeof data->norm);
data->invislen = unibi_pre_fmt_str(data, unibi_cursor_invisible,
data->invis, sizeof data->invis);
// Set 't_Co' from the result of unibilium & fix_terminfo.
t_colors = unibi_get_num(data->ut, unibi_max_colors);
// Ask the terminal to send us the background color.
// If get_bg is sent at the same time after enter_ca_mode, tmux will not send
// get_bg to the host terminal. To avoid this, send get_bg before
// enter_ca_mode.
data->input.waiting_for_bg_response = 5;
unibi_out_ext(ui, data->unibi_ext.get_bg);
// Enter alternate screen, save title, and clear.
// NOTE: Do this *before* changing terminal settings. #6433
unibi_out(ui, unibi_enter_ca_mode);
// Save title/icon to the "stack". #4063
unibi_out_ext(ui, data->unibi_ext.save_title);
unibi_out(ui, unibi_keypad_xmit);
unibi_out(ui, unibi_clear_screen);
// Enable bracketed paste
unibi_out_ext(ui, data->unibi_ext.enable_bracketed_paste);
uv_loop_init(&data->write_loop);
if (data->out_isatty) {
uv_tty_init(&data->write_loop, &data->output_handle.tty, data->out_fd, 0);
#ifdef WIN32
uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_RAW);
#else
int retry_count = 10;
// A signal may cause uv_tty_set_mode() to fail (e.g., SIGCONT). Retry a
// few times. #12322
while (uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_IO) == UV_EINTR
&& retry_count > 0) {
retry_count--;
}
#endif
} else {
uv_pipe_init(&data->write_loop, &data->output_handle.pipe, 0);
uv_pipe_open(&data->output_handle.pipe, data->out_fd);
}
flush_buf(ui);
}
static void terminfo_stop(UI *ui)
{
TUIData *data = ui->data;
// Destroy output stuff
tui_mode_change(ui, (String)STRING_INIT, SHAPE_IDX_N);
tui_mouse_off(ui);
unibi_out(ui, unibi_exit_attribute_mode);
// Reset cursor to normal before exiting alternate screen.
unibi_out(ui, unibi_cursor_normal);
unibi_out(ui, unibi_keypad_local);
unibi_out(ui, unibi_exit_ca_mode);
// Restore title/icon from the "stack". #4063
unibi_out_ext(ui, data->unibi_ext.restore_title);
if (data->cursor_color_changed) {
unibi_out_ext(ui, data->unibi_ext.reset_cursor_color);
}
// Disable bracketed paste
unibi_out_ext(ui, data->unibi_ext.disable_bracketed_paste);
// Disable focus reporting
unibi_out_ext(ui, data->unibi_ext.disable_focus_reporting);
flush_buf(ui);
uv_tty_reset_mode();
uv_close((uv_handle_t *)&data->output_handle, NULL);
uv_run(&data->write_loop, UV_RUN_DEFAULT);
if (uv_loop_close(&data->write_loop)) {
abort();
}
unibi_destroy(data->ut);
}
static void tui_terminal_start(UI *ui)
{
TUIData *data = ui->data;
data->print_attr_id = -1;
ugrid_init(&data->grid);
terminfo_start(ui);
tui_guess_size(ui);
signal_watcher_start(&data->winch_handle, sigwinch_cb, SIGWINCH);
tinput_start(&data->input);
}
static void tui_terminal_after_startup(UI *ui)
FUNC_ATTR_NONNULL_ALL
{
TUIData *data = ui->data;
// Emit this after Nvim startup, not during. This works around a tmux
// 2.3 bug(?) which caused slow drawing during startup. #7649
unibi_out_ext(ui, data->unibi_ext.enable_focus_reporting);
flush_buf(ui);
}
static void tui_terminal_stop(UI *ui)
{
TUIData *data = ui->data;
if (uv_is_closing(STRUCT_CAST(uv_handle_t, &data->output_handle))) {
// Race between SIGCONT (tui.c) and SIGHUP (os/signal.c)? #8075
ELOG("TUI already stopped (race?)");
ui->data = NULL; // Flag UI as "stopped".
return;
}
tinput_stop(&data->input);
signal_watcher_stop(&data->winch_handle);
terminfo_stop(ui);
ugrid_free(&data->grid);
}
static void tui_stop(UI *ui)
{
tui_terminal_stop(ui);
ui->data = NULL; // Flag UI as "stopped".
}
/// Returns true if UI `ui` is stopped.
static bool tui_is_stopped(UI *ui)
{
return ui->data == NULL;
}
/// Main function of the TUI thread.
static void tui_main(UIBridgeData *bridge, UI *ui)
{
Loop tui_loop;
loop_init(&tui_loop, NULL);
TUIData *data = xcalloc(1, sizeof(TUIData));
ui->data = data;
data->bridge = bridge;
data->loop = &tui_loop;
data->is_starting = true;
data->screenshot = NULL;
kv_init(data->invalid_regions);
signal_watcher_init(data->loop, &data->winch_handle, ui);
signal_watcher_init(data->loop, &data->cont_handle, data);
#ifdef UNIX
signal_watcher_start(&data->cont_handle, sigcont_cb, SIGCONT);
#endif
// TODO(bfredl): zero hl is empty, send this explicitly?
kv_push(data->attrs, HLATTRS_INIT);
#if TERMKEY_VERSION_MAJOR > 0 || TERMKEY_VERSION_MINOR > 18
data->input.tk_ti_hook_fn = tui_tk_ti_getstr;
#endif
tinput_init(&data->input, &tui_loop);
tui_terminal_start(ui);
// Allow main thread to continue, we are ready to handle UI callbacks.
CONTINUE(bridge);
loop_schedule_deferred(&main_loop,
event_create(show_termcap_event, 1, data->ut));
// "Active" loop: first ~100 ms of startup.
for (size_t ms = 0; ms < 100 && !tui_is_stopped(ui);) {
ms += (loop_poll_events(&tui_loop, 20) ? 20 : 1);
}
if (!tui_is_stopped(ui)) {
tui_terminal_after_startup(ui);
}
// "Passive" (I/O-driven) loop: TUI thread "main loop".
while (!tui_is_stopped(ui)) {
loop_poll_events(&tui_loop, -1); // tui_loop.events is never processed
}
ui_bridge_stopped(bridge);
tinput_destroy(&data->input);
signal_watcher_stop(&data->cont_handle);
signal_watcher_close(&data->cont_handle, NULL);
signal_watcher_close(&data->winch_handle, NULL);
loop_close(&tui_loop, false);
kv_destroy(data->invalid_regions);
kv_destroy(data->attrs);
xfree(data->space_buf);
xfree(data);
}
/// Handoff point between the main (ui_bridge) thread and the TUI thread.
static void tui_scheduler(Event event, void *d)
{
UI *ui = d;
TUIData *data = ui->data;
loop_schedule_fast(data->loop, event); // `tui_loop` local to tui_main().
}
#ifdef UNIX
static void sigcont_cb(SignalWatcher *watcher, int signum, void *data)
{
((TUIData *)data)->cont_received = true;
}
#endif
static void sigwinch_cb(SignalWatcher *watcher, int signum, void *data)
{
got_winch = true;
UI *ui = data;
if (tui_is_stopped(ui)) {
return;
}
tui_guess_size(ui);
ui_schedule_refresh();
}
static bool attrs_differ(UI *ui, int id1, int id2, bool rgb)
{
TUIData *data = ui->data;
if (id1 == id2) {
return false;
} else if (id1 < 0 || id2 < 0) {
return true;
}
HlAttrs a1 = kv_A(data->attrs, (size_t)id1);
HlAttrs a2 = kv_A(data->attrs, (size_t)id2);
if (rgb) {
return a1.rgb_fg_color != a2.rgb_fg_color
|| a1.rgb_bg_color != a2.rgb_bg_color
|| a1.rgb_ae_attr != a2.rgb_ae_attr
|| a1.rgb_sp_color != a2.rgb_sp_color;
} else {
return a1.cterm_fg_color != a2.cterm_fg_color
|| a1.cterm_bg_color != a2.cterm_bg_color
|| a1.cterm_ae_attr != a2.cterm_ae_attr
|| (a1.cterm_ae_attr & (HL_UNDERLINE|HL_UNDERCURL)
&& a1.rgb_sp_color != a2.rgb_sp_color);
}
}
static void update_attrs(UI *ui, int attr_id)
{
TUIData *data = ui->data;
if (!attrs_differ(ui, attr_id, data->print_attr_id, ui->rgb)) {
data->print_attr_id = attr_id;
return;
}
data->print_attr_id = attr_id;
HlAttrs attrs = kv_A(data->attrs, (size_t)attr_id);
int attr = ui->rgb ? attrs.rgb_ae_attr : attrs.cterm_ae_attr;
bool bold = attr & HL_BOLD;
bool italic = attr & HL_ITALIC;
bool reverse = attr & HL_INVERSE;
bool standout = attr & HL_STANDOUT;
bool strikethrough = attr & HL_STRIKETHROUGH;
bool underline;
bool undercurl;
if (data->unibi_ext.set_underline_style != -1) {
underline = attr & HL_UNDERLINE;
undercurl = attr & HL_UNDERCURL;
} else {
underline = (attr & HL_UNDERLINE) || (attr & HL_UNDERCURL);
undercurl = false;
}
if (unibi_get_str(data->ut, unibi_set_attributes)) {
if (bold || reverse || underline || standout) {
UNIBI_SET_NUM_VAR(data->params[0], standout);
UNIBI_SET_NUM_VAR(data->params[1], underline);
UNIBI_SET_NUM_VAR(data->params[2], reverse);
UNIBI_SET_NUM_VAR(data->params[3], 0); // blink
UNIBI_SET_NUM_VAR(data->params[4], 0); // dim
UNIBI_SET_NUM_VAR(data->params[5], bold);
UNIBI_SET_NUM_VAR(data->params[6], 0); // blank
UNIBI_SET_NUM_VAR(data->params[7], 0); // protect
UNIBI_SET_NUM_VAR(data->params[8], 0); // alternate character set
unibi_out(ui, unibi_set_attributes);
} else if (!data->default_attr) {
unibi_out(ui, unibi_exit_attribute_mode);
}
} else {
if (!data->default_attr) {
unibi_out(ui, unibi_exit_attribute_mode);
}
if (bold) {
unibi_out(ui, unibi_enter_bold_mode);
}
if (underline) {
unibi_out(ui, unibi_enter_underline_mode);
}
if (standout) {
unibi_out(ui, unibi_enter_standout_mode);
}
if (reverse) {
unibi_out(ui, unibi_enter_reverse_mode);
}
}
if (italic) {
unibi_out(ui, unibi_enter_italics_mode);
}
if (strikethrough && data->unibi_ext.enter_strikethrough_mode != -1) {
unibi_out_ext(ui, data->unibi_ext.enter_strikethrough_mode);
}
if (undercurl && data->unibi_ext.set_underline_style != -1) {
UNIBI_SET_NUM_VAR(data->params[0], 3);
unibi_out_ext(ui, data->unibi_ext.set_underline_style);
}
if ((undercurl || underline) && data->unibi_ext.set_underline_color != -1) {
int color = attrs.rgb_sp_color;
if (color != -1) {
UNIBI_SET_NUM_VAR(data->params[0], (color >> 16) & 0xff); // red
UNIBI_SET_NUM_VAR(data->params[1], (color >> 8) & 0xff); // green
UNIBI_SET_NUM_VAR(data->params[2], color & 0xff); // blue
unibi_out_ext(ui, data->unibi_ext.set_underline_color);
}
}
int fg, bg;
if (ui->rgb && !(attr & HL_FG_INDEXED)) {
fg = ((attrs.rgb_fg_color != -1)
? attrs.rgb_fg_color : data->clear_attrs.rgb_fg_color);
if (fg != -1) {
UNIBI_SET_NUM_VAR(data->params[0], (fg >> 16) & 0xff); // red
UNIBI_SET_NUM_VAR(data->params[1], (fg >> 8) & 0xff); // green
UNIBI_SET_NUM_VAR(data->params[2], fg & 0xff); // blue
unibi_out_ext(ui, data->unibi_ext.set_rgb_foreground);
}
} else {
fg = (attrs.cterm_fg_color
? attrs.cterm_fg_color - 1 : (data->clear_attrs.cterm_fg_color - 1));
if (fg != -1) {
UNIBI_SET_NUM_VAR(data->params[0], fg);
unibi_out(ui, unibi_set_a_foreground);
}
}
if (ui->rgb && !(attr & HL_BG_INDEXED)) {
bg = ((attrs.rgb_bg_color != -1)
? attrs.rgb_bg_color : data->clear_attrs.rgb_bg_color);
if (bg != -1) {
UNIBI_SET_NUM_VAR(data->params[0], (bg >> 16) & 0xff); // red
UNIBI_SET_NUM_VAR(data->params[1], (bg >> 8) & 0xff); // green
UNIBI_SET_NUM_VAR(data->params[2], bg & 0xff); // blue
unibi_out_ext(ui, data->unibi_ext.set_rgb_background);
}
} else {
bg = (attrs.cterm_bg_color
? attrs.cterm_bg_color - 1 : (data->clear_attrs.cterm_bg_color - 1));
if (bg != -1) {
UNIBI_SET_NUM_VAR(data->params[0], bg);
unibi_out(ui, unibi_set_a_background);
}
}
data->default_attr = fg == -1 && bg == -1
&& !bold && !italic && !underline && !undercurl && !reverse && !standout
&& !strikethrough;
// Non-BCE terminals can't clear with non-default background color. Some BCE
// terminals don't support attributes either, so don't rely on it. But assume
// italic and bold has no effect if there is no text.
data->can_clear_attr = !reverse && !standout && !underline && !undercurl
&& !strikethrough && (data->bce || bg == -1);
}
static void final_column_wrap(UI *ui)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
if (grid->row != -1 && grid->col == ui->width) {
grid->col = 0;
if (grid->row < MIN(ui->height, grid->height - 1)) {
grid->row++;
}
}
}
/// It is undocumented, but in the majority of terminals and terminal emulators
/// printing at the right margin does not cause an automatic wrap until the
/// next character is printed, holding the cursor in place until then.
static void print_cell(UI *ui, UCell *ptr)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
if (!data->immediate_wrap_after_last_column) {
// Printing the next character finally advances the cursor.
final_column_wrap(ui);
}
update_attrs(ui, ptr->attr);
out(ui, ptr->data, strlen(ptr->data));
grid->col++;
if (data->immediate_wrap_after_last_column) {
// Printing at the right margin immediately advances the cursor.
final_column_wrap(ui);
}
}
static bool cheap_to_print(UI *ui, int row, int col, int next)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
UCell *cell = grid->cells[row] + col;
while (next) {
next--;
if (attrs_differ(ui, cell->attr,
data->print_attr_id, ui->rgb)) {
if (data->default_attr) {
return false;
}
}
if (strlen(cell->data) > 1) {
return false;
}
cell++;
}
return true;
}
/// This optimizes several cases where it is cheaper to do something other
/// than send a full cursor positioning control sequence. However, there are
/// some further optimizations that may seem obvious but that will not work.
///
/// We cannot use VT (ASCII 0/11) for moving the cursor up, because VT means
/// move the cursor down on a DEC terminal. Similarly, on a DEC terminal FF
/// (ASCII 0/12) means the same thing and does not mean home. VT, CVT, and
/// TAB also stop at software-defined tabulation stops, not at a fixed set
/// of row/column positions.
static void cursor_goto(UI *ui, int row, int col)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
if (row == grid->row && col == grid->col) {
return;
}
if (0 == row && 0 == col) {
unibi_out(ui, unibi_cursor_home);
ugrid_goto(grid, row, col);
return;
}
if (grid->row == -1) {
goto safe_move;
}
if (0 == col ? col != grid->col :
row != grid->row ? false :
1 == col ? 2 < grid->col && cheap_to_print(ui, grid->row, 0, col) :
2 == col ? 5 < grid->col && cheap_to_print(ui, grid->row, 0, col) :
false) {
// Motion to left margin from anywhere else, or CR + printing chars is
// even less expensive than using BSes or CUB.
unibi_out(ui, unibi_carriage_return);
ugrid_goto(grid, grid->row, 0);
}
if (row == grid->row) {
if (col < grid->col
// Deferred right margin wrap terminals have inconsistent ideas about
// where the cursor actually is during a deferred wrap. Relative
// motion calculations have OBOEs that cannot be compensated for,
// because two terminals that claim to be the same will implement
// different cursor positioning rules.
&& (data->immediate_wrap_after_last_column || grid->col < ui->width)) {
int n = grid->col - col;
if (n <= 4) { // This might be just BS, so it is considered really cheap.
while (n--) {
unibi_out(ui, unibi_cursor_left);
}
} else {
UNIBI_SET_NUM_VAR(data->params[0], n);
unibi_out(ui, unibi_parm_left_cursor);
}
ugrid_goto(grid, row, col);
return;
} else if (col > grid->col) {
int n = col - grid->col;
if (n <= 2) {
while (n--) {
unibi_out(ui, unibi_cursor_right);
}
} else {
UNIBI_SET_NUM_VAR(data->params[0], n);
unibi_out(ui, unibi_parm_right_cursor);
}
ugrid_goto(grid, row, col);
return;
}
}
if (col == grid->col) {
if (row > grid->row) {
int n = row - grid->row;
if (n <= 4) { // This might be just LF, so it is considered really cheap.
while (n--) {
unibi_out(ui, unibi_cursor_down);
}
} else {
UNIBI_SET_NUM_VAR(data->params[0], n);
unibi_out(ui, unibi_parm_down_cursor);
}
ugrid_goto(grid, row, col);
return;
} else if (row < grid->row) {
int n = grid->row - row;
if (n <= 2) {
while (n--) {
unibi_out(ui, unibi_cursor_up);
}
} else {
UNIBI_SET_NUM_VAR(data->params[0], n);
unibi_out(ui, unibi_parm_up_cursor);
}
ugrid_goto(grid, row, col);
return;
}
}
safe_move:
unibi_goto(ui, row, col);
ugrid_goto(grid, row, col);
}
static void clear_region(UI *ui, int top, int bot, int left, int right,
int attr_id)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
update_attrs(ui, attr_id);
// Background is set to the default color and the right edge matches the
// screen end, try to use terminal codes for clearing the requested area.
if (data->can_clear_attr
&& left == 0 && right == ui->width && bot == ui->height) {
if (top == 0) {
unibi_out(ui, unibi_clear_screen);
ugrid_goto(&data->grid, top, left);
} else {
cursor_goto(ui, top, 0);
unibi_out(ui, unibi_clr_eos);
}
} else {
int width = right-left;
// iterate through each line and clear
for (int row = top; row < bot; row++) {
cursor_goto(ui, row, left);
if (data->can_clear_attr && right == ui->width) {
unibi_out(ui, unibi_clr_eol);
} else if (data->can_erase_chars && data->can_clear_attr && width >= 5) {
UNIBI_SET_NUM_VAR(data->params[0], width);
unibi_out(ui, unibi_erase_chars);
} else {
out(ui, data->space_buf, (size_t)width);
grid->col += width;
if (data->immediate_wrap_after_last_column) {
// Printing at the right margin immediately advances the cursor.
final_column_wrap(ui);
}
}
}
}
}
static void set_scroll_region(UI *ui, int top, int bot, int left, int right)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
UNIBI_SET_NUM_VAR(data->params[0], top);
UNIBI_SET_NUM_VAR(data->params[1], bot);
unibi_out(ui, unibi_change_scroll_region);
if (left != 0 || right != ui->width - 1) {
unibi_out_ext(ui, data->unibi_ext.enable_lr_margin);
if (data->can_set_lr_margin) {
UNIBI_SET_NUM_VAR(data->params[0], left);
UNIBI_SET_NUM_VAR(data->params[1], right);
unibi_out(ui, unibi_set_lr_margin);
} else {
UNIBI_SET_NUM_VAR(data->params[0], left);
unibi_out(ui, unibi_set_left_margin_parm);
UNIBI_SET_NUM_VAR(data->params[0], right);
unibi_out(ui, unibi_set_right_margin_parm);
}
}
grid->row = -1;
}
static void reset_scroll_region(UI *ui, bool fullwidth)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
if (0 <= data->unibi_ext.reset_scroll_region) {
unibi_out_ext(ui, data->unibi_ext.reset_scroll_region);
} else {
UNIBI_SET_NUM_VAR(data->params[0], 0);
UNIBI_SET_NUM_VAR(data->params[1], ui->height - 1);
unibi_out(ui, unibi_change_scroll_region);
}
if (!fullwidth) {
if (data->can_set_lr_margin) {
UNIBI_SET_NUM_VAR(data->params[0], 0);
UNIBI_SET_NUM_VAR(data->params[1], ui->width - 1);
unibi_out(ui, unibi_set_lr_margin);
} else {
UNIBI_SET_NUM_VAR(data->params[0], 0);
unibi_out(ui, unibi_set_left_margin_parm);
UNIBI_SET_NUM_VAR(data->params[0], ui->width - 1);
unibi_out(ui, unibi_set_right_margin_parm);
}
unibi_out_ext(ui, data->unibi_ext.disable_lr_margin);
}
grid->row = -1;
}
static void tui_grid_resize(UI *ui, Integer g, Integer width, Integer height)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
ugrid_resize(grid, (int)width, (int)height);
xfree(data->space_buf);
data->space_buf = xmalloc((size_t)width * sizeof(*data->space_buf));
memset(data->space_buf, ' ', (size_t)width);
// resize might not always be followed by a clear before flush
// so clip the invalid region
for (size_t i = 0; i < kv_size(data->invalid_regions); i++) {
Rect *r = &kv_A(data->invalid_regions, i);
r->bot = MIN(r->bot, grid->height);
r->right = MIN(r->right, grid->width);
}
if (!got_winch && (!data->is_starting || did_user_set_dimensions)) {
// Resize the _host_ terminal.
UNIBI_SET_NUM_VAR(data->params[0], (int)height);
UNIBI_SET_NUM_VAR(data->params[1], (int)width);
unibi_out_ext(ui, data->unibi_ext.resize_screen);
// DECSLPP does not reset the scroll region.
if (data->scroll_region_is_full_screen) {
reset_scroll_region(ui, ui->width == grid->width);
}
} else { // Already handled the SIGWINCH signal; avoid double-resize.
got_winch = false;
grid->row = -1;
}
}
static void tui_grid_clear(UI *ui, Integer g)
{
TUIData *data = ui->data;
UGrid *grid = &data->grid;
ugrid_clear(grid);
kv_size(data->invalid_regions) = 0;
clear_region(ui, 0, grid->height, 0, grid->width, 0);
}
static void tui_grid_cursor_goto(UI *ui, Integer grid, Integer row, Integer col)
{
TUIData *data = ui->data;
// cursor position is validated in tui_flush
data->row = (int)row;
data->col = (int)col;
}
CursorShape tui_cursor_decode_shape(const char *shape_str)
{
CursorShape shape;
if (strequal(shape_str, "block")) {
shape = SHAPE_BLOCK;
} else if (strequal(shape_str, "vertical")) {
shape = SHAPE_VER;
} else if (strequal(shape_str, "horizontal")) {
shape = SHAPE_HOR;
} else {
WLOG("Unknown shape value '%s'", shape_str);
shape = SHAPE_BLOCK;
}
return shape;
}
static cursorentry_T decode_cursor_entry(Dictionary args)
{
cursorentry_T r = shape_table[0];
for (size_t i = 0; i < args.size; i++) {
char *key = args.items[i].key.data;
Object value = args.items[i].value;
if (strequal(key, "cursor_shape")) {
r.shape = tui_cursor_decode_shape(args.items[i].value.data.string.data);
} else if (strequal(key, "blinkon")) {
r.blinkon = (int)value.data.integer;
} else if (strequal(key, "blinkoff")) {
r.blinkoff = (int)value.data.integer;
} else if (strequal(key, "attr_id")) {
r.id = (int)value.data.integer;
}
}
return r;
}
static void tui_mode_info_set(UI *ui, bool guicursor_enabled, Array args)
{
cursor_style_enabled = guicursor_enabled;
if (!guicursor_enabled) {
return; // Do not send cursor style control codes.
}
TUIData *data = ui->data;