robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3b00ddb601
master
1#include <assert.h> 2#include <stdio.h> 3#include <stdlib.h> 4#include <string.h> 5 6#include "klib/kvec.h" 7#include "nvim/api/private/defs.h" 8#include "nvim/api/private/helpers.h" 9#include "nvim/event/loop.h" 10#include "nvim/event/rstream.h" 11#include "nvim/macros_defs.h" 12#include "nvim/main.h" 13#include "nvim/map_defs.h" 14#include "nvim/memory.h" 15#include "nvim/msgpack_rpc/channel.h" 16#include "nvim/option_vars.h" 17#include "nvim/os/os.h" 18#include "nvim/os/os_defs.h" 19#include "nvim/strings.h" 20#include "nvim/tui/input.h" 21#include "nvim/tui/input_defs.h" 22#include "nvim/tui/termkey/driver-csi.h" 23#include "nvim/tui/termkey/termkey.h" 24#include "nvim/tui/termkey/termkey_defs.h" 25#include "nvim/tui/tui.h" 26#include "nvim/ui_client.h" 27 28#ifdef MSWIN 29# include "nvim/os/os_win_console.h" 30#endif 31 32#define READ_STREAM_SIZE 0xfff 33 34/// Size of libtermkey's internal input buffer. The buffer may grow larger than 35/// this when processing very long escape sequences, but will shrink back to 36/// this size afterward 37#define INPUT_BUFFER_SIZE 256 38 39static const struct kitty_key_map_entry { 40int key ; 41const char * name ; 42}kitty_key_map_entry []= { 43 {KITTY_KEY_ESCAPE ,"Esc" }, 44 {KITTY_KEY_ENTER ,"CR" }, 45 {KITTY_KEY_TAB ,"Tab" }, 46 {KITTY_KEY_BACKSPACE ,"BS" }, 47 {KITTY_KEY_INSERT ,"Insert" }, 48 {KITTY_KEY_DELETE ,"Del" }, 49 {KITTY_KEY_LEFT ,"Left" }, 50 {KITTY_KEY_RIGHT ,"Right" }, 51 {KITTY_KEY_UP ,"Up" }, 52 {KITTY_KEY_DOWN ,"Down" }, 53 {KITTY_KEY_PAGE_UP ,"PageUp" }, 54 {KITTY_KEY_PAGE_DOWN ,"PageDown" }, 55 {KITTY_KEY_HOME ,"Home" }, 56 {KITTY_KEY_END ,"End" }, 57 {KITTY_KEY_F1 ,"F1" }, 58 {KITTY_KEY_F2 ,"F2" }, 59 {KITTY_KEY_F3 ,"F3" }, 60 {KITTY_KEY_F4 ,"F4" }, 61 {KITTY_KEY_F5 ,"F5" }, 62 {KITTY_KEY_F6 ,"F6" }, 63 {KITTY_KEY_F7 ,"F7" }, 64 {KITTY_KEY_F8 ,"F8" }, 65 {KITTY_KEY_F9 ,"F9" }, 66 {KITTY_KEY_F10 ,"F10" }, 67 {KITTY_KEY_F11 ,"F11" }, 68 {KITTY_KEY_F12 ,"F12" }, 69 {KITTY_KEY_F13 ,"F13" }, 70 {KITTY_KEY_F14 ,"F14" }, 71 {KITTY_KEY_F15 ,"F15" }, 72 {KITTY_KEY_F16 ,"F16" }, 73 {KITTY_KEY_F17 ,"F17" }, 74 {KITTY_KEY_F18 ,"F18" }, 75 {KITTY_KEY_F19 ,"F19" }, 76 {KITTY_KEY_F20 ,"F20" }, 77 {KITTY_KEY_F21 ,"F21" }, 78 {KITTY_KEY_F22 ,"F22" }, 79 {KITTY_KEY_F23 ,"F23" }, 80 {KITTY_KEY_F24 ,"F24" }, 81 {KITTY_KEY_F25 ,"F25" }, 82 {KITTY_KEY_F26 ,"F26" }, 83 {KITTY_KEY_F27 ,"F27" }, 84 {KITTY_KEY_F28 ,"F28" }, 85 {KITTY_KEY_F29 ,"F29" }, 86 {KITTY_KEY_F30 ,"F30" }, 87 {KITTY_KEY_F31 ,"F31" }, 88 {KITTY_KEY_F32 ,"F32" }, 89 {KITTY_KEY_F33 ,"F33" }, 90 {KITTY_KEY_F34 ,"F34" }, 91 {KITTY_KEY_F35 ,"F35" }, 92 {KITTY_KEY_KP_0 ,"k0" }, 93 {KITTY_KEY_KP_1 ,"k1" }, 94 {KITTY_KEY_KP_2 ,"k2" }, 95 {KITTY_KEY_KP_3 ,"k3" }, 96 {KITTY_KEY_KP_4 ,"k4" }, 97 {KITTY_KEY_KP_5 ,"k5" }, 98 {KITTY_KEY_KP_6 ,"k6" }, 99 {KITTY_KEY_KP_7 ,"k7" }, 100 {KITTY_KEY_KP_8 ,"k8" }, 101 {KITTY_KEY_KP_9 ,"k9" }, 102 {KITTY_KEY_KP_DECIMAL ,"kPoint" }, 103 {KITTY_KEY_KP_DIVIDE ,"kDivide" }, 104 {KITTY_KEY_KP_MULTIPLY ,"kMultiply" }, 105 {KITTY_KEY_KP_SUBTRACT ,"kMinus" }, 106 {KITTY_KEY_KP_ADD ,"kPlus" }, 107 {KITTY_KEY_KP_ENTER ,"kEnter" }, 108 {KITTY_KEY_KP_EQUAL ,"kEqual" }, 109 {KITTY_KEY_KP_LEFT ,"kLeft" }, 110 {KITTY_KEY_KP_RIGHT ,"kRight" }, 111 {KITTY_KEY_KP_UP ,"kUp" }, 112 {KITTY_KEY_KP_DOWN ,"kDown" }, 113 {KITTY_KEY_KP_PAGE_UP ,"kPageUp" }, 114 {KITTY_KEY_KP_PAGE_DOWN ,"kPageDown" }, 115 {KITTY_KEY_KP_HOME ,"kHome" }, 116 {KITTY_KEY_KP_END ,"kEnd" }, 117 {KITTY_KEY_KP_INSERT ,"kInsert" }, 118 {KITTY_KEY_KP_DELETE ,"kDel" }, 119 {KITTY_KEY_KP_BEGIN ,"kOrigin" }, 120}; 121 122static PMap (int )kitty_key_map = MAP_INIT ; 123 124#include "tui/input.c.generated.h" 125 126void tinput_init (TermInput * input ,Loop * loop ,TerminfoEntry * ti ) 127{ 128assert (input -> loop == NULL ); 129input -> loop = loop ; 130input -> paste = 0 ; 131input -> in_fd = STDIN_FILENO ; 132input -> ttimeout = (bool )p_ttimeout ; 133input -> ttimeoutlen = p_ttm ; 134 135// setup input handle 136rstream_init_fd (loop ,& input -> read_stream ,input -> in_fd ); 137 138for (size_t i = 0 ;i < ARRAY_SIZE (kitty_key_map_entry );i ++ ) { 139pmap_put (int )(& kitty_key_map ,kitty_key_map_entry [i ].key , (ptr_t )kitty_key_map_entry [i ].name ); 140 } 141 142input -> tk = termkey_new_abstract (ti , (TERMKEY_FLAG_UTF8 |TERMKEY_FLAG_NOSTART 143 |TERMKEY_FLAG_KEEPC0 )); 144termkey_set_buffer_size (input -> tk ,INPUT_BUFFER_SIZE ); 145termkey_hook_terminfo_getstr (input -> tk ,input -> tk_ti_hook_fn ,input ); 146termkey_start (input -> tk ); 147 148int curflags = termkey_get_canonflags (input -> tk ); 149termkey_set_canonflags (input -> tk ,curflags |TERMKEY_CANON_DELBS ); 150 151// initialize a timer handle for handling ESC with libtermkey 152uv_timer_init (& loop -> uv ,& input -> timer_handle ); 153input -> timer_handle .data = input ; 154 155uv_timer_init (& loop -> uv ,& input -> bg_query_timer ); 156input -> bg_query_timer .data = input ; 157} 158 159void tinput_destroy (TermInput * input ) 160{ 161map_destroy (int ,& kitty_key_map ); 162uv_close ((uv_handle_t * )& input -> timer_handle ,NULL ); 163uv_close ((uv_handle_t * )& input -> bg_query_timer ,NULL ); 164rstream_may_close (& input -> read_stream ); 165termkey_destroy (input -> tk ); 166input -> loop = NULL ; 167} 168 169void tinput_start (TermInput * input ) 170{ 171rstream_start (& input -> read_stream ,tinput_read_cb ,input ); 172} 173 174void tinput_stop (TermInput * input ) 175{ 176rstream_stop (& input -> read_stream ); 177uv_timer_stop (& input -> timer_handle ); 178uv_timer_stop (& input -> bg_query_timer ); 179} 180 181static void tinput_done_event (void ** argv ) 182FUNC_ATTR_NORETURN 183{ 184os_exit (1 ); 185} 186 187/// Send all pending input in key buffer to Nvim server. 188static void tinput_flush (TermInput * input ) 189{ 190String keys = { .data = input -> key_buffer , .size = input -> key_buffer_len }; 191if (input -> paste ) {// produce exactly one paste event 192MAXSIZE_TEMP_ARRAY (args ,3 ); 193ADD_C (args ,STRING_OBJ (keys ));// 'data' 194ADD_C (args ,BOOLEAN_OBJ (true));// 'crlf' 195ADD_C (args ,INTEGER_OBJ (input -> paste ));// 'phase' 196rpc_send_event (ui_client_channel_id ,"nvim_paste" ,args ); 197if (input -> paste == 1 ) { 198// Paste phase: "continue" 199input -> paste = 2 ; 200 } 201 }else {// enqueue input 202if (input -> key_buffer_len > 0 ) { 203MAXSIZE_TEMP_ARRAY (args ,1 ); 204ADD_C (args ,STRING_OBJ (keys )); 205// NOTE: This is non-blocking and won't check partially processed input, 206// but should be fine as all big sends are handled with nvim_paste, not nvim_input 207rpc_send_event (ui_client_channel_id ,"nvim_input" ,args ); 208 } 209 } 210input -> key_buffer_len = 0 ; 211} 212 213static void tinput_enqueue (TermInput * input ,const char * buf ,size_t size ) 214{ 215if (input -> key_buffer_len > KEY_BUFFER_SIZE - size ) { 216// don't ever let the buffer get too full or we risk putting incomplete keys into it 217tinput_flush (input ); 218 } 219size_t to_copy = MIN (size ,KEY_BUFFER_SIZE - input -> key_buffer_len ); 220memcpy (input -> key_buffer + input -> key_buffer_len ,buf ,to_copy ); 221input -> key_buffer_len += to_copy ; 222} 223 224/// Handle TERMKEY_KEYMOD_* modifiers, i.e. Shift, Alt and Ctrl. 225/// 226/// @return The number of bytes written into "buf", excluding the final NUL. 227static size_t handle_termkey_modifiers (TermKeyKey * key ,char * buf ,size_t buflen ) 228FUNC_ATTR_WARN_UNUSED_RESULT 229{ 230size_t len = 0 ; 231if (key -> modifiers & TERMKEY_KEYMOD_SHIFT ) {// Shift 232len += (size_t )snprintf (buf + len ,buflen - len ,"S-" ); 233 } 234if (key -> modifiers & TERMKEY_KEYMOD_ALT ) {// Alt 235len += (size_t )snprintf (buf + len ,buflen - len ,"A-" ); 236 } 237if (key -> modifiers & TERMKEY_KEYMOD_CTRL ) {// Ctrl 238len += (size_t )snprintf (buf + len ,buflen - len ,"C-" ); 239 } 240assert (len < buflen ); 241return len ; 242} 243 244enum { 245KEYMOD_SUPER = 1 <<3 , 246KEYMOD_META = 1 <<5 , 247#ifdef _MSC_VER 248# pragma warning(push) 249# pragma warning(disable : 5287) 250#endif 251KEYMOD_RECOGNIZED = ( TERMKEY_KEYMOD_SHIFT | TERMKEY_KEYMOD_ALT | TERMKEY_KEYMOD_CTRL 252| KEYMOD_SUPER | KEYMOD_META ), 253#ifdef _MSC_VER 254# pragma warning(pop) 255#endif 256}; 257 258/// Handle modifiers not handled by libtermkey. 259/// Currently only Super ("D-") and Meta ("T-") are supported in Nvim. 260/// 261/// @return The number of bytes written into "buf", excluding the final NUL. 262static size_t handle_more_modifiers ( TermKeyKey * key , char * buf , size_t buflen ) 263FUNC_ATTR_WARN_UNUSED_RESULT 264{ 265size_t len = 0 ; 266if ( key -> modifiers & KEYMOD_SUPER ) { 267len += ( size_t ) snprintf ( buf + len , buflen - len , "D-" ); 268} 269if ( key -> modifiers & KEYMOD_META ) { 270len += ( size_t ) snprintf ( buf + len , buflen - len , "T-" ); 271} 272assert ( len < buflen ); 273return len ; 274} 275 276static void handle_kitty_key_protocol ( TermInput * input , TermKeyKey * key ) 277{ 278const char * name = pmap_get ( int )( & kitty_key_map , key -> code . codepoint ); 279if ( name ) { 280char buf [ 64 ]; 281size_t len = 0 ; 282buf [ len ++ ] = '<' ; 283len += handle_termkey_modifiers ( key , buf + len , sizeof( buf ) - len ); 284len += handle_more_modifiers ( key , buf + len , sizeof( buf ) - len ); 285len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "%s>" , name ); 286assert ( len < sizeof( buf )); 287tinput_enqueue ( input , buf , len ); 288} 289} 290 291static void forward_simple_utf8 ( TermInput * input , TermKeyKey * key ) 292{ 293size_t len = 0 ; 294char buf [ 64 ]; 295char * ptr = key -> utf8 ; 296 297if ( key -> code . codepoint >= 0xE000 && key -> code . codepoint <= 0xF8FF 298&& map_has ( int , & kitty_key_map , ( int ) key -> code . codepoint )) { 299handle_kitty_key_protocol ( input , key ); 300return; 301} 302while ( * ptr ) { 303if ( * ptr == '<' ) { 304len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "<lt>" ); 305} else { 306buf [ len ++ ] = * ptr ; 307} 308assert ( len < sizeof( buf )); 309ptr ++ ; 310} 311 312tinput_enqueue ( input , buf , len ); 313} 314 315static void forward_modified_utf8 ( TermInput * input , TermKeyKey * key ) 316{ 317size_t len ; 318char buf [ 64 ]; 319 320if ( key -> type == TERMKEY_TYPE_KEYSYM 321&& key -> code . sym == TERMKEY_SYM_SUSPEND ) { 322len = ( size_t ) snprintf ( buf , sizeof( buf ), "<C-Z>" ); 323} else if ( key -> type != TERMKEY_TYPE_UNICODE ) { 324len = termkey_strfkey ( input -> tk , buf , sizeof( buf ), key , TERMKEY_FORMAT_VIM ); 325} else { 326assert ( key -> modifiers ); 327if ( key -> code . codepoint >= 0xE000 && key -> code . codepoint <= 0xF8FF 328&& map_has ( int , & kitty_key_map , ( int ) key -> code . codepoint )) { 329handle_kitty_key_protocol ( input , key ); 330return; 331} 332// Termkey doesn't include the S- modifier for ASCII characters (e.g., 333// ctrl-shift-l is <C-L> instead of <C-S-L>. Vim, on the other hand, 334// treats <C-L> and <C-l> the same, requiring the S- modifier. 335len = termkey_strfkey ( input -> tk , buf , sizeof( buf ), key , TERMKEY_FORMAT_VIM ); 336if (( key -> modifiers & TERMKEY_KEYMOD_CTRL ) 337&& !( key -> modifiers & TERMKEY_KEYMOD_SHIFT ) 338&& ASCII_ISUPPER ( key -> code . codepoint )) { 339assert ( len + 2 < sizeof( buf )); 340// Make room for the S- 341memmove ( buf + 3 , buf + 1 , len - 1 ); 342buf [ 1 ] = 'S' ; 343buf [ 2 ] = '-' ; 344len += 2 ; 345} 346} 347 348char more_buf [ 25 ]; 349size_t more_len = handle_more_modifiers ( key , more_buf , sizeof( more_buf )); 350if ( more_len > 0 ) { 351assert ( len + more_len < sizeof( buf )); 352memmove ( buf + 1 + more_len , buf + 1 , len - 1 ); 353memcpy ( buf + 1 , more_buf , more_len ); 354len += more_len ; 355} 356 357assert ( len < sizeof( buf )); 358tinput_enqueue ( input , buf , len ); 359} 360 361static void forward_mouse_event ( TermInput * input , TermKeyKey * key ) 362{ 363char buf [ 64 ]; 364size_t len = 0 ; 365int button , row , col ; 366static int last_pressed_button = 0 ; 367TermKeyMouseEvent ev ; 368termkey_interpret_mouse ( input -> tk , key , & ev , & button , & row , & col ); 369 370if (( ev == TERMKEY_MOUSE_RELEASE || ev == TERMKEY_MOUSE_DRAG ) 371&& button == 0 ) { 372// Some terminals (like urxvt) don't report which button was released. 373// libtermkey reports button 0 in this case. 374// For drag and release, we can reasonably infer the button to be the last 375// pressed one. 376button = last_pressed_button ; 377} 378 379if (( button == 0 && ev != TERMKEY_MOUSE_RELEASE ) 380|| ( ev != TERMKEY_MOUSE_PRESS && ev != TERMKEY_MOUSE_DRAG && ev != TERMKEY_MOUSE_RELEASE )) { 381return; 382} 383 384row -- ; col -- ; // Termkey uses 1-based coordinates 385buf [ len ++ ] = '<' ; 386 387len += handle_termkey_modifiers ( key , buf + len , sizeof( buf ) - len ); 388// Doesn't actually work because there are only 3 bits (0x1c) for modifiers. 389// len += handle_more_modifiers(key, buf + len, sizeof(buf) - len); 390 391if ( button == 1 ) { 392len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "Left" ); 393} else if ( button == 2 ) { 394len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "Middle" ); 395} else if ( button == 3 ) { 396len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "Right" ); 397} else if ( button == 8 ) { 398len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "X1" ); 399} else if ( button == 9 ) { 400len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "X2" ); 401} 402 403switch ( ev ) { 404case TERMKEY_MOUSE_PRESS : 405if ( button == 4 ) { 406len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "ScrollWheelUp" ); 407} else if ( button == 5 ) { 408len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "ScrollWheelDown" ); 409} else if ( button == 6 ) { 410len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "ScrollWheelLeft" ); 411} else if ( button == 7 ) { 412len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "ScrollWheelRight" ); 413} else { 414len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "Mouse" ); 415last_pressed_button = button ; 416} 417break; 418case TERMKEY_MOUSE_DRAG : 419len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "Drag" ); 420break; 421case TERMKEY_MOUSE_RELEASE : 422len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , button ? "Release" : "MouseMove" ); 423last_pressed_button = 0 ; 424break; 425case TERMKEY_MOUSE_UNKNOWN : 426abort (); 427} 428 429len += ( size_t ) snprintf ( buf + len , sizeof( buf ) - len , "><%d,%d>" , col , row ); 430assert ( len < sizeof( buf )); 431tinput_enqueue ( input , buf , len ); 432} 433 434static TermKeyResult tk_getkey ( TermKey * tk , TermKeyKey * key , bool force ) 435{ 436return force ? termkey_getkey_force ( tk , key ) : termkey_getkey ( tk , key ); 437} 438 439static void tk_getkeys ( TermInput * input , bool force ) 440{ 441TermKeyKey key ; 442TermKeyResult result ; 443 444while (( result = tk_getkey ( input -> tk , & key , force )) == TERMKEY_RES_KEY ) { 445// Only press and repeat events are handled for now 446switch ( key . event ) { 447case TERMKEY_EVENT_PRESS : 448case TERMKEY_EVENT_REPEAT : 449break; 450default: 451continue; 452} 453 454if ( key . type == TERMKEY_TYPE_UNICODE && !( key . modifiers & KEYMOD_RECOGNIZED )) { 455forward_simple_utf8 ( input , & key ); 456} else if ( key . type == TERMKEY_TYPE_UNICODE 457|| key . type == TERMKEY_TYPE_FUNCTION 458|| key . type == TERMKEY_TYPE_KEYSYM ) { 459forward_modified_utf8 ( input , & key ); 460} else if ( key . type == TERMKEY_TYPE_MOUSE ) { 461forward_mouse_event ( input , & key ); 462} else if ( key . type == TERMKEY_TYPE_MODEREPORT ) { 463handle_modereport ( input , & key ); 464} else if ( key . type == TERMKEY_TYPE_UNKNOWN_CSI ) { 465handle_unknown_csi ( input , & key ); 466} else if ( key . type == TERMKEY_TYPE_OSC || key . type == TERMKEY_TYPE_DCS 467|| key . type == TERMKEY_TYPE_APC ) { 468handle_term_response ( input , & key ); 469} 470} 471 472if ( result != TERMKEY_RES_AGAIN ) { 473return; 474} 475// else: Partial keypress event was found in the buffer, but it does not 476// yet contain all the bytes required. `key` structure indicates what 477// termkey_getkey_force() would return. 478 479if ( input -> ttimeout && input -> ttimeoutlen >= 0 ) { 480// Stop the current timer if already running 481uv_timer_stop ( & input -> timer_handle ); 482uv_timer_start ( & input -> timer_handle , tinput_timer_cb , ( uint64_t ) input -> ttimeoutlen , 0 ); 483} else { 484tk_getkeys ( input , true); 485} 486} 487 488static void tinput_timer_cb ( uv_timer_t * handle ) 489{ 490TermInput * input = handle -> data ; 491// If the raw buffer is not empty, process the raw buffer first because it is 492// processing an incomplete bracketed paste sequence. 493size_t size = rstream_available ( & input -> read_stream ); 494if ( size ) { 495size_t consumed = handle_raw_buffer ( input , true, input -> read_stream . read_pos , size ); 496rstream_consume ( & input -> read_stream , consumed ); 497} 498tk_getkeys ( input , true); 499tinput_flush ( input ); 500} 501 502static void bg_query_timer_cb ( uv_timer_t * handle ) 503FUNC_ATTR_NONNULL_ALL 504{ 505TermInput * input = handle -> data ; 506tui_query_bg_color ( input -> tui_data ); 507} 508 509/// Handle focus events. 510/// 511/// If the upcoming sequence of bytes in the input stream matches the termcode 512/// for "focus gained" or "focus lost", consume that sequence and send an event 513/// to Nvim server. 514/// 515/// @param input the input stream 516/// @return true iff handle_focus_event consumed some input 517static size_t handle_focus_event ( TermInput * input , const char * ptr , size_t size ) 518{ 519if ( size >= 3 520&& (! memcmp ( ptr , "\x1b[I" , 3 ) 521|| ! memcmp ( ptr , "\x1b[O" , 3 ))) { 522bool focus_gained = ptr [ 2 ] == 'I' ; 523 524MAXSIZE_TEMP_ARRAY ( args , 1 ); 525ADD_C ( args , BOOLEAN_OBJ ( focus_gained )); 526rpc_send_event ( ui_client_channel_id , "nvim_ui_set_focus" , args ); 527return 3 ; // Advance past the sequence 528} 529return 0 ; 530} 531 532#define START_PASTE "\x1b[200~" 533#define END_PASTE "\x1b[201~" 534static size_t handle_bracketed_paste ( TermInput * input , const char * ptr , size_t size , 535bool * incomplete ) 536{ 537if ( size >= 6 538&& (! memcmp ( ptr , START_PASTE , 6 ) 539|| ! memcmp ( ptr , END_PASTE , 6 ))) { 540bool enable = ptr [ 4 ] == '0' ; 541if ( input -> paste && enable ) { 542return 0 ; // Pasting "start paste" code literally. 543} 544 545// Advance past the sequence 546if (!! input -> paste == enable ) { 547return 6 ; // Spurious "disable paste" code. 548} 549 550if ( enable ) { 551// Flush before starting paste. 552tinput_flush ( input ); 553// Paste phase: "first-chunk". 554input -> paste = 1 ; 555} else if ( input -> paste ) { 556// Paste phase: "last-chunk". 557input -> paste = input -> paste == 2 ? 3 : -1 ; 558tinput_flush ( input ); 559// Paste phase: "disabled". 560input -> paste = 0 ; 561} 562return 6 ; 563} else if ( size < 6 564&& (! memcmp ( ptr , START_PASTE , size ) 565|| ! memcmp ( ptr , END_PASTE , size ))) { 566// Wait for further input, as the sequence may be split. 567* incomplete = true; 568return 0 ; 569} 570return 0 ; 571} 572 573/// Handle an OSC, DCS, or APC response sequence from the terminal. 574static void handle_term_response ( TermInput * input , const TermKeyKey * key ) 575FUNC_ATTR_NONNULL_ALL 576{ 577const char * str = NULL ; 578if ( termkey_interpret_string ( input -> tk , key , & str ) == TERMKEY_RES_KEY ) { 579assert ( str != NULL ); 580 581// Handle DECRQSS SGR response for the query from tui_query_extended_underline(). 582// Some terminals include "0" in the attribute list unconditionally; others don't. 583if ( key -> type == TERMKEY_TYPE_DCS 584&& ( strnequal ( str , S_LEN ( "1$r4:3m" )) || strnequal ( str , S_LEN ( "1$r0;4:3m" )))) { 585tui_enable_extended_underline ( input -> tui_data ); 586} 587 588// Send an event to nvim core. This will update the v:termresponse variable 589// and fire the TermResponse event 590MAXSIZE_TEMP_ARRAY ( args , 2 ); 591ADD_C ( args , STATIC_CSTR_AS_OBJ ( "termresponse" )); 592 593// libtermkey strips the OSC/DCS bytes from the response. We add it back in 594// so that downstream consumers of v:termresponse can differentiate between 595// the two. 596StringBuilder response = KV_INITIAL_VALUE ; 597switch ( key -> type ) { 598case TERMKEY_TYPE_OSC : 599kv_printf ( response , "\x1b]%s" , str ); 600break; 601case TERMKEY_TYPE_DCS : 602kv_printf ( response , "\x1bP%s" , str ); 603break; 604case TERMKEY_TYPE_APC : 605kv_printf ( response , "\x1b_%s" , str ); 606break; 607default: 608// Key type already checked for OSC/DCS in termkey_interpret_string 609UNREACHABLE ; 610} 611 612ADD_C ( args , STRING_OBJ ( cbuf_as_string ( response . items , response . size ))); 613rpc_send_event ( ui_client_channel_id , "nvim_ui_term_event" , args ); 614kv_destroy ( response ); 615} 616} 617 618/// Handle a Primary Device Attributes (DA1) response from the terminal. 619static void handle_primary_device_attr ( TermInput * input , TermKeyCsiParam * params , size_t nparams ) 620FUNC_ATTR_NONNULL_ALL 621{ 622if ( input -> callbacks . primary_device_attr ) { 623void ( * cb_save )( TUIData * ) = input -> callbacks . primary_device_attr ; 624// Clear the callback before invoking it, as it may set a new callback. #34031 625input -> callbacks . primary_device_attr = NULL ; 626cb_save ( input -> tui_data ); 627} 628 629if ( nparams == 0 ) { 630return; 631} 632 633MAXSIZE_TEMP_ARRAY ( args , 2 ); 634ADD_C ( args , STATIC_CSTR_AS_OBJ ( "termresponse" )); 635 636StringBuilder response = KV_INITIAL_VALUE ; 637kv_concat ( response , "\x1b[?" ); 638 639for ( size_t i = 0 ; i < nparams ; i ++ ) { 640int arg ; 641if ( termkey_interpret_csi_param ( params [ i ], & arg , NULL , NULL ) != TERMKEY_RES_KEY ) { 642goto out ; 643} 644 645kv_printf ( response , "%d" , arg ); 646if ( i < nparams - 1 ) { 647kv_push ( response , ';' ); 648} 649} 650 651kv_push ( response , 'c' ); 652 653ADD_C ( args , STRING_OBJ ( cbuf_as_string ( response . items , response . size ))); 654rpc_send_event ( ui_client_channel_id , "nvim_ui_term_event" , args ); 655out : 656kv_destroy ( response ); 657} 658 659/// Handle a mode report (DECRPM) sequence from the terminal. 660static void handle_modereport ( TermInput * input , const TermKeyKey * key ) 661FUNC_ATTR_NONNULL_ALL 662{ 663int initial ; 664int mode ; 665int value ; 666if ( termkey_interpret_modereport ( input -> tk , key , & initial , & mode , & value ) == TERMKEY_RES_KEY ) { 667( void ) initial ; // Unused 668tui_handle_term_mode ( input -> tui_data , ( TermMode ) mode , ( TermModeState ) value ); 669} 670} 671 672/// Handle a CSI sequence from the terminal that is unrecognized by libtermkey. 673static void handle_unknown_csi ( TermInput * input , const TermKeyKey * key ) 674FUNC_ATTR_NONNULL_ALL 675{ 676// There is no specified limit on the number of parameters a CSI sequence can 677// contain, so just allocate enough space for a large upper bound 678TermKeyCsiParam params [ 16 ]; 679size_t nparams = 16 ; 680unsigned cmd ; 681if ( termkey_interpret_csi ( input -> tk , key , params , & nparams , & cmd ) != TERMKEY_RES_KEY ) { 682return; 683} 684 685uint8_t intermediate = ( cmd >> 16 ) & 0xFF ; 686uint8_t initial = ( cmd >> 8 ) & 0xFF ; 687uint8_t command = cmd & 0xFF ; 688 689switch ( command ) { 690case 'q' : 691if ( initial == '>' && intermediate == ' ' ) { 692// Kitty multiple-cursors protocol query response: 693// CSI > shape;shape;… SP q 694MAXSIZE_TEMP_ARRAY ( args , 2 ); 695ADD_C ( args , STATIC_CSTR_AS_OBJ ( "termresponse" )); 696 697StringBuilder response = KV_INITIAL_VALUE ; 698kv_concat ( response , "\x1b[>" ); 699for ( size_t i = 0 ; i < nparams ; i ++ ) { 700int arg ; 701if ( termkey_interpret_csi_param ( params [ i ], & arg , NULL , NULL ) != TERMKEY_RES_KEY ) { 702kv_destroy ( response ); 703return; 704} 705kv_printf ( response , "%d" , arg ); 706if ( i < nparams - 1 ) { 707kv_push ( response , ';' ); 708} 709} 710kv_concat ( response , " q" ); 711ADD_C ( args , STRING_OBJ ( cbuf_as_string ( response . items , response . size ))); 712 713// Forward to the client (TermResponse). 714rpc_send_event ( ui_client_channel_id , "nvim_ui_term_event" , args ); 715kv_destroy ( response ); 716} 717break; 718case 'u' : 719switch ( initial ) { 720case '?' : 721// Kitty keyboard protocol query response. 722input -> key_encoding = kKeyEncodingKitty ; 723break; 724} 725break; 726case 'c' : 727switch ( initial ) { 728case '?' : 729// Primary Device Attributes (DA1) response 730handle_primary_device_attr ( input , params , nparams ); 731break; 732} 733break; 734case 't' : 735if ( nparams == 5 ) { 736// We only care about the first 3 parameters, and we ignore subparameters 737int args [ 3 ]; 738for ( size_t i = 0 ; i < ARRAY_SIZE ( args ); i ++ ) { 739if ( termkey_interpret_csi_param ( params [ i ], & args [ i ], NULL , NULL ) != TERMKEY_RES_KEY ) { 740return; 741} 742} 743 744if ( args [ 0 ] == 48 ) { 745// In-band resize event (DEC private mode 2048) 746int height_chars = args [ 1 ]; 747int width_chars = args [ 2 ]; 748tui_set_size ( input -> tui_data , width_chars , height_chars ); 749} 750} 751break; 752case 'n' : 753// Device Status Report (DSR) 754if ( nparams == 1 ) { 755// ECMA-48 DSR 756// https://ecma-international.org/wp-content/uploads/ECMA-48_5th_edition_june_1991.pdf 757int arg ; 758if ( termkey_interpret_csi_param ( params [ 0 ], & arg , NULL , NULL ) != TERMKEY_RES_KEY ) { 759return; 760} 761 762MAXSIZE_TEMP_ARRAY ( args , 2 ); 763ADD_C ( args , STATIC_CSTR_AS_OBJ ( "termresponse" )); 764 765StringBuilder response = KV_INITIAL_VALUE ; 766kv_printf ( response , "\x1b[%dn" , arg ); 767ADD_C ( args , STRING_OBJ ( cbuf_as_string ( response . items , response . size ))); 768 769rpc_send_event ( ui_client_channel_id , "nvim_ui_term_event" , args ); 770kv_destroy ( response ); 771} else if ( nparams == 2 ) { 772// Hard to find comprehensive docs on these responses. Some can be found at https://www.xfree86.org/current/ctlseqs.html 773// under "Device Status Report (DSR, DEC-specific)" 774// - Report Printer status 775// - Report User Defined Key status 776// - Report Locator status 777// When the first parameter is 997, it's a theme update response based on 778// contour terminal VT extensions, as described below. 779int args [ 2 ]; 780for ( size_t i = 0 ; i < ARRAY_SIZE ( args ); i ++ ) { 781if ( termkey_interpret_csi_param ( params [ i ], & args [ i ], NULL , NULL ) != TERMKEY_RES_KEY ) { 782return; 783} 784} 785 786if ( args [ 0 ] == 997 ) { 787// Theme update notification 788// https://github.com/contour-terminal/contour/blob/master/docs/vt-extensions/color-palette-update-notifications.md 789// The second argument tells us whether the OS theme is set to light 790// mode or dark mode, but all we care about is the background color of 791// the terminal emulator. We query for that with OSC 11 and the response 792// is handled by the autocommand created in _core/defaults.lua. The terminal 793// may send us multiple notifications all at once so we use a timer to 794// coalesce the queries. 795if ( uv_timer_get_due_in ( & input -> bg_query_timer ) > 0 ) { 796return; 797} 798 799uv_timer_start ( & input -> bg_query_timer , bg_query_timer_cb , 100 , 0 ); 800} 801} 802break; 803default: 804break; 805} 806} 807 808static size_t handle_raw_buffer ( TermInput * input , bool force , const char * data , size_t size ) 809{ 810const char * ptr = data ; 811 812do { 813if (! force ) { 814size_t consumed = handle_focus_event ( input , ptr , size ); 815if ( consumed ) { 816ptr += consumed ; 817size -= consumed ; 818continue; 819} 820 821bool incomplete = false; 822consumed = handle_bracketed_paste ( input , ptr , size , & incomplete ); 823if ( incomplete ) { 824assert ( consumed == 0 ); 825// Wait for the next input, leaving it in the raw buffer due to an 826// incomplete sequence. 827return ( size_t )( ptr - data ); 828} else if ( consumed ) { 829ptr += consumed ; 830size -= consumed ; 831continue; 832} 833} 834 835// 836// Find the next ESC and push everything up to it (excluding), so it will 837// be the first thing encountered on the next iteration. The `handle_*` 838// calls (above) depend on this. 839// 840size_t count = 0 ; 841for ( size_t i = 0 ; i < size ; i ++ ) { 842count = i + 1 ; 843if ( ptr [ i ] == '\x1b' && count > 1 ) { 844count -- ; 845break; 846} 847} 848// Push bytes directly (paste). 849if ( input -> paste ) { 850tinput_enqueue ( input , ptr , count ); 851ptr += count ; 852size -= count ; 853continue; 854} 855 856// Push through libtermkey (translates to "<keycode>" strings, etc.). 857{ 858const size_t to_use = MIN ( count , size ); 859if ( to_use > termkey_get_buffer_remaining ( input -> tk )) { 860// We are processing a very long escape sequence. Increase termkey's 861// internal buffer size. We don't handle out of memory situations so 862// abort if it fails 863const size_t delta = to_use - termkey_get_buffer_remaining ( input -> tk ); 864const size_t bufsize = termkey_get_buffer_size ( input -> tk ); 865if (! termkey_set_buffer_size ( input -> tk , MAX ( bufsize + delta , bufsize * 2 ))) { 866abort (); 867} 868} 869 870size_t consumed = termkey_push_bytes ( input -> tk , ptr , to_use ); 871 872// We resize termkey's buffer when it runs out of space, so this should 873// never happen 874assert ( consumed <= to_use ); 875ptr += consumed ; 876size -= consumed ; 877 878// Process the input buffer now for any keys 879tk_getkeys ( input , false); 880} 881} while ( size ); 882 883const size_t tk_size = termkey_get_buffer_size ( input -> tk ); 884const size_t tk_remaining = termkey_get_buffer_remaining ( input -> tk ); 885const size_t tk_count = tk_size - tk_remaining ; 886if ( tk_count < INPUT_BUFFER_SIZE && tk_size > INPUT_BUFFER_SIZE ) { 887// If the termkey buffer was resized to handle a large input sequence then 888// shrink it back down to its original size. 889if (! termkey_set_buffer_size ( input -> tk , INPUT_BUFFER_SIZE )) { 890abort (); 891} 892} 893 894return ( size_t )( ptr - data ); 895} 896 897static size_t tinput_read_cb ( RStream * stream , const char * buf , size_t count_ , void * data , bool eof ) 898{ 899TermInput * input = data ; 900 901size_t consumed = handle_raw_buffer ( input , false, buf , count_ ); 902tinput_flush ( input ); 903 904if ( eof ) { 905loop_schedule_fast ( & main_loop , event_create ( tinput_done_event , NULL )); 906return consumed ; 907} 908 909// An incomplete sequence was found. Leave it in the raw buffer and wait for 910// the next input. 911if ( consumed < count_ ) { 912// If 'ttimeout' is not set, start the timer with a timeout of 0 to process 913// the next input. 914int64_t ms = input -> ttimeout 915? ( input -> ttimeoutlen >= 0 ? input -> ttimeoutlen : 0 ) : 0 ; 916// Stop the current timer if already running 917uv_timer_stop ( & input -> timer_handle ); 918uv_timer_start ( & input -> timer_handle , tinput_timer_cb , ( uint32_t ) ms , 0 ); 919} 920 921return consumed ; 922}